創(chuàng)建實體類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中l(wèi)ogin方法用User實體接收參數(shù)
@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