Spring Boot @ResponseBody Jackson-转义所有String字段

时间:2019-04-17 16:09:59

标签: java spring spring-boot jackson jackson-databind

有什么方法可以在Spring Boot中配置Jackson,因此我可以HTML转义@RequestBody中的所有值吗?我曾尝试过使用序列化程序,但据我所知它们是针对特定类定义的。我需要一个过滤器来处理所有在JSON中发送的值,并使用类似以下内容对它们进行转义:

StringEscapeUtils.escapeHtml4(value)

谢谢

1 个答案:

答案 0 :(得分:0)

如何创建XSS过滤器并在RequestInterceptor中调用

public class XSSRequestWrapper extends HttpServletRequestWrapper {

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

/**
 * Get XSS stripped parameter values
 * @param parameter parameter values string to be checked
 * @return xss striped encoded string
 */
@Override
public String[] getParameterValues(String parameter)
{
    String[] values = super.getParameterValues(parameter);
    if(values == null)
    {
        return new String[0];
    }
    int count = values.length;
    String[] encodedValues = new String[count];
    for(int i=0; i<count; i++)
    {
        encodedValues[i]= stripXSS(values[i]);
    }
    return encodedValues;
}

/**
 * Get XSS stripped parameter
 * @param parameter parameter string to be checked
 * @return xss striped encoded string
 */
@Override
public String getParameter(String parameter)
{
    String value = super.getParameter(parameter);
    return stripXSS(value);
}

/**
 * Get XSS stripped header
 * @param name header string to be checked
 * @return xss striped encoded string
 */
@Override
public String getHeader(String name)
{
    String value = super.getHeader(name);
    return stripXSS(value);
}

private String stripXSS(String value)
{
    return HtmlUtils.htmlEscape(value);
}
}

XSS过滤器如下

 @WebFilter(urlPatterns = "/*")
 public class XSSFilter implements Filter {


/**
 * Filter initialization
 * @param filterConfig FilterConfig
*/
@Override
public void init(FilterConfig filterConfig) {
    // nothing required here
}

/**
 * Actual filter implementation
 * @param servletRequest ServletRequest
 * @param servletResponse ServletResponse
 * @param filterChain FilterChain
 * @throws IOException IOException
 * @throws ServletException ServletException
 */
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    filterChain.doFilter(new XSSRequestWrapper((HttpServletRequest) servletRequest), servletResponse);
}

/**
 * Filter destroy
 */
@Override
public void destroy() {
    // nothing required here
}
}