@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