SpringBoot – 登录 & 拦截器
一、登录
@Controller
public class LoginController {
@PostMapping(value = "/user/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Map<String,Object> map,
HttpSession session){
//判断用户名是否为空且密码赋值为123456
if(!StringUtils.isEmpty(username) && "123456".equals(password)){
session.setAttribute("loginUser",username);
///main.html:当前目录下的main.html页面
return "redirect:/main.html";
} else {
map.put("msg","用户名或密码错误");
return "login";
}
}
}
登录细节:
-
登录需要有用户名和密码,不为空则转发到主页面,若为空则返回登录页面
-
登录时通过 Httpsession 保存好用户名,方便查看用户的登录状态
session.setAttribute("loginUser",username);
-
为了防止页面重复提交,使用重定向 redirect 转发页面
-
登录错误
1) 显示错误提示,通过 Map<String,Object>集合 去保存错误信息
map.put("msg","用户名或密码错误");
2) 同时在登录页面进行提示:
注意:这一句是在进行判断,当登录错误时这一句才会起作用,代码才显示在页面中,其他情况在网页查看源代码时看不到这一句代码。
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
二、若无登录,则拦截
-
先请求登录时的用户名,通过登录时保存的 session 去获取
request.getSession().getAttribute("loginUser");
-
判断我们请求的用户名是否为空,若为空则进行错误提示并且不能进入到其他页面
注意:这两步的步骤不能颠倒,不能错误提示不会出现在页面上
request.setAttribute("msg","没有权限请先登录"); request.getRequestDispatcher("/index.html").forward(request,response);
-
添加登录拦截器组件
- addPathPatterns("/**"):添加所有页面
- excludePathPatterns("/","/index.html","/user/login"):排除登录页面
@Configuration public class MyConfig implements WebMvcConfigurer { //所有的WebMvcConfigurer组件都会一起起作用 @Bean //将组件注册在容器 public WebMvcConfigurer webMvcConfigurer(){ WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer() { //视图控制器 @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/index.html").setViewName("login"); registry.addViewController("/main.html").setViewName("dashboard"); } //添加拦截器 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/","/index.html","/user/login"); } }; return webMvcConfigurer; } }