Xss过滤,只json型数据过滤,图片文件不过滤,采用jsoup

时间:2024-04-04 15:07:40

package com.huaji.fes.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

public XssHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
}

@Override
public String getParameter(String name) {
return clearXss(super.getParameter(name));
}

@Override
public String getHeader(String name) {
return clearXss(super.getHeader(name));
}
@O

verride
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
if (values == null) {
return null;
}
String[] newValues = new String[values.length];
for (int i = 0; i < values.length; i++) {
newValues[i] = clearXss(values[i]);
}
return newValues;
}

/**
* 处理字符转义
* @param value
* @return
*/
private String clearXss(String value) {
if (value == null || "".equals(value)) {
return value;
}
return Jsoup.clean(value, Whitelist.basic());
}
}

自定义过滤器

package com.huaji.fes.filter;

import java.io.IOException;

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 org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.jfinal.kit.StrKit;

public class XssFilter implements Filter {

private CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();

@Override
public void destroy() {

}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
String contentType = request.getContentType();
if (StrKit.notBlank(contentType) && contentType.contains("multipart/form-data")) {// 文件上传请求 *特殊请求
MultipartHttpServletRequest multiReq = multipartResolver.resolveMultipart((HttpServletRequest) request);
request = multiReq;// 将转化后的reuqest赋值到过滤链中的参数 *重要
}
chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response);// 对request和response进行过滤
}

@Override
public void init(FilterConfig arg0) throws ServletException {

}

}