springboot拦截器判断是否登录
实现拦截器的两个步骤
- 自定义拦截器实现HandlerInterceptor接口
- 创建一个配置类继承WebMvcConfigurerAdapter类并重写addInterceptors方法
代码:
1、自定义拦截器
@Component
public class AdminLoginInterceptor implements HandlerInterceptor {
// 在请求处理之前调用,只有返回true才会执行请求
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
// 得到session
HttpSession session = httpServletRequest.getSession(true);
// 得到对象
Object admin = session.getAttribute("admin");
// 判断对象是否存在
if(admin!=null){
return true;
}else{
// 不存在则跳转到登录页
httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login/adminLogin");
return false;
}
}
// 试图渲染之后执行
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
// 在请求处理之后,视图渲染之前执行
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
2、自定义配置类继承WebMvcConfigurerAdapter
@SpringBootConfiguration
public class AdminLoginAdapter extends WebMvcConfigurerAdapter {
@Autowired
AdminLoginInterceptor adminLoginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/admin
public class LoginInterceptor implements HandlerInterceptor {
private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
// 在请求处理之前,只有返回true才会执行请求
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.info("[拦截器]启动登录状态拦截");
// 得到session
HttpSession session = request.getSession();
logger.info("[拦截器]sessionID:" + session.getId());
// 得到用户信息
Object userInfo = session.getAttribute("userInfo");
//判断用户是否登录
if (userInfo != null) {
logger.info("[拦截器]用户已经登录,用户名,密码:" + session.getAttribute("userInfo"));
return true;
} else {
//不存在跳转至登录页
response.sendRedirect(request.getContextPath() + "/"); // 跳转到首页登录
logger.info("[拦截器]用户没有登录,已跳转到:" + request.getContextPath() + "/");
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 {
}
}
2、继承WebMvcConfigureAdapter类
覆盖其addInterceptors接口,注册自定义的拦截器
@Configuration 注解一定要有
package com.example.demo.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class LoginConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// addPathPatterns 添加路径
// excludePathPatterns 排除路径
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/sys
package com.example.demo.controller;
import com.example.demo.dao.UserDAO;
import com.example.demo.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
public class LoginController {
// 日志
private Logger logger = LoggerFactory.getLogger(LoginController.class);
@Autowired
private UserDAO userDAO;
// 启动服务自动跳转登录
// @RequestMapping(value = {"/", "/login"})
@RequestMapping(value = "/")
public String login() {
return "login";
}
// 登录
@RequestMapping(value = "/loginCheck", method = RequestMethod.POST)
@ResponseBody
public String loginCheck(HttpServletRequest request) {
// 获取登录信息
String userName = request.getParameter("userName");
String password = request.getParameter("password");
// 封装成对象
User user = new User();
user.setUserName(userName);
user.setPassword(password);
// 校验用户信息
User info = userDAO.checkUser(user);
if (info != null) {
request.getSession().setAttribute("userInfo", userName + "-" + password);
logger.info("登录成功,用户名:" + userName + "密码:" + password);
return "success";
} else {
logger.info("登录失败,用户名:" + userName + "密码:" + password);
return "fail";
}
}
}
4、未登录会自动跳转到登录页面
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。