org.springframework.web.bind.annotation.SessionAttributes注解类型允许我们有选择的指定Model中的哪些属性需要转存到HttpSesion对象中
SessionAttributes注解支持的属性
names–>String[]–> model中属性的名称,即存储在HTTPSession当中的属性名称
value–>String[]–>names属性的名称
types–>Class<\?>[]–>指示参数是否必须绑定
@SeesionAttributes 只能声明在类上,而不能声明在方法上
SessionAttributesController .java
package org.fkit.controller;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
//Controller 用于指定该注解是一个控制器
@Controller
//将model中的属性名为user的属性放入HttpSession对象中
@SessionAttributes("user")
public class SessionAttributesController {
//静态日志类 LogFactory
private static final Log logger = LogFactory.getLog(SessionAttributesController.class);
//该方法映射的请求为http://localhost:8080/项目名称/formName
@RequestMapping(value="/{formname}")
public String loginForm(@PathVariable String formName) {
//动态跳转页面
return formName;
}
//该方法映射的请求为 http://localhost:8080/项目名称/login
@RequestMapping(value="/login")
public String login(
@RequestParam("loginname") String loginname,
@RequestParam("password") String password,
Model model
) {
SMUserVO user = new SMUserVO();
user.setLoginname(loginname);
user.setPassword(password);
user.setUsername("admin");
//将user对象添加到Model对象中
model.addAttribute("user", user);
return "welcome1";
}
}
welcome.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">
<%@ page isELIgnored ="false" %>
<title>Insert title here</title>
</head>
<body>
test
${requestScope.user.loginname}<br>
${sessionScope.user.loginname}<br>
</body>
</html>
loginForm.jsp
<html>
<body>
<h2>Hello World!</h2>
测试@SessionAttribute注解
<form action="login" method="post">
<table>
<tr>
<td><label>登录名:</label></td>
<td><input type="text" id="loginname" name="loginname"></td>
</tr>
<tr>
<td><label>密码:</label></td>
<td><input type="text" id="password" name="password"></td>
</tr>
<tr>
<td><input id="submit" type="submit" value="登录"></td>
</tr>
</table>
</form>
</body>
</html>
@SessionAttributes 还有如下写法
@SeesionAttributes(types={User.class},value="user")
还可以设置多个对象到一个 httpsession当中
@SessionAttributes(types={User.class,Dept.class},value={"user","dept"})
types属性用来指定放入HttpSession当中的对象类型