有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何绑定JSP页面和控制器的会话范围字段?

我有一个带有范围注释的简单控制器

@Controller
@Scope("session")
@RequestMapping("/")
public class HelloController {

    private User user = new User("Bob");

    @RequestMapping(method = RequestMethod.GET)
    public String printWelcome() {
        return "hello";
    }
}

和简单的jsp页面

<html>
<body>
    <h1>Y=${sessionScope.user}</h1>
    <h1>Z=${user}</h1>
</body>
</html>

但是当我试图运行这段代码时,我什么也得不到。结果是空的。我不想使用User的单个bean,也不想将HttpSession的对象传递给控制器中的方法或HttpServletRequest对象以从中检索会话。使用一些注释(除了@SessionAttributes)将对象从我的控制器传递到jsp有什么解决方案吗


共 (1) 个答案

  1. # 1 楼答案

    我不明白你为什么感到惊讶。代码中唯一在HttpSession中的是@Controllerbean

    仅仅因为该对象有一个类型为User的字段,并不意味着HttpSession中会有一个User属性

    The result is empty. I don't want to use single beans of User, also I don't like to pass object of HttpSession to method in controller or HttpServletRequest object for retrieving session from it. Is there any solution for using some annotation (except @SessionAttributes) to pass object to jsp from my controller?

    你基本上已经列出了你所有的选择。使用其中任何一种