SpringMVC对Servlet API的支持
我们要保存cookie的时候,没有response是搞不明白的,这时候我们就可以使用到Servlet API。下面举一个登录来看一下,前提是要搭建好springMVC所需要的包及配置文件
写一个user模型
public class User {
private int id;
private String userName;
private String password;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int 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;
}
}
然后再来写一个控制器,这里用注解的方式比传统的配置方式较简单
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/login")
public String login(HttpServletRequest request,HttpServletResponse response){
System.out.println("----登录验证---");
String userName=request.getParameter("userName");
String password=request.getParameter("password");
Cookie cookie=new Cookie("user",userName+"-"+password);
cookie.setMaxAge(1*60*60*24*7);
User currentUser=new User(userName,password);
response.addCookie(cookie);
HttpSession session=request.getSession();
session.setAttribute("currentUser", currentUser);
return "redirect:/main.jsp";
}
}
最后再给出相应的jsp文件,这样一来就放到了session中,这样一个完整的登录已经模拟好了
login.jsp文件
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="user/login.do" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="userName"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td>
<input type="submit" value="登录"/>
</td>
</tr>
</table>
</form>
</body>
</html>
main.jsp文件
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Main.jsp ${currentUser.userName }
</body>
</html>