原文:http://liujiajia.me/#/blog/details/spring-filter-request-with-filter
public class CustomizedFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//Do nothing
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// 验证请求
if (!validate(request)) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setCharacterEncoding("UTF-8");
httpResponse.setContentType("application/json;charset=UTF-8");
httpResponse.setStatus(HttpServletResponse.SC_OK);
Result result = new Result();
result.setCode(ErrorCode.UNHANDLEDEXCEPTION); // 错误号
result.setMsg("error message"); // 错误信息
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
httpResponse.getWriter().write(JSONObject.fromObject(result).toString());
return;
}
chain.doFilter(request, response);
}
private boolean validate(ServletRequest request) {
// do some validation
return true;
}
@Override
public void destroy() {
//Do nothing
}
}