SpringMVC拦截所有Controller请求,实现⾃定义参数
SpringMVC拦截所有Controller请求,实现⾃定义参数
1.⾃定义参数分解器
重写addArgumentResolvers⽅法⽣产参数分解器
需要实现HandlerMethodArgumentResolver接⼝, supportsParameter⽅法返回的是当前⽅法实例 resolveArgument⽅法返回时对象类型
上代码:
// An highlighted block
@Service
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
@Autowired
private MiaoShaUserService userService;
@Override
public boolean supportsParameter(MethodParameter methodParameter){
Class<?> clazz =    ParameterType();
return clazz == MiaoshaUser.class;
}
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest webReque st, WebDataBinderFactory webDataBinderFactory) throws Exception {
/**
*  threadlocal  线程安全
*/
User();
}
}
2.重写⽅法
需要继承HandlerInterceptorAdapter
需要注意的是三个⽅法: preHandle postHandle afterCompletion
perHandle:执⾏controller⽅法之前调⽤,通常做登录之前的处理,共同⽅法,可以获取⽅法的注解response,request之类postHandle:执⾏controller后,返回modelAndView⽅法,但未进⾏页⾯渲染的时候调⽤。
afterCompletion:服务器端已经执⾏完毕,页⾯渲染完毕后执⾏
上代码:
// An highlighted block
@Service
public class AccessInterceptor  extends HandlerInterceptorAdapter{
private static Logger logger = Logger(AccessInterceptor.class);
@Autowired
MiaoShaUserService userService;
@Autowired
@Autowired
RedisService redisService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
/**
* 获取调⽤获取主要⽅法
*/
if(handler instanceof HandlerMethod){
logger.info("打印拦截⽅法handler :{} ",handler);
HandlerMethod hm =(HandlerMethod)handler;
MiaoshaUser user =getUser(request, response);
UserContext.setUser(user);
AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
if(accessLimit ==null){
return true;
}
int seconds = accessLimit.seconds();
int maxCount = accessLimit.maxCount();
boolean needLogin = dLogin();
String key = RequestURI();
if(needLogin){
if(user ==null){
render(response,SESSION_ERROR);
return false;
}
key +="_"+ Nickname();
}else{
}
AccessKey ak = AccessKey.withExpire(seconds);
Integer count = (ak, key, Integer.class);
if(count  ==null){
redisService.set(ak, key,1);
}else if(count < maxCount){
redisService.incr(ak, key);
}else{
render(response,ACCESS_LIMIT_REACHED);
return false;
}
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { super.afterCompletion(request, response, handler, ex);
}
private void render(HttpServletResponse response, ResultStatus cm)throws Exception {
response.setContentType("application/json;charset=UTF-8");
OutputStream out = OutputStream();
String str  =(cm));
out.Bytes("UTF-8"));
out.flush();
out.close();
}
private MiaoshaUser getUser(HttpServletRequest request, HttpServletResponse response){
String paramToken = Parameter(MiaoShaUserService.COOKIE_NAME_TOKEN);
String cookieToken =getCookieValue(request, MiaoShaUserService.COOKIE_NAME_TOKEN);
if(StringUtils.isEmpty(cookieToken)&& StringUtils.isEmpty(paramToken)){
return null;
}
String token = StringUtils.isEmpty(paramToken)?cookieToken:paramToken;
ByToken(response, token);
}
private String getCookieValue(HttpServletRequest request, String cookiName){
Cookie[]  cookies = Cookies();
if(cookies ==null|| cookies.length <=0){
return null;
}
for(Cookie cookie : cookies){
Name().equals(cookiName)){
Value();
}
}
return null;
}
2.实现WebMvcConfigurer
需要实现两个⽅法
addinterceptors:添加⽅法
addArgumentResolvers:添加参数解调器
上代码:
// An highlighted block
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
UserArgumentResolver resolver;
@Autowired
private AccessInterceptor interceptor;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers){
argumentResolvers.add(resolver);
}
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(interceptor);
}
然后就可以在controllor⽅法⾥写参数调⽤,例如这样:
// An highlighted block
@AccessLimit(seconds =5, maxCount =5, needLogin =true)
@RequestMapping(value="/{path}/do_miaosha", method= RequestMethod.POST)
mvc的controller@ResponseBody
public ResultObject<Integer>miaosha(Model model, MiaoshaUser user, @PathVariable("path") String path,                                        @RequestParam("goodsId") long goodsId){
miaoshaUser就是通过参数解调器实现的。
以上

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。