本文主要是介绍请求过滤器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1,在项目中我们有时需要对每个请求拦截做处理,这时我们就用到了过滤器 Filter
public class TokenFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {// 生成匹配正则,跳过token验证和权限验证的urlskipAuthenticatePattern = fitByList(serviceConfig.getSkipAuthenticateUrls());Filter.super.init(filterConfig);}public void tokenInvalidError(HttpServletResponse response,FilterChain filterChain) throws IOException, ServletException{//ResponseBean responseBean = ResponseBean.builder().code(ExecptionConstant.TOKEN_INVALID_CODE)// .message(ExecptionConstant.TOKEN_INVALID).build();ResponseUtil.out(response,ResponseUtil.resultMap(AppErrEnum.PHONEAREA_NOT_EXIST));}/*** 使用response输出JSON* @param response* @param responseBean*/public static void out(ServletResponse response, ResponseBean responseBean){PrintWriter out = null;try {response.setCharacterEncoding("UTF-8");response.setContentType("application/json");out = response.getWriter();out.println(new Gson().toJson(responseBean));} catch (Exception e) {log.error(e + "输出JSON出错");}finally{if(out!=null){out.flush();out.close();}}}
@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) servletRequest;HttpServletResponse response = (HttpServletResponse) servletResponse;String uri = request.getRequestURI();//OPTIONS直接放行if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {filterChain.doFilter(request, response);return;}if (SLASH.equals(uri)) {response.sendRedirect("/index.html");return;}// token 校验String token = RestUtil.getHeader(request);if(StringUtils.isEmpty(token)){tokenInvalidError( response, filterChain);filterChain.doFilter(request, response);return;}else{String userId = RestUtil.getUserIdByToken(token,serviceConfig.getPmoUrl());if(org.apache.commons.lang3.StringUtils.isEmpty(userId)){tokenInvalidError( response, filterChain);filterChain.doFilter(request, response);return;}else{// 将用户id添加到请求参数中ParameterRequestWrapper wrapper = new ParameterRequestWrapper(request) ;wrapper.addParameter("userId",userId);filterChain.doFilter(wrapper, response);return;}}}
@Overridepublic void destroy() {Filter.super.destroy();}}
有时候我们还需要在请求中添加参数,则可继承HttpServletRequestWrapper
public class ParameterRequestWrapper extends HttpServletRequestWrapper {private Map<String , String[]> params = new HashMap<>() ;public ParameterRequestWrapper(HttpServletRequest request) {super(request);//将参数表,赋予给当前Map以便于持有request中的参数this.params.putAll(request.getParameterMap());}public ParameterRequestWrapper(HttpServletRequest request , Map<String , Object> extendParams){this(request);addAllParameters(extendParams) ;}/*** 重写getParameter方法* @param name 参数名* @return 参数数值*/@Overridepublic String getParameter(String name) {String[] values = params.get(name) ;if (values == null){return null ;}return values[0] ;}@Overridepublic String[] getParameterValues(String name){String[] values = params.get(name) ;if (values == null || values.length == 0){return null ;}return values ;}/*** 在获取所有的参数名,必须重写此方法,* 否则对象中参数值映射不上* @return*/@Overridepublic Enumeration<String> getParameterNames(){return new Vector(params.keySet()).elements() ;}public void addAllParameters(Map<String, Object> extendParams) {for (Map.Entry<String , Object> entry : extendParams.entrySet())addParameter(entry.getKey() , entry.getValue()) ;}public void addParameter(String key, Object value) {if (value != null){if (value instanceof String[])params.put(key , (String[])value) ;else if (value instanceof String)params.put(key , new String[]{(String) value}) ;elseparams.put(key , new String[]{String.valueOf(value)}) ;}}
}
项目中有时需要对输出做统一处理,则可以建立统一处理的返回类
public class ResponseUtil {/*** 使用response输出JSON* @param response* @param resultMap*/public static void out(ServletResponse response, Map<String, Object> resultMap){PrintWriter out = null;try {response.setCharacterEncoding("UTF-8");response.setContentType("application/json");out = response.getWriter();out.println(new Gson().toJson(resultMap));} catch (Exception e) {log.error(e + "输出JSON出错");}finally{if(out!=null){out.flush();out.close();}}}public static Map<String, Object> resultMap(CodeEnum codeEnum){Map<String, Object> resultMap = new HashMap<>(16);resultMap.put("code", codeEnum.getCode());resultMap.put("msg", codeEnum.getMessage());resultMap.put("data","");return resultMap;}public static Map<String, Object> resultMap(boolean flag, Integer code, String msg){Map<String, Object> resultMap = new HashMap<>(16);resultMap.put("code", code);resultMap.put("msg", msg);resultMap.put("data", String.valueOf(flag));
// resultMap.put("timestamp", System.currentTimeMillis());return resultMap;}public static Map<String, Object> resultMap(boolean flag, Integer code, String msg, Object data){Map<String, Object> resultMap = new HashMap<>(16);
// resultMap.put("success", flag);
// resultMap.put("timestamp", System.currentTimeMillis());resultMap.put("code", code);resultMap.put("msg", msg);resultMap.put("data", data);return resultMap;}public static Map<String, Object> resultMap(Integer code, String msg, Object data){Map<String, Object> resultMap = new HashMap<>(16);
// resultMap.put("success", flag);
// resultMap.put("timestamp", System.currentTimeMillis());resultMap.put("code", code);resultMap.put("msg", msg);resultMap.put("data", data);return resultMap;}
}
对于的异常枚举
public enum AppErrEnum implements CodeEnum {PHONEAREA_NOT_EXIST(10048, "区号不存在");public Integer code;public String message;AppErrEnum(Integer code, String message) {this.code = code;this.message = message;}@Overridepublic String getMessage() {return message;}@Overridepublic Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public void setMessage(String message) {this.message = message;}
}
这篇关于请求过滤器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!