昨天讲述Day32——国际化,今天学习登录&拦截器
访问登录页面,输入用户名以及密码点击登录,后台验证密码是否正确,若正确则由登录页面进入到主页面。
首先修改登录页面的form表单提交地址th:action="@{/user/login}"
,提交方式注意是post方式,如下:
<form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post">
然后写一个controller方法,控制跳转,如下:
package com.atguigu.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpSession;
import java.util.Map;
/**
* 登录控制器
*/
@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){
if(!StringUtils.isEmpty(username) && "123456".equals(password)){
System.out.println("dashboard");
session.setAttribute("loginUser", username);//保存登录状态,用来判断是否要拦截请求
//防止表单重复提交,重定向到主页
return "redirect:/main.html";
}else{
map.put("msg", "用户名密码错误");
return "login";
}
}
}
在登录页面添加错误信息展示代码,如下:
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}" >p>
定义视图映射,如果登录成功则重定向到main.html(main.html定义视图映射到dashboard.html),如下:
package com.atguigu.springboot.config;
@Configuration
//@EnableWebMvc
public class MyMvcConfig2 implements WebMvcConfigurer {
/**
* 所有的WebMvcConfigurer都会一起起作用
* @return
*/
@Bean //将组件加载进容器中
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
registry.addViewController("/main.html").setViewName("dashboard");
}
}
定义登录拦截器,如下:
package com.atguigu.springboot.component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
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 user = request.getSession().getAttribute("loginUser");
if(user == null){
//未登录
request.setAttribute("msg", "没有权限请先登录");
request.getRequestDispatcher("/index.html").forward(request, response);
return false;
}else{
//已登录,放行
return true;
}
}
@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 {
}
}
注册拦截器,如下:
package com.atguigu.springboot.config;
@Configuration
//@EnableWebMvc
public class MyMvcConfig2 implements WebMvcConfigurer {
/**
* 所有的WebMvcConfigurer都会一起起作用
* @return
*/
@Bean //将组件加载进容器中
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
//注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/asserts/**", "/webjars/**",
"/", "/index.html", "/user/login");
}
};
}
}
在dashboard.html页面设置用户名在左上角显示,如下:
<a class="navbar-brand col-sm-3 col-md-2 mr-0"
href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">
[[ ${session.loginUser} ]]a>
按照上面代码运行如果报错的话,常见有下面2种错误情况。笔者亲自遇到并解决
spring.thymeleaf.cache=false
禁用thymeleaf的缓存功能关于thymeleaf静态资源引用无效
Error resolving template [dashboard], template might not exist or might not be acceible