java - 设置 session 变量spring mvc 3

标签 java spring spring-mvc

我如何设置一个 session 对象,然后我可以通过使用 ${variable} 在我的任何 View 中使用它或 ${requestScope.variable}

为了能够使用 session ,我需要设置 <%@ page session="true" %> ?

最佳答案

如果您想在 View 中访问 session 变量,最简单的方法是:

${sessionScope.yourVariable} 

Using Scope Objects了解更多信息。

如果您设置 <%@ page session="true">然后 JSP 会将 session 范围和页面范围合并到一个命名空间中。然后你可以这样做:

${yourVariable}

你可以像这样在 mvc Controller 的 session 中加入一些东西:

@RequestMapping("/test")
@Controller
public class TestController {
    @RequestMapping(method = RequestMethod.GET)
    public String testMestod(HttpServletRequest request)
    {
        request.getSession().setAttribute("testVariable", "Test Values!!");
        return "testJsp";
    }
}

最后,@SessionAttribute 是针对特定用例的,它不会将变量放入 session 中以便任何人都可以访问它们:

Spring 的人们是这样描述@SessionAttribute 的功能的:

The @SessionAttributes works in the same way as the sessionForm of the SimpleFormController. It puts the command (or for the @SessionAttributes any object) in the session for the duration between the first and the last request (most of the time the initial GET and the final POST). After that the stuff is removed.

Each Controller has it's own ModelMap so something put as a @SessionAttributes in controller1 isn't available in controller2 and vice versa. For that to work you will have to put stuff on the session manually yourself.

关于java - 设置 session 变量spring mvc 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5938951/

相关文章:

java - 当 API 通过 JSON 返回 null 值时,使用 Moshi 时有什么方法可以返回 Kotlin 数据类中的默认值

java - War 在本地独立 tomcat 7(无 eclipse)上运行良好,上传到 ec2 时不起作用

java - 在 spring 中找不到带有 URI 的 HTTP 请求的映射?

java - 分散-聚集 : combine set of Mono<List<Item>> into single Mono<List<Item>>

java - Spring MVC 、Tomcat 和 mysql 的开发环境

java - 在模拟类中初始化私有(private)字段

java - 一堆数字中的 "e"

hibernate - 找不到 FieldInterceptionHelper 类

java.lang.ClassNotFoundException : com. sun.faces.config.ConfigureListener 在 NetBeans 7.0.1 中部署时出错

java - spring-boot报 "400 bad request"错误,具体如下