springboot隨筆五:新增Interceptor,Filter,Servlet
阿新 • • 發佈:2020-12-22
一:新增攔截器:實現HandlerInterceptor介面,並在由配置類(有@Configuration註解)加入該interceptor,並設定攔截路徑
package com.wzp.interceptor; import com.wzp.domain.User; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; public class LoginHandlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("intercept url:" + request.getRequestURL()); System.out.println("intercept uri:" + request.getRequestURI()); User user = (User) request.getSession().getAttribute("user"); if (null != user) { return true; } request.setAttribute("flag", "error"); request.getRequestDispatcher("/login").forward(request, response);return false; } @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 { } }
package com.wzp.config; import com.wzp.interceptor.LoginHandlerInterceptor; import com.wzp.resolver.MyLocaleResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration //@EnableWebMvc// 如果配置了這個,springboot的webMvc將不會自動裝配,也就是說springboot給我們的預設很多web功能將失效,完全有自己接管 public class MyConfig implements WebMvcConfigurer {// 通過實現WebMvcConfigurer來在原來springboot自動化的基礎上進行擴充套件 // 新增攔截器 @Override public void addInterceptors(InterceptorRegistry registry) { // 除了去登入頁面,其他請求全部攔截 registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/", "/index", "/index.html", "/", "/login", "/login.html", "/user/login", "/images/*", "/webjars/**"); } }