LoginIntercepter
@Slf4j
public class LoginIntercepter implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = request.getRequestURI();
log.info("拦截的请求路径是"+requestURI);
HttpSession session = request.getSession();
Object loginUser = session.getAttribute("loginUser");
if (loginUser==null){
//session.setAttribute("msg","请先登录");
request.setAttribute("msg","请先登录");
//response.sendRedirect("/");
request.getRequestDispatcher("/").forward(request,response);
return false;
}else {
return true;
}
}
}
implements WebMvcConfigurer
@Configuration
public class AdminWebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginIntercepter())
.addPathPatterns("/*")
.excludePathPatterns("/","/login");
}
}
页面登录逻辑
@Controller
public class IndexController {
////用于一访问当前项目路径就进入登陆页面(index.html)
//public String loginPage(){
//return
//}@PostMapping("/login")
public String main(User user, HttpSession session, Model model){
if (StringUtils.hasText(user.getUsername())&&"123456".equals(user.getPassword())){
//把登陆成功的用户保存起来
session.setAttribute("loginUser",user.getUsername());
//登陆后重定向到main,防止表单重复提交
return "redirect:/main";
}else {
model.addAttribute("msg","用户名或密码错误");
//回到登陆页面
return "index";
}}
@RequestMapping("/main")
public String mainPage(HttpSession session,Model model){
return "dashboard";
}
}
推荐阅读
- Java|不重启服务进行功能开发
- java|Springboot 一文搞懂AOP面向切面编程
- Spring|Lombok 妙用之@RequiredArgsConstructo注解
- spring|spring boot 集成Kafka配置文件详解
- JavaEE|【Spring Boot】SpringBoot 配置文件详解
- springboot|springboot配置文件详解
- SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍
- 使用idea引入注解@SpringBootApplication报错Cannot resolve symbol 'SpringBootApplication'
- mvn+spring+webapp模板