添加攔截其它挺簡單的,直接上代碼吧,我以簡單的登錄驗證攔截爲例java
1,先實現一個攔截器web
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,添加攔截器spring
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"); //注意這裏路徑的匹配,必須以/開頭。 } }
更多文章:http://www.coc88.commvc