拦截器,return true 是放行
package com.jay.interceptors; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception { //拦截前 String url = request.getRequestURL().toString(); if (url.contains("login")) { return true; } HttpSession session = request.getSession(); String name = (String) session.getAttribute("username"); System.out.println(name); if (name != null) { return true; } else { 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 { //清理前 } }
在Spring xml中配置拦截器 /** 是拦截所有请求
<!--拦截器--> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.jay.interceptors.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors>
在SpringBoot中配置拦截器,在自定义解析器中
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**") .excludePathPatterns("/index","/login","/css/**","/js/**","/img/**"); }
视图解析器
package com.jay.SpringBootStudy8.config; 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.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MyMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { //设置视图请求地址,相当于 @RequestMapping("/a") // registry.addViewController("/a").setViewName("views/sysuser/index"); // registry.addViewController("/index.html").setViewName("index"); } @Bean public LocaleResolver localeResolver(){ return new MyLocaleResolver(); } @Override public void addInterceptors(InterceptorRegistry registry) { // registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**") // .excludePathPatterns("/index","/login","/css/**","/js/**","/img/**"); } }