package com.curiousby.cn.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.curiousby.cn.constants.Constants; import com.curiousby.cn.one.entity.User; public class LoginAuthInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { User user = (User)request.getSession().getAttribute(Constants.USER); if (null == user) { response.sendRedirect("/SpringBootWebDemo/web/static/forward"); return false; } return true; } @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.curiousby.cn.configurer; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.curiousby.cn.interceptor.LoginAuthInterceptor; @Configuration public class WebAppConfigurer extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginAuthInterceptor()).addPathPatterns("/web/**").excludePathPatterns("/web/static/**"); super.addInterceptors(registry); } //优先级 :META-INFO/resources > resources > static > public @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/img/**").addResourceLocations("classpath:/img/"); super.addResourceHandlers(registry); } }
访问 http://localhost:8080/SpringBootWebDemo/web/users/7
会自动重定向到
http://localhost:8080/SpringBootWebDemo/web/static/forword
拦截器中添加了SpringBootWebDemo 这是我的工程名
server.context-path=/SpringBootWebDemo
也许默认更好点