springMVC数据模型model,modelmap,map,@ModelAttribute的相互关系

结论:

a.注解方法中形参为model,modelmap,map一个或几个时,他们指向的引用对象相同即他们的值相同。

b.当使用@ModelAttribute注解请求参数时,springmvc自动将该参数放入model,modelmap,map中。

c.model,modelmap,map中put,request.setattribute(),b中@ModelAttribute以及modelandveiw.addObj()效果相同,return时都是将参数放request的attribute中。

d.model,modelmap,map,modelandview的生命同期仅存在于当前方法内,forward/return后重新生成新空对象。

e.当使用redirectAttribute.addFlashAttribute重定向时,FlashAttribute会自动注入下一个action内部model,modelmap,map,详细请参考FlashAtrribute详细中的3.2model跟踪。

 

1.发送请求:http://localhost:8080/project/page/login/ModelTest/Map.do?aa=111&bb=333

@Controller
@RequestMapping("/page/login/ModelTest")
public class ModelTestController {
    @RequestMapping(value = "/Map.do")
    public String MapTest(HttpServletRequest request, Map<String, Object> map) {
        System.out.println("hello");
        System.out.println(map);
        map.put("step1", "step1");
        PrintRequestInfo.printSessionAndRequest(request, ModelTestController.class.getName());//打印
        map.put("step2", "step2");
        request.setAttribute("step3", "step3");
        final HttpSession session = request.getSession();
        session.setAttribute("step4", "step4");
        // return "../loginSuccess.jsp";
        return "Map1.do";

    }
}

输出:
hello
{}
================com..controller.ModelTestController====================
print  request parameter:
aa==111
bb==333
print  request attribute:

print  session parameter:
step4==step4

结论:map的初始值为空

 

2.当请求forward到第二个action(Map1.do)中

@RequestMapping(value = "/Map1.do")
    public ModelAndView MapTest1(HttpServletRequest request, @ModelAttribute("aa") String aa,
            Map<String, Object> map, Model model) {
     ModelAndView mav = new ModelAndView(); System.out.println(
"welcome to MapTest1"); model.addAttribute("mdbefore", "before"); System.out.println(map); System.out.println("................"); System.out.println(model.asMap()); model.addAttribute("mdafter", "after"); System.out.println("hello"); System.out.println(map); System.out.println("................"); System.out.println(model.asMap()); PrintRequestInfo.printSessionAndRequest(request, ModelTestController.class.getName() + "1"); mav.addObject("name", "mike");
      mav.setViewName("Map2.do");
      // return "Map2.do";
      return mav;
     //return new ModelAndView("Map2.do","name","mike");//红色部分代码可用这一句代替
}

输出:

welcome to MapTest1
{aa=111, org.springframework.validation.BindingResult.aa=org.springframework.validation.BeanPropertyBindingResult: 0 errors, mdbefore=before}

................//aa由形参@ModelAttribute(“aa”)注入
{aa=111, org.springframework.validation.BindingResult.aa=org.springframework.validation.BeanPropertyBindingResult: 0 errors, mdbefore=before}
hello
{aa=111, org.springframework.validation.BindingResult.aa=org.springframework.validation.BeanPropertyBindingResult: 0 errors, mdbefore=before, mdafter=after}
................
{aa=111, org.springframework.validation.BindingResult.aa=org.springframework.validation.BeanPropertyBindingResult: 0 errors, mdbefore=before, mdafter=after}
================com.controller.ModelTestController1====================
print  request parameter:
aa==111
bb==333
print  request attribute:

step3==step3 //上一个action中map.put加入
step2==step2
step1==step1 //上一个action中request.setattribute加入

print  session parameter:
step4==step4

结论:

a.注解方法中形参为model,modelmap,map一个或几个时,他们指向的引用对象相同即他们的值相同。

b.当使用@ModelAttribute注解请求参数时,springmvc自动将该参数放入model,modelmap,map中。

 

3.当请求进入第三个action(Map2.do)时

@RequestMapping(value = "/Map2.do")
    public String MapTest2(HttpServletRequest request, Map<String, Object> map, Model model,
            ModelMap mm) {
        System.out.println("welcome to MapTest2");
        model.addAttribute("mdbefore2", "before2");
        System.out.println(map);
        System.out.println("................");
        System.out.println(model.asMap());
        System.out.println("................");
        System.out.println(mm);
        model.addAttribute("mdafter2", "after2");

        System.out.println("hello");
        System.out.println(map);
        System.out.println("................");
        System.out.println(model.asMap());

        PrintRequestInfo.printSessionAndRequest(request, ModelTestController.class.getName() + "2");
        return "../loginSuccess.jsp";
    }

输出结果:

welcome to MapTest2
{mdbefore2=before2}
................
{mdbefore2=before2}
................
{mdbefore2=before2}
hello
{mdbefore2=before2, mdafter2=after2}
................
{mdbefore2=before2, mdafter2=after2}
================com.controller.ModelTestController2====================
print  request parameter:
aa==111
bb==333
print  request attribute:

mdbefore==before//由上一个action中model.addAtrribute加入
step3==step3
step2==step2
step1==step1
mdafter==after//由上一个action中model.addAtrribute加入
aa==111 //aa由上一个action形参@ModelAttribute(“aa”)注入

name=mike// name由上一个action中modelAndView.addObject()加入

print  session parameter:
step4==step4

结论:

c.model,modelmap,map中put,request.setattribute(),b中@ModelAttribute以及modelandveiw.addObj()效果相同(可以自己测试),return时都是将参数放request的attribute中。

d.model,modelmap,map,modelandview的生命同期仅存在于当前方法内,forward/return后重新生成新空对象

 

打印方法代码

public class PrintRequestInfo {
    public static void printSessionAndRequest(HttpServletRequest request, String remark) {
        System.out.println("================" + remark + "====================");
        System.out.println("print  request parameter:");
        final Enumeration reqEnum = request.getParameterNames();
        while (reqEnum.hasMoreElements()) {
            final String s = (String) reqEnum.nextElement();
            System.out.println(s + "==" + request.getParameter(s));
        }

        System.out.println("print  request attribute:");
        final Enumeration reqAttrs = request.getAttributeNames();
        while (reqAttrs.hasMoreElements()) {
            final String s = (String) reqAttrs.nextElement();
            System.out.println(s + "==" + request.getAttribute(s));
        }

        System.out.println("print  session parameter:");
        final HttpSession session = request.getSession();
        final Enumeration se = session.getAttributeNames();
        while (se.hasMoreElements()) {
            final String key = (String) se.nextElement();
            System.out.println(key + "==" + session.getAttribute(key));
        }
    }
}

 

 

4.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'login.jsp' starting page</title>
    
      </head>
  
  <body>
   This is webSuc JSP page. <br>
    ${name}<br>
        ${aa}<br>
        <c:out value="Hello World"></c:out>
    ${param.name}<br>
    <%=request.getAttribute("name") %><br>
    ${aa}
    
  </body>
</html>

jsp页面结果:

This is webSuc JSP page. 
     mike
        111
        Hello World
        
    mike
     111

 

转载于:https://www.cnblogs.com/pu20065226/p/10076758.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@ModelAttribute是Spring MVC框架中的一个注解,它主要用于将数据添加到Model对象中,以便在视图页面展示时使用。 @ModelAttribute注解有多种用法,根据注解的位置和其他注解的组合使用,含义也有所不同。在同一个Controller中,标注了@ModelAttribute的方法会在@RequestMapping方法之前被调用,因此对于一个controller映射多个URL的用法来说,需要谨慎使用。一个Controller可以拥有多个@ModelAttribute方法,这些方法都会在@RequestMapping方法之前被调用。 另外,@ModelAttribute注解也可以在@ControllerAdvice标注的类中使用,并且这些@ModelAttribute可以同时对多个控制器生效。 当@ModelAttribute和@RequestMapping同时注解一个方法时,方法的返回值并不表示一个视图名称,而是表示model属性的值。视图名称会由RequestToViewNameTranslator根据请求路径进行转换,而Model属性名称则由@ModelAttribute(value=””)指定。这样,在请求中就会封装了key=attributeName,value=hi的model属性。 总之,@ModelAttribute在Spring MVC中是一个重要的属性,理解好它可以帮助我们更好地使用自动封装等功能。但由于与@RequestMapping组合后会有不同的情况,所以需要注意使用时的状况。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [SpringMVC中的@ModelAttribute注解【详解】](https://blog.csdn.net/weixin_44296929/article/details/116484673)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值