首页 > 代码库 > java防止脚本注入,通过拦截器实现

java防止脚本注入,通过拦截器实现

1:利用action过滤

package com.tsou.comm.servlet; import java.util.Enumeration;import java.util.Map;import java.util.Vector; import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;/** * * <p class="detail"> * 功能:封装的请求处理特殊字符 * </p> * @ClassName: TsRequest * @version V1.0 * @date 2014年9月25日 * @author wangsheng */public class TsRequest extends HttpServletRequestWrapper {           private Map params;            public TsRequest(HttpServletRequest request, Map newParams) {                    super(request);                    this.params = newParams;          }            public Map getParameterMap() {                    return params ;          }            public Enumeration getParameterNames() {                    Vector l = new Vector( params.keySet());                    return l.elements();          }            public String[] getParameterValues(String name) {                   Object v = params.get(name);                    if (v == null ) {                              return null ;                   } else if (v instanceof String[]) {                             String[] value = (String[]) v;                              for (int i = 0; i < value.length; i++) {                                      value[i] = value[i].replaceAll( "<", "&lt;" );                                      value[i] = value[i].replaceAll( ">", "&gt;" );                             }                              return (String[]) value;                   } else if (v instanceof String) {                             String value = (String) v;                             value = value.replaceAll( "<", "&lt;" );                             value = value.replaceAll( ">", "&gt;" );                              return new String[] { (String) value };                   } else {                              return new String[] { v.toString() };                   }          }            public String getParameter(String name) {                   Object v = params.get(name);                    if (v == null ) {                              return null ;                   } else if (v instanceof String[]) {                             String[] strArr = (String[]) v;                              if (strArr.length > 0) {                                      String value = strArr[0];                                      value = value.replaceAll( "<", "&lt;" );                                      value = value.replaceAll( "<", "&gt;" );                                       return value;                             } else {                                       return null ;                             }                   } else if (v instanceof String) {                             String value = (String) v;                             value = value.replaceAll( "<", "&lt;" );                             value = value.replaceAll( ">", "&gt;" );                              return (String) value;                   } else {                              return v.toString();                   }          }}

 

2:利用拦截器过滤

package com.kadang.wp.mobile.wap.core.common;import java.io.IOException;import java.util.Enumeration;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.lang3.StringUtils;/** * XSS 检查过滤器 *  * @author jianghao * @date 2014-08-22 *  */public class XSSCheckFilter implements Filter {    // 需要拦截的JS字符关键字    private String errorPath;    // 非法xss 字符    private static String[] SAFE_LESS = { "set-cookie", "<", "%3c", "%3e", ">", "\\" };    @Override    public void init(FilterConfig filterConfig) throws ServletException {        this.setErrorPath(filterConfig.getInitParameter("errorPath"));    }    @Override    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,            ServletException {        boolean isSafe = true;        Enumeration<?> params = req.getParameterNames();        HttpServletRequest request = (HttpServletRequest) req;        HttpServletResponse response = (HttpServletResponse) resp;        String requestUrl = request.getRequestURI();        if (isSafeStr(requestUrl)) {            while (params.hasMoreElements()) {                String paramKey = (String) params.nextElement();                String paramValue = request.getParameter(paramKey);                if (StringUtils.isNotBlank(paramValue)) {                    if (!isSafeStr(paramValue)) {                        isSafe = false;                        break;                    }                }            }        } else {            isSafe = false;        }        if (isSafe) {            chain.doFilter(req, resp);        } else {            request.setAttribute("error", "url or params is full of illegal XSS character");            request.getRequestDispatcher(this.getErrorPath()).forward(request, response);            return;        }    }    /**     * 判断URL是否存在非法字符     * */    private boolean isSafeStr(String str) {        if (StringUtils.isNotBlank(str)) {            for (String s : SAFE_LESS) {                if (str.toLowerCase().contains(s)) {                    return false;                }            }        }        return true;    }    @Override    public void destroy() {    }    public String getErrorPath() {        return errorPath;    }    public void setErrorPath(String errorPath) {        this.errorPath = errorPath;    }}

3:利用拦截器拦截URL

<filter>                    <filter-name> characterFilter</filter-name >                     <filter-class> com.tsou.comm.filter.CharacterFilter</filter-class >           </filter>           <filter-mapping>                    <filter-name> characterFilter</filter-name >                    <url-pattern> /*</ url-pattern>           </filter-mapping>

 

java防止脚本注入,通过拦截器实现