servlet過濾器防xss,sql注入.filter裡修改parameter引數
這中間起到最關鍵作用的就是HttpServletRequestWrapper
首先建立一個類繼承HttpServletRequestWrapper。然後重寫getAttribute,getParameter,getParameterValues,getParameterMap這幾個方法。
public class OpRequestWrap extends HttpServletRequestWrapper { public OpRequestWrap(HttpServletRequest request) { super(request); } private String format(String name) { return StringUtils.replaceEach(name,// new String[]{"\"","'","<",">"}, // new String[]{""","´","<",">"}); //return StringEscapeUtils.escapeHtml4(name); } /** * * @param name * @return */ public Object getAttribute(String name) { Object value = super.getAttribute(name); if (value instanceof String) { value = format(String.valueOf(value)); } return value; } /** * 重寫getParameter方法 * * @param name * @return */ public String getParameter(String name) { String value = super.getParameter(name); if (value == null) return null; return format(value); } /** * * @param name * @return */ public String[] getParameterValues(String name) { String[] values = super.getParameterValues(name); if (values != null) { for (int i = 0; i < values.length; i++) { values[i] = format(values[i]); } } return values; } /** * @return */ public Map<String, String[]> getParameterMap() { HashMap<String, String[]> paramMap = (HashMap<String, String[]>) super.getParameterMap(); paramMap = (HashMap<String, String[]>) paramMap.clone(); for (Iterator iterator = paramMap.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<String,String[]> entry = (Map.Entry<String,String[]>) iterator.next(); String [] values = entry.getValue(); for (int i = 0; i < values.length; i++) { if(values[i] instanceof String){ values[i] = format(values[i]); } } entry.setValue(values); } return paramMap; } }
然後配置一個過濾器;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
filterChain.doFilter(new OpRequestWrap((HttpServletRequest) servletRequest),servletResponse);
}
請仔細看doFilter裡面的request,這一步也很重要。它是對request進行包裝,才能起到修改request中引數,屬性的功能。