index.html (登录页)
<form class="form-signin" th:action="@{/user/login}" method="post">
controller
package com.zoe.customer.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
public class loginController {
@PostMapping("/user/login")
public String test4(String name, String password, Model model, HttpSession httpSession) {
if (name.equals("admin") && password.equals("123")) {
httpSession.setAttribute("session",name);
return "redirect:/main";
}else {
model.addAttribute("msg","账号密码错误");
return "index";
}
}
}
登录成功 session会存储一个string
登录失败 没有session存储任何东西
那么对链接进行拦截,来查看时候存有session
有就放行
没有就跳到首页
拦截器
package com.zoe.customer.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object name = request.getSession().getAttribute("session");
if (name == null) {
System.out.println("未登录");
request.getRequestDispatcher("/").forward(request,response);
return false; //false 不放行
}else {
System.out.println("已登录"+name);
return true; // true 放行
}
}
}
配置类 对静态类文件进行放行
package com.zoe.customer.configuration;
import com.zoe.customer.interceptor.LoginHandlerInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
public class MyConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("main").setViewName("dashboard");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/","/user/login","/static/**");
}
}
网友评论