1.在项目中的WEB-INF目录下建立一个properties文件,文件名随意,我的是str.properties如图
2.str.properties里面添加name是要被和谐的字符,value是和谐后应该显示的字符如:
?3.贴上过滤器代码:
class="java" name="code">package com.filter; import java.io.IOException; import java.io.InputStream; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Properties; // java中用于读写 properties 文件的工具类 public class StrFilter implements Filter{ private Properties pro =null; public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest hrequest = (HttpServletRequest)request; HttpServletResponse hresponse = (HttpServletResponse)response; java.util.Enumeration names= hrequest.getParameterNames(); while(names.hasMoreElements()){ String name = names.nextElement().toString(); String values[] = request.getParameterValues(name); for(int i = 0;i<values.length;i++){ if(pro.getProperty(values[i])!=null){ values[i]=pro.getProperty(values[i]); //将不雅字符替换为配置文件中对应的值 } } } //实现模糊匹配? chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub //加载Properties文件 pro = new Properties(); //1.获得ServletContext ServletContext context = filterConfig.getServletContext(); //2.获得WEB-inf下配置文件的内容 IO 流 InputStream is= context.getResourceAsStream("/WEB-INF/str.properties"); //3.加载配置文件 try { pro.load(is); //循环获取配置文件里所有的内容 java.util.Enumeration names= pro.propertyNames(); while(names.hasMoreElements()){ String name = names.nextElement().toString(); String value= pro.getProperty(name); System.out.println(name+" "+value); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
?
4.web.xml中配置
<filter> <filter-name>StrFilter</filter-name> <filter-class>com.filter.StrFilter</filter-class> </filter> <filter-mapping> <filter-name>StrFilter</filter-name> <url-pattern>*</url-pattern> </filter-mapping>
?
?