ModelAttribute的使用

ModelAttribute的使用

SessionAttribute注解的value包含对应的key,则会从HttpSession中获取key的value值,否则抛出异常

 

package com.hous.springmvc.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.hous.springmvc.pojo.User;

@Controller
public class ModelAttributeController {
	
	/**
	 * 有@ModelAttribute标记的方法,会在每个目标方法执行之前被SpringMVC调用
	 * @param id
	 * @param map
	 */
	@ModelAttribute
	public void getUser(@RequestParam(value="id", required=false) Integer id,
			Map<String, Object> map) {
		if(id != null) {
			//模拟从数据库中获取模型数据
			User user = new User(101, "hous", "pass1234");
			System.out.println("数据库查询【" + user + "】");
			map.put("user", user);
		}
	}

	@RequestMapping("/testModelAttribute")
	public String testModelAttribute(HttpServletRequest request, 
			@ModelAttribute(value="user") User user){
		System.out.println("修改" + user.toString());
		System.out.println(request.getCharacterEncoding());
		
		return "success";
	}
}

 

猜你喜欢

转载自shuizhongyue.iteye.com/blog/2294967