【发布时间】:2015-04-09 02:38:10
【问题描述】:
我对 Spring 世界很陌生,正在尝试一些与 Spring MVC 和会话处理相关的事情。
我的问题是,如果我们有同名的模型属性和会话属性,那么模型属性会覆盖会话属性的值吗?
在下面的代码 sn-p 中(对于格式不好的问题,我是新来的)我正在将属性名称 sessionAttribute 添加到模型和会话中。在 JSP 中访问相同的属性时,我得到了 Model Attribute 的值([name] as Model Attribute )。
@RequestMapping(value="/hello", method=RequestMethod.GET)
public String hello(@RequestParam(value="username", required=false,defaultValue="World") String name, Model model,HttpServletRequest req) {
model.addAttribute("sessionAttribute", name+" as Model Attribute");
System.out.println("In controller");
HttpSession hs=req.getSession();
hs.setAttribute("sessionAttribute","overridden Session attribute"); //prints"overridden Session attribute"
System.out.println(hs.getAttribute("sessionAttribute"));
return "someViewName";
}
下面是视图(someViewName),它将 sessionAttribute 的值打印为模型属性
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring4 MVC -HelloWorld</title>
</head>
<body>
<% HttpSession hs=request.getSession();
String sesstionAttr=(String)session.getAttribute("sessionAttribute");
out.println(sesstionAttr); //printin [name] as Model Attribute
%>
</body>
</html>
【问题讨论】:
-
您正在将
sessionAttribute添加到 HttpSession 中,然后从中读取。为什么它必须打印其他内容(hs.getAttribute("sessionAttribute")正在从会话中获取 :))?顺便说一句,在这里查看一个主题,stackoverflow.com/questions/3423262/… -
用更多细节更新了问题。在控制器中,我得到了预期的值,但在 JSP 中,访问会话属性时,我得到了模型属性的值。
-
我认为你需要检查这个:stackoverflow.com/questions/16383439/…
-
感谢 Patrick LC 和 vtorosyan,我阅读了这两篇文章,但我仍然感到困惑。请在这里帮助我:)
标签: spring model-view-controller