@SessionAttributes
可以给它配置一个字符串数组,这个数组对应的是数据模型对应的键值对,然后将这些键值对保存到session中。
创建User
package com.po;
public class User {
private String userName;
private String passWord;
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;
}
}
创建UserController
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.po.User;
@Controller
@SessionAttributes(names= {"userName"},types= {User.class})
public class UserController {
@RequestMapping("/getUser")
public ModelAndView getUser(String userName) {
ModelAndView mv=new ModelAndView();
User user=new User();
user.setUserName("baixue");
user.setPassWord("123");
//根据用户名
mv.addObject("userName", userName);
//根据类型
mv.addObject("user", user);
mv.setViewName("success");
return mv;
}
}
创建success.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@page import="com.po.User" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>success</title>
</head>
<body>
<%
String userName=(String)session.getAttribute("userName");
User user=(User)session.getAttribute("user");
%>
<table>
<tr>
<td>用户名:<%=userName %></td>
</tr>
<tr>
<td>用户名:<%=user.getUserName() %></td>
</tr>
<tr>
<td>密码:<%=user.getPassWord() %></td>
</tr>
</table>
</body>
</html>
启动Tomcat并访问控制器