自定义 Filter 过滤器 和 HttpServletRequestWrapper 实现 request 参数 修改/验证

实现对request中参数去空格功能:
自定义过滤器:实现Filter

@Component
public class TestFilter implements Filter {

public TestFilter() {
}

@Override
public void init(FilterConfig filterConfig) throws ServletException {
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws Exception {
    HttpServletRequest req = (HttpServletRequest) request;
    TestrequestWrapper testRequestWrapper = new TestRequestWrapper(req);
    chain.doFilter(testRequestWrapper ,  response);
}

@Override
public void destroy() {
}

}

继承HttpServletRequestWrapper

public class TestWrapper extends HttpServletRequestWrapper {

private Map params = new HashMap<>();

public TestWrapper(HttpServletRequest request) {
    super(request);
    this.params.putAll(request.getParameterMap());
    this.modifyValues();
}

public void modifyValues() {//将parameter的值去除空格后重写回去
    Set set = params.keySet();
    Iterator iterator = set.iterator();
    while (iterator .hasNext()) {
        String ket = iterator .next();
        String[] values = params.get(key);
        for (int i = 0; i < values.length; i++) {
            values[i] = values[i].trim();
        }
        params.put(key, values);
    }
}

@Override
public Enumeration getParameterNames() {
    return new Vector<>(params.keySet()).elements();
}

@Override
public String getParameter(String name) {
    String[] values = params.get(name);
    if (values == null || values.length == 0) {
        return null;
    }
    return values[0];
}

}

}

你可能感兴趣的:(spring-boot,java)