@sessionattributes注解应用到Controller上面,能够将Model中的属性同步到session做用域当中。
SessionAttributesController.javahtml
package com.rookie.bigdata; import com.rookie.bigdata.domain.User; 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 // 将Model中的属性名为user的放入HttpSession对象当中 @SessionAttributes("user") public class SessionAttributesController{ private static final Log logger = LogFactory .getLog(SessionAttributesController.class); @RequestMapping(value="/{formName}") public String loginForm(@PathVariable String formName){ // 动态跳转页面 return formName; } @RequestMapping(value="/login") public String login( @RequestParam("loginname") String loginname, @RequestParam("password") String password, Model model ) { // 建立User对象,装载用户信息 User user = new User(); user.setLoginname(loginname); user.setPassword(password); user.setUsername("admin"); // 将user对象添加到Model当中 model.addAttribute("user",user); return "welcome"; } }
loginForm.jspjava
<%@ 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>登陆页面</title> </head> <body> <h3>测试@SessionAttributes注解</h3> <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="password" id="password" name="password"></td> </tr> <tr> <td><input id="submit" type="submit" value="登陆"></td> </tr> </table> </form> </body> </html>
输入用户名和面,点击登陆按钮,请求会被提交到SessionAttributesController中的login方法,该方法将会建立User对象来保存数据,并将其设置到HttpSession做用域当中。web
org.springframework.web.bind.annotation.ModelAttribute注解类型将请求参数绑定到Model对象中。被@ModelAttribute注解的方法会在Controller每一个方法之执行前被执行。
@ModelAttribute注解只支持一个属性value,类型String,表示绑定的属性名称。spring