码迷,mamicode.com
首页 > 编程语言 > 详细

springmvc学习第二天

时间:2015-08-10 16:08:02      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

一、pojo

Spring mvc 会按请求参数名和pojo属性名进行自动匹配,自动为该对象填充属性值,并且支持级联属性

表单:

<form action="springmvc/testPojo" method="post">
username: <input type="text" name="username"/>
<br>
password: <input type="password" name="password"/>
<br>
email: <input type="text" name="email"/>
<br>
age: <input type="text" name="age"/>
<br>
city: <input type="text" name="address.city"/>
<br>
province: <input type="text" name="address.province"/>
<br>
<input type="submit" value="Submit"/>
</form>

pojo:

User类

private Integer id;

private String username;
private String password;

private String email;
private int age;

private Address address;

Address类

private String province;
private String city;

@RequestMapping("/testPojo")
public String testPojo(User user) {
System.out.println("testPojo: " + user);
return SUCCESS;
}

二、servlet API

Spring mvc 还支持原生的servlet API

可以使用servlet原生的API作为目标方法的参数 具体支持以下类型

HttpServletRequest
HttpServletResponse
HttpSession
java.security.Principal
Locale InputStream
OutputStream
Reader
Writer

@RequestMapping("/testServletAPI")
public void testServletAPI(HttpServletRequest request,
HttpServletResponse response) throws IOException {
System.out.println("testServletAPI, " + request + ", " + response);
return "success";
}

三、spring mvc 处理模型数据之ModelAndView

目标方法的返回值可以使ModelAndView类型。

其中可以包含视图和模型信息

spring mvc会把ModelAndView的model中数据放到request域对象中

@RequestMapping(value="/testModelAndView")
public ModelAndView testModelAndView(){
String viewName= "success";
ModelAndView modelAndView = new ModelAndView(viewName);
modelAndView.addObject("time",new Date());
return modelAndView;

}

jsp页面取值:time:${requestScope.time}

四、spring mvc处理模型数据之Model

目标方法可以添加Map类型(实际上也可以是Model类型或者ModelMap类型的)的参数

@RequestMapping("/testMap")
public String testMap(Map<String, Object> map){
System.out.println(map.getClass().getName());
map.put("names", Arrays.asList("Tom", "Jerry", "Mike"));
return SUCCESS;
}

取值:names: ${requestScope.names }

与ModelAndView的关系是,Map类型也会转化成ModelAndView类型,其中Map中的值存放到ModelAndView的modelMap中,而方法的返回值放在了ModelAndView的viewName中

五、SessionAttributes注解

除了可以通过属性名指定需要放到会话中的属性外(实际上使用的是 value 属性值),还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中(实际上使用的是 types 属性值)

@SessionAttributes(value={"user"}, types={String.class})

注意: 该注解只能放在类的上面. 而不能修饰方法. 

六、ModelAttribute注解

 

springmvc学习第二天

标签:

原文地址:http://www.cnblogs.com/yydeyi/p/4718267.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!