提供了一下几种途径输出模型数据
1.控制器处理方法的返回值如果为ModelAndView,则其既包含视图信息,也包含模型数据信息。
2.添加模型数据
代码演示:
/**
* 目标方法的返回类型可以是ModelAndView类型
* 其中包含视图信息和模型数据信息
* @return
*/
@RequestMapping("/springMVC/testModelAndView")
public ModelAndView testModelAndView(){
String viewName = "success";
ModelAndView modelAndView = new ModelAndView(viewName);
//放在request域中
modelAndView.addObject("time",new Date().toString());
return modelAndView;
}
//index.jsp页面
<a href="springMVC/testModelAndView">ModelAndViewa>
//success.jsp页面
time:${requestScope.time}
SpringMVC在内部使用了一个 org.springframework.ui.Model接口存储模型数据具体使用步骤
代码演示:
@RequestMapping("/testMap")
public String testMap(Map<String,Object> map){
//【重点】
System.out.println(map.getClass().getName());
//org.springframework.validation.support.BindingAwareModelMap
map.put("names", Arrays.asList("Tom","Jerry","Kite"));
return "success";
}
//index.jsp页面
<a href="springmvc/testMap">testMapa>
//success.jsp页面
names: ${requestScope.names }
若希望在多个请求之间共用某个模型属性数据,则可以在控制器类上标注一@SessionAttributes,SpringMVC将在模型中对应的属性暂存到HttpSession中
@SessionAttributes除了可以通过属性名指定需要放到会话中的属性外,还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中
@SessionAttributes注解源码
package org.springframework.web.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({
ElementType.TYPE}) //说明这个注解只能应用在类型上面
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface SessionAttributes {
String[] value() default {
}; //推荐使用
Class<?>[] types() default {
}; //范围太广
}
代码演示
@Controller
//@SessionAttributes("user")
@SessionAttributes(value={
"user"},types={
String.class})
public class SpringMVCController {
/**
* @SessionAttributes
* 除了可以通过属性名指定需要放到会话中的属性外(实际上是通过value指定key值),
* 还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中(实际上是通过types指定类型)
* 注意:只能放在类的上面,不能修饰方法
*/
@RequestMapping("/testSessionAttributes")
public String testSessionAttributes(Map<String,Object> map){
User user = new User("Tom","123","[email protected]",22);
map.put("user", user);
map.put("school", "atguigu");
//默认是被存放到request 域,如果设置了@SessionAttribute注解,就同时存放到session域中
return "success";
}
}
//index.jsp页面
<a href="testSessionAttributes">testSessionAttributesa>
//success.jap页面
request user : ${requestScope.user } <br><br>
session user : ${sessionScope.user } <br><br>
request school : ${requestScope.school } <br><br>
session school : ${sessionScope.school } <br><br>