IT虾米网

java之springMVC中的Httpsession管理

zfyouxi 2023年05月21日 程序员 150 0

我是 spring MVC 的新手,并开始根据所学制作示例应用程序。我计划在 spring MVC 中实现 session 管理。我找到了 this一个有帮助。

但是我没弄清楚。我们向 session 添加值,例如

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

稍后我们会根据像

这样的键获取值
session.getAttrubute("key"); 

但是在 spring MVC 中,我看不到任何类似的东西,这让我很困惑。

@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 因为我正在使用 backbone.marionette.js

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

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

更新

下面是我拥有的 Controller 并提供了评论

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 session 管理。如果两个或多个 Controller 方法需要传递某些数据,请使用它。但是,使用它我们只能在单个 Controller 类中实现通信。如果您正在使用 @SessionAttributes,则您不会显式地从 session 读取和写入 session 。 @SessionAttributes 仅建议用于短期通信。如果您需要在 session 中存储长期数据,建议显式使用 session.setAttributesession.getAttribute,而不是 @SessionAttributes .更多信息check this out .


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!