filter的一个应用举例
网上的一些文本框和文本域都有良好的过滤作用,防止恶意的攻击。那么,我们平时的项目中到底有没有想到我们的表单里的文本会不会安全呢?
当然,我们可以可以采用filter进行字符的替换来解决这些问题,首先,
我们首先要写一个filter类,代码如下:
//新建一个Myfilter类实现Filter的接口 public class Myfilter implements Filter{private FilterConfig config;private String encode;public void destroy() {config = null;encode = null;}public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain) throws IOException, ServletException {req.setCharacterEncoding(encode);chain.doFilter(new MyWrapper((HttpServletRequest)req),resp);}public void init(FilterConfig config) throws ServletException {this.config = config;encode = config.getInitParameter("encode");if(encode == null){ //设置字符为UTF-8encode = "UTF-8";}}}
//也是创建一个类MyWrapper继承HttpServletRequestWrapperpublic class MyWrapper extends HttpServletRequestWrapper{ public MyWrapper(HttpServletRequest request) {super(request);}public String getParameter(String name) {String value = super.getParameter(name);value = value.replaceAll("<","<").replaceAll("//","&").replaceAll(">",">").replace(" "," ");return value;}}