1、过滤器代码(FilterTszf.java)
package filters; import java.io.IOException; import java.util.Iterator; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class FilterTszf implements Filter { public void destroy() { } //拦截器的方法 public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); StringBuffer str = new StringBuffer(""); //需要过滤的特殊字符 String dszf = "'_|_&_;_$_%_@_,_\"_\\\"_\'_\\\'_<_>_(_)_+_CR_LF_\\_and_exec_insert_select_delete_update_count_*_chr_mid_master_truncate_char_declare_or_+_--"; //将特殊字符拆成数组 String dszf_array[] = dszf.split("_"); //拿到页面传过来的键值对,并迭代出所有的键 //request.getParameterMap()得到页面的键值对集合(返回值是map集合) Iterator itr = request.getParameterMap().keySet().iterator(); //根据key拿value值 while (itr.hasNext()) { //每一项value值 String zhi = request.getParameter(itr.next().toString()); if(null != zhi){ //将页面传入的值拼接 str.append(zhi.toString()); str.append("_"); } } System.out.println(str); //将页面字符与所有特殊字符比对 for(int i = 0; i < dszf_array.length; i++){ if(str.toString().indexOf(dszf_array[i]) >= 0){ //含有非法,跳转到错误页面 RequestDispatcher dispatcher = request.getRequestDispatcher("/error.jsp"); dispatcher .forward(request,response); return; } } //不含特殊字符正常跳转 chain.doFilter(request,response); return; } public void init(FilterConfig filterConfig) throws ServletException { } }
?
2、登入输入页面(dengRu.jsp)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>测试登录</title> </head> <body> <form action="huangYi.jsp" enctype="multipart/form-data"> <input type="text" name="name" id="name" /> <input type="text" name="password" id="password" /> <select name="yyyy"> <option>你好</option> <option>\"</option> <option>and</option> <option>select</option> </select> <input type="file" name="fileAdder" id="fileAdder" value="上传"/> <input type="submit" value="登入"/> </form> </body> </html>
?
3、web.xml配置
<!-- 过滤器 --> <filter> <filter-name>first </filter-name> <filter-class>filters.FilterTszf </filter-class> <init-param> <param-name>encoding</param-name> <param-value>GBK</param-value> </init-param> </filter> <filter-mapping> <filter-name>first </filter-name> <!--/*表示拦截所有--> <url-pattern>/* </url-pattern> </filter-mapping>
?