SpringMVC笔记第四篇<源码分析>--数据在域中的保存(重点章节)

1.request对象中保存数据

@Controller
public class ScopeController {

    @RequestMapping(value = "/requestScope")
    public String requestScope(HttpServletRequest request){
        System.out.println(" requestScope() 方法调用了 ");
        // 往Request域中保存数据
        request.setAttribute("reqKey1", "reqValue1");
        request.setAttribute("reqKey2", "reqValue2");
        return "ok";
    }

}

jsp页面的输出:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    请求成功!!! <br/>
    <br/>
    request域中的 reqKey1 数据 => ${ requestScope.reqKey1 } <br/>
    request域中的 reqKey2 数据 => ${ requestScope.reqKey2 } <br/>

</body>
</html>
  1. Session域中保存数据

Controller层:

@RequestMapping(value = "/sessionScope")
public String sessionScope(HttpSession session){
    System.out.println(" sessionScope() 方法调用了 ");
    // 往 HttpSession 域中保存数据
    session.setAttribute("sessionKey1", "sessionValue1");
    session.setAttribute("sessionKey2", "sessionValue2");

    return "ok";
}

3.ServletContext域中保存数据

在Controller中的代码。在Controller的中获取SerlvetContext对象有两种方法。

一种是@Autowired注入,

@Autowired
ServletContext servletContext;

@RequestMapping(value = "/servletContextScope")
public String servletContextScope(){
    System.out.println(" servletContextScope() 方法调用了 ");
    // 往 servletContext域中保存数据
    servletContext.setAttribute("servletContextKey1", "servletContextValue1");
    servletContext.setAttribute("servletContextKey2", "servletContextValue2");

    return "ok";
}

二种是通过Session获取

@RequestMapping(value = "/servletContextScope")
public String servletContextScope(HttpSession session){
    System.out.println(" servletContextScope() 方法调用了 ");
	//获取SerlvetContext对象
    ServletContext servletContext = session.getServletContext();

    // 往 servletContext域中保存数据
    servletContext.setAttribute("servletContextKey1", "servletContextValue1");
    servletContext.setAttribute("servletContextKey2", "servletContextValue2");

    return "ok";
}

注:
servletContext 对应–> applicationScope
request 对应–> requestScope
response 对应–> responseScope

4. 以Map或Model或ModelMap形式保存数据在request域中

其实三者功能都是一模一样!!!一般选Model使用能减少代码量

在四个域中,我们使用最频繁的域就是request对象。往request域对象中,保存数据,还在以下的几种形式。
我们可以在Controller的方法中,添加Map类型的参数,或者是Model类型的参数。或者是ModelMap类型的参数。都可以直接用来保存域数据到Request对象中。

Map全类名是: java.util.Map

@RequestMapping(value = "/mapToRequest")
public String mapToRequest(Map<String,Object> map){
    System.out.println(" mapToRequest() 方法调用了 ");
    // 我们把数据保存到Map中,这些数据也会自动的保存到Reqeust域中.
    map.put("mapKey1", "mapValue1");
    map.put("mapKey2", "mapValue2");

    return "ok";
}

Model全类名是: org.springframework.ui.Model

@RequestMapping(value = "/modelToRequest")
public String modelToRequest(Model model){

    System.out.println(" modelToRequest() 方法调用了 ");
    // 我们把数据保存到 model 中,这些数据也会自动的保存到Reqeust域中.
    model.addAttribute("modelKey1", "modelValue1");
    model.addAttribute("modelKey2", "modelValue2");

    return "ok";
}

ModelMap全类名是: org.springframework.ui.ModelMap

@RequestMapping(value = "/modelMapToRequest")
public String modelMapToRequest(ModelMap modelMap){

    System.out.println(" modelMapToRequest() 方法调用了 ");
    
    // 我们把数据保存到 model 中,这些数据也会自动的保存到Reqeust域中.
    modelMap.addAttribute("modelMapKey1", "modelMapValue1");
    modelMap.addAttribute("modelMapKey2", "modelMapValue2");

    return "ok";
}

源码解析
隐含模型对象 :

* 不管你是Map,还是Model,还是ModelMap,他们都是 BindingAwareModelMap 类 <br/>
     * class org.springframework.validation.support.BindingAwareModelMap <br/>
     *                                  /\
     *                                  ||
     *                                  ||
     *           BindingAwareModelMap extends ExtendedModelMap
     *                                  /\
     *                                  ||
     *                                  ||
     *           ExtendedModelMap extends ModelMap implements Model
     *                                  /\
     *                                  ||
     *                                  ||
     *              ModelMap extends LinkedHashMap<String, Object>
     *
     *
     *   BindingAwareModelMap 类在SpringMVC中是隐含模型对象!!! 
     *   BindingAwareModelMap 隐含模型中一般都用来保存 视图渲染时 需要的数据 
     *   视图         就是页面 (比如 jsp页面 )
     *   渲染         执行,显示
     */
    @RequestMapping(value = "/mapAndModelAndModelMap")
    public String mapAndModelAndModelMap( Map map , Model model , ModelMap modelMap ){
//        org.springframework.validation.support.BindingAwareModelMap
        System.out.println( map );
        System.out.println( model );
        System.out.println( modelMap );
        System.out.println(" 最美分隔线================================== ");

        map.put("mapKey1", "mapValue1");

        System.out.println( map );
        System.out.println( model );
        System.out.println( modelMap );
        System.out.println(" 最美分隔线================================== ");

        model.addAttribute("modelKey1", "modelValue1");
        System.out.println( map );
        System.out.println( model );
        System.out.println( modelMap );
        System.out.println(" 最美分隔线================================== ");

        modelMap.addAttribute("modelMapKey1", "modelMapValue1");
        System.out.println( map );
        System.out.println( model );
        System.out.println( modelMap );

        System.out.println(" 最美分隔线================================== ");
        System.out.println( map.getClass() );
        System.out.println( model.getClass() );
        System.out.println( modelMap.getClass() );

        return "ok";
    }

5. ModelAndView方式保存数据到request域中

@RequestMapping(value = "/modelAndViewToReqeust")
public ModelAndView modelAndViewToReqeust(){
    ModelAndView modelAndView = new ModelAndView("ok");

    //使用 ModelAndView 返回值保存数据到 Reqeuat 域中
    modelAndView.addObject("mavKey1", "mavValue1");
    modelAndView.addObject("mavKey2", "mavValue2");

    return modelAndView;
}
  1. @SessionAttributes注解作用:保存数据到Session域中
    了解内容

@SessionAttributes 注解可以标注在类上。它的作用是:指定隐含模型中哪些数据可以保存到Session域中。

@SessionAttributes(value = { “key1”,“key2” }, types = { String.class, Book.class })
value属性,它表示把request域中key为key1,key2的键值对信息,也保存到Session中
types属性,它表示把request域中value类型为String.class或Book.class类型的键值对,也保存到Session中

注: 如果 指定多个值时,用大括号包起来!!!

/**
 * @SessionAttributes 可以指定哪些隐含模型中的数据也同步保存到Session域中 
 *  names   属性设置哪些 key 数据保存到Session中 <br/>
 *  types   属性设置哪些类型的 value 属性也同步到Session中 <br/>
 */
// @SessionAttributes(value = { "key1","key2" } , types = { String.class, Book.class })

@SessionAttributes(types = {Integer.class,String.class})
@Controller
public class ScopeController {

    @RequestMapping(value = "/sessionAttrubute")
    public String sessionAttrubute(Map<String,Object> map){
        System.out.println(" sessionAttrubute() 方法调用了 ");
        // 我们把数据保存到Map中,这些数据也会自动的保存到Reqeust域中.
        map.put("mapKey1", "字符串类型");
        map.put("mapKey2", new Integer(100));

        return "ok";
    }
}
  1. @ModelAttribute注解

@ModelAttribute这个注解可以标注在方法和参数上。
@ModelAttribute三个常见作用:
1、被标注了@ModelAttribute的方法都会在Controller的目标方法之前执行。
2、目标方法的参数(JavaBean对象)会先从隐含模型中获取值传入。( 如果在客户端地址栏输入或表单提交的信息参数会覆盖掉隐含模型中的值 )
3、被标注在参数上,参数值会按照指定的key从隐含模型中获取值。

@ModelAttribute
public void modelAttributeFun( Map<String,Object> map ){
    // 可以为目标方法准备数据
    System.out.println(" modelAttributeFun() 方法被调用了 ");
    map.put("book1",new Book(100,"国哥,为什么你这么帅,帅的不要不要的!"));
}

传值原理:
		目标方法的参数,如果是JavaBean,SpringMVC会先把这个参数的类型,这里是Book类型,
		然后取类名Book,然后首字母小写为book.再到隐含模型中找看看有没有key值为book的值传入,
		如果找到隐含模型中的有key对应上这里的book,那么就会把隐含模型中对应key的value值,
		传给目标方法作为参数,如果没有对应上的key,那么就为null。
		
@ModelAttribute("book1") 表示 按照 book1 去隐含模型中查找key,
找到就注入,找不到就返回null。如果有在表单或浏览器栏输入的值,就会覆盖掉隐含模型中的值。

@RequestMapping(value = "/target")
public String target( @ModelAttribute("book1") Book book){
    System.out.println(" target() 方法调用了 =====>>>> " + book);
    return "ok";
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://JAVA.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>springMVC</display-name> <welcome-file-list> <welcome-file>/WEB-INF/jsp/login.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext-mybatis.xml</param-value> </context-param> <filter> <filter-name>encodingFilter</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <param-name>webAppRootKey</param-name> <param-value>keshe_C12_09.root</param-value> </context-param> <listener> <listener-class> org.springframework.web.util.Log4jConfigListener </listener-class> </listener> </web-app>
最新发布
07-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值