springMVC之@ModelAttribute

用法一:

@Controller
public class BankController
{
	@ModelAttribute
	private void pre()
	{
		System.out.println("我会在每个请求之前执行,相当于before filter");
	}
	
	@RequestMapping(value = "/bank", params = "type=index")
	public String index()
	{
		return "/show";
	}
	
	@RequestMapping(value = "/bank", params = "type=show")
	public String show()
	{
		return "/show";
	}
}

以后只要访问/bank.do?type=index 或/bank.do?type=show

都会执行pre方法


用法二:

@Controller
public class BankController
{
	@ModelAttribute("user")
	private User mock()
	{
		User user = new User();
		user.setId(10012);
		user.setName("李世民");
		user.setDesc("这个user对象会放到model里面去");
		return user;
	}
	
	@RequestMapping(value = "/bank", params = "type=index")
	public String index()
	{
		return "/show";
	}
	
	@RequestMapping(value = "/bank", params = "type=show")
	public String show()
	{
		return "/show";
	}
}

以后只要访问/bank.do?type=index 或/bank.do?type=show

都会执行mock方法,而且把mock方法的返回值放到Model里面去,key=user

然后,在show.jsp页面

<p>${user.id}</p>
<p>${user.name}</p>
<p>${user.desc}</p>

取值

你可能感兴趣的:(springMVC之@ModelAttribute)