【问题标题】:How SpringMVC @SessionAttributes sends session object to JSPSpringMVC @SessionAttributes 如何将会话对象发送到 JSP
【发布时间】:2016-10-26 01:46:55
【问题描述】:

我正在学习 SpringMVC 框架,我从here 获得了以下示例。 Java 控制器:

SessionController.java

package javabeat.net.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@RequestMapping("/sessiontest")
@SessionAttributes("sessionValue")
public class SessionController {
    @RequestMapping(method = RequestMethod.GET)
    public String getForm(@RequestParam("param") String paramVal, ModelMap map){
        System.out.println("Param Value : " + paramVal);
        map.addAttribute("sessionValue", "Test Object");
        return "hello";
    }

}

JSP 页面:

hello.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<%
    String value = (String)session.getAttribute("sessionValue");
    out.print(value);
%>
</body>
</html>

我正在尝试了解执行流程:

据我所知,它假定在执行流程中 URL /sessiontest?param=paramVal 将首先被命中。然后paramVal 被筛选到控制台。然后集合map 被键值对"sessionValue"/"Test Object" 丰富。然后返回"hello"。所以当hello.jsp被点击时,它会检索刚刚添加的值,并且html正文会屏蔽Test Object

如果我的上述解释是正确的,我想知道:

1) 谁将ModelMap map 对象传递给getForm 方法?

2) 将hello 退回到无处的目的是什么?

3) JSP 中的session 对象如何与添加新键值对的ModelMap map 绑定?

【问题讨论】:

    标签: html spring jsp spring-mvc web-applications


    【解决方案1】:

    我想我不太擅长解释事情,因为我的话很笨拙。 但事情是这样的:

    1) 谁将 ModelMap 地图对象传递给 getForm 方法?

    Spring 容器生成这个模型对象并(在幕后)调用它作为方法的参数,它的工作方式就像 JSP 隐式对象(requestresponse, .etc),其中 JSP Container 使它们在每个页面中都可用,并且可以直接调用这些对象而无需显式声明。

    ModelMap 用于包装一些属性(键和值),以便您可以将这些值传递给方法返回的视图。所以稍后,您可以通过相应的键在视图中访问这些值。

    2)。回你好无处的目的是什么?

    hello 是从方法转发的视图名称 (hello.jsp),您可以在其中访问地图中先前包装的属性

    3) JSP 中的会话对象如何与 ModelMap 映射绑定,其中 正在添加新的键值对?

    Spring 的 @SessionAttributes 用于控制器上指定哪些模型属性(将这些属性视为包装在映射中的键和值)应存储在会话中。

    简单的解释:由于这个控制器是用 @SessionAttributes("sessionValue") 注释的,所以每当一个地图包装一个用“sessionValue”键映射的值时,这个值就会是在 HttpSession 中可用。

    那么稍后您可以通过视图中的隐式 session 对象访问此会话属性。

    String value = (String)session.getAttribute("sessionValue"); // gives you "Test Object"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-19
      • 1970-01-01
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      • 2015-06-10
      相关资源
      最近更新 更多