创建实体类User
package com.xbb.springboot.tutorial.entity;
import java.sql.Date;
public class User {
private String id;
private String username;
private String password;
private Date birthday;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
修改LoginController中login方法用User实体接收参数
@RequestMapping("login")
public ModelAndView login(HttpServletRequest request, User user) {
ModelAndView mav = new ModelAndView();
if ("admin".equals(user.getUsername()) && "666666".equals(user.getPassword())) {
request.getSession().setAttribute("user", user);
mav.setViewName("redirect:/view/index");//客户端跳转
return mav;
} else {
mav.addObject("errorMsg", "用户名或密码有误");
mav.setViewName("login");//服务器跳转
return mav;
}
}
修改index.html获取用户信息
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
${user.username}<br/>
${user.password}
</body>
</html>
修改LoginInterceptor中preHandle方法
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
User user = (User)request.getSession().getAttribute("user");
if (user == null) {
response.sendRedirect("/view/login");
return false;
}
return true;
}
重新登录
http://localhost:8080/view/login