springmvc 注解二

@SessionAttributes

@sessionattributes注解应用到Controller上面,可以将Model中的属性同步到session作用域当中。
SessionAttributesController.java

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.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>登录页面</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作用域当中。

@ModelAttribute注解

org.springframework.web.bind.annotation.ModelAttribute注解类型将请求参数绑定到Model对象中。被@ModelAttribute注解的方法会在Controller每个方法之执行前被执行。
@ModelAttribute注解只支持一个属性value,类型String,表示绑定的属性名称。

原文地址:https://www.cnblogs.com/haizhilangzi/p/11028869.html