Springboot项目使用拦截器方法详解
1.创建一个拦截器并实现HandlerInterceptor接口
packagecom.leiyuan.bs.interceptor; importorg.springframework.web.servlet.HandlerInterceptor; importorg.springframework.web.servlet.ModelAndView; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; //拦截器 publicclassMyHandlerInterceptorimplementsHandlerInterceptor{ /** *拦截(Controller方法调用之前) * *@paramrequestrequest *@paramresponseresponse *@paramoo *@return通过与否 *@throwsException异常处理 */ @Override publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Object o)throwsException{ //TODO我这里是通过用户是否登陆进行拦截,我的用户信息存储在session中,名称为userSession,大家可以自行实现 if(request.getSession().getAttribute("userSession")==null){ //拦截至登陆页面 request.getRequestDispatcher("/user/toLogin").forward(request,response); //false为不通过 returnfalse; } //true为通过 returntrue; } //此方法为处理请求之后调用(调用过controller方法之后,跳转视图之前) @Override publicvoidpostHandle(HttpServletRequesthttpServletRequest,HttpServletResponsehttpServletResponse,Objecto, ModelAndViewmodelAndView)throwsException{ } //此方法为整个请求结束之后进行调用 @Override publicvoidafterCompletion(HttpServletRequesthttpServletRequest,HttpServletResponsehttpServletResponse, Objecto,Exceptione)throwsException{ } }
2.创建一个配置类MyHandlerInterceptorConfig并继承WebMvcConfigurerAdapter类重写addInterceptors(InterceptorRegistryregistry)方法
packagecom.leiyuan.bs; importcom.leiyuan.bs.interceptor.MyHandlerInterceptor; importorg.springframework.stereotype.Component; importorg.springframework.web.servlet.config.annotation.InterceptorRegistry; importorg.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; //拦截器配置类 @Component publicclassMyHandlerInterceptorConfigextendsWebMvcConfigurerAdapter{ @Override publicvoidaddInterceptors(InterceptorRegistryregistry){ /** *这里的addPathPatterns("/**")为配置需要拦截的方法“/**”代表所有,而后excludePathPatterns("/user/toLogin")等方法为排除哪些方法不进行 拦截 */ registry.addInterceptor(newMyHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/toLogin").excludePathPatterns ("/user/login").excludePathPatterns("/user/toNewUser").excludePathPatterns("/user/newUser"); super.addInterceptors(registry); } }
3.启动项目即可看到效果了
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。