springMVC中的HttpSession管理


问题内容

我是MVC的新手,并通过做我所学的知识开始制作示例应用程序。我计划在Spring
MVC中实施会话管理。我发现很有帮助。

但是我无法弄清楚。我们为会话添加值,例如

HttpSession session = request.getSession(false);
session.setAttribute("key", value);
session.setAttribute("key1",  value1);

然后我们根据像

session.getAttrubute("key");

但是在springMVC中,我看不到任何类似的东西,这完全使我感到困惑。

@Controller
@SessionAttributes("thought")
public class SingleFieldController {

    @RequestMapping(value="/single-field")
    public ModelAndView singleFieldPage() {
        return new ModelAndView("single-field-page");
    }

    @RequestMapping(value="/remember")  
    public ModelAndView rememberThought(@RequestParam String thoughtParam) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("thought", thoughtParam);
        modelAndView.setViewName("single-field-page");
        return modelAndView;
    }

}

在上面的代码
@SessionAttributes("thought")中,这完全使我感到困惑,就像这个thought定义是什么一样,ModelAndView因为我正在使用,所以我不需要返回abackbone.marionette.js

那么,如何在会话中设置值并在需要时使用它们呢?我还必须将会话对象转换为我的用户定义对象,因为在将值返回到屏幕时,我仅返回会话中可用的UserDefined对象的列表。

因此,请帮助我更好地理解它。也许我对使用jsp / servlet的方式感到困惑。

更新

以下是我拥有的控制器并提供了注释

package com.hexgen.puppet;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.hexgen.puppet.CreatePuppet;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class PuppetService {

    @RequestMapping(method = RequestMethod.POST, value = "/create")
    public @ResponseBody
    void createOrder(@RequestBody CreatePuppet request) {
        //logic to add/update values in session
    }

    @RequestMapping(method = RequestMethod.GET, value = "/list")
    public @ResponseBody
    List<Puppet> getGroups() {
        //logic to retrive objects from session and convert it as List and send it back

        return puppets;
    }


}

并根据需要转换对象,然后继续


问题答案:

@SessionAttributes 不能完全替代传统的 HttpServlet
会话管理。如果两个或多个Controller方法需要传达一些数据,请使用它。但是,使用此方法,我们只能在单个控制器类内实现通信。如果使用
@SessionAttributes, 则不使用显式读写会话。建议仅在短暂的通信中使用 @SessionAttributes
。如果需要在会话中存储长期数据,建议显式使用 session.setAttributesession.getAttribute 而不是
@SessionAttributes
。有关更多信息,请查看此