添加拦截其它挺简单的,直接上代码吧,我以简单的登陆验证拦截为例
1,先实现一个拦截器
package com.xinyue.interview.gm.filter;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;/** * * @ClassName: LoginFilter * @Description: 登陆拦截 * @author: wgs QQ群:66728073,197321069,398808948 * @date: 2018年10月26日 下午3:03:48 */public class LoginFilter implements HandlerInterceptor { public static String SESSION_USER = "USER"; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println(request.getRequestURI()); Object value = request.getSession(true).getAttribute(SESSION_USER); return value != null; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }}
2,添加拦截器
package com.xinyue.interview;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import com.xinyue.interview.gm.filter.LoginFilter;/** * * @ClassName: WebMvcConfig * @Description: webmvc的相关配置实现,可以添加拦截器 * @author: wgs QQ群:66728073,197321069,398808948 * @date: 2018年10月26日 下午3:13:46 */@Configuration //这里的@Configuration注解必须有,要不然这个类不起做用,网上有的文章没有这个注解,拦截器不起作用,让我查了半天public class WebMvcConfig extends WebMvcConfigurerAdapter { @Bean //这里的@Bean是向spring注入拦截器的实例,可以写到别的类里面,这样写的好处,如果LoginFilter里面有对其它实例的依赖,spring会帮你自动注入。 public LoginFilter getLoginFilter() { return new LoginFilter(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(getLoginFilter()).addPathPatterns("/gm/**.gm"); //注意这里路径的匹配,必须以/开头。 }}
更多文章: