【Spring】使用Filter过滤请求
2017-08-22 10:12 佳佳的博客 阅读(559) 评论(0) 编辑 收藏 举报原文: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
}
}
转载请标明原文出处 【liujiajia.me】 !