上节讲过了登录后将信息存储于session中,但是如何做鉴权页的登录检测呢?这一节讲到spring boot的拦截器
您可以在以下情况下使用SpringBoot中的Interceptor来执行操作
以下是在使用拦截器时应了解的三种方法:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration //@EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/ucenter/*"); } } 复制代码
这里对路径以ucenter开头的进行SecurityInterceptor处理
import com.google.gson.Gson; import com.vison.learnMall.Response; import com.vison.learnMall.ResponseRet; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.HandlerInterceptor; /** * * */ public class SecurityInterceptor implements HandlerInterceptor { private Logger logger = LoggerFactory.getLogger(this.getClass()); public SecurityInterceptor() { } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // logger.debug(request.getSession().getAttribute(App.SESSION_USER).toString()); if (request.getSession().getAttribute(App.SESSION_USER) != null) { return true; } if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) { PrintWriter writer = null; response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); writer = response.getWriter(); Gson gson = new Gson(); String jsonObject = gson.toJson(new Response(ResponseRet.unLogin, "未登录")); writer.print(jsonObject); return false; } //未登录的业务逻辑 response.sendRedirect("/login"); return false; } } 复制代码