如何在Spring-mvc中使用Session属性

时间:2013-09-13 17:05:59

标签: spring-mvc session servlets

你能帮我写一下这个代码的spring mvc风格吗?

 session.setAttribute("name","value");

如何将一个由@ModelAttribute注释注释的元素添加到会话中,然后获取对它的访问权限?

9 个答案:

答案 0 :(得分:170)

如果您想在每次回复后删除对象,则不需要会话,

如果您想在用户会话期间保留对象, 有一些方法:

  1. 直接向会话添加一个属性:

    @RequestMapping(method = RequestMethod.GET)
    public String testMestod(HttpServletRequest request){
       ShoppingCart cart = (ShoppingCart)request.getSession().setAttribute("cart",value);
       return "testJsp";
    }
    

    你可以从控制器那里得到它:

    ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
    
  2. 使控制器会话作用域

    @Controller
    @Scope("session")
    
  3. 范围对象,例如,您每次都应该在会话中使用用户对象:

    @Component
    @Scope("session")
    public class User
     {
        String user;
        /*  setter getter*/
      }
    

    然后在每个你想要的控制器中注入类

       @Autowired
       private User user
    

    让课程继续进行。

  4. AOP代理注入: 在春天-xml:

    <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
    
      <bean id="user"    class="com.User" scope="session">     
          <aop:scoped-proxy/>
      </bean>
    </beans>
    

    然后在每个你想要的控制器中注入类

    @Autowired
    private User user
    
  5. 5.Pass HttpSession方法:

     String index(HttpSession session) {
                session.setAttribute("mySessionAttribute", "someValue");
                return "index";
            }
    

    6.通过@SessionAttributes(“ShoppingCart”)在会话中创建ModelAttribute:

      public String index (@ModelAttribute("ShoppingCart") ShoppingCart shoppingCart, SessionStatus sessionStatus) {
    //Spring V4
    //you can modify session status  by sessionStatus.setComplete();
    }
    

    或者您可以将模型添加到整个控制器类,如

    @Controller
        @SessionAttributes("ShoppingCart")
        @RequestMapping("/req")
        public class MYController {
    
            @ModelAttribute("ShoppingCart")
            public Visitor getShopCart (....) {
                return new ShoppingCart(....); //get From DB Or Session
            }  
          }
    

    每个人都有优势和劣势:

    @session可能会在云系统中使用更多的内存,它会将会话复制到所有节点,而直接方法(1和5)则采用凌乱的方法,单元测试并不好。

    访问会话jsp

    <%=session.getAttribute("ShoppingCart.prop")%>
    

    在Jstl:

    <c:out value="${sessionScope.ShoppingCart.prop}"/>
    
    在Thymeleaf中

    <p th:text="${session.ShoppingCart.prop}" th:unless="${session == null}"> . </p>
    

答案 1 :(得分:40)

使用@SessionAttributes

请参阅文档:Using @SessionAttributes to store model attributes in the HTTP session between requests

Understanding Spring MVC Model And Session Attributes”还提供了对Spring MVC会话的非常好的概述,并解释了@ModelAttribute如何/何时被转移到会话中(如果控制器被@SessionAttributes注释)。< / p>

该文章还解释了最好在模型上使用@SessionAttributes而不是直接在HttpSession上设置属性,因为这有助于Spring MVC与视图无关。

答案 2 :(得分:25)

SessionAttribute注释是最简单直接的,而不是从请求对象和设置属性获取会话。 任何对象都可以添加到控制器中的模型中,如果其名称与@SessionAttributes注释中的参数匹配,它将存储在会话中。 在下面,例如,personObj将在会话中提供。

@Controller
@SessionAttributes("personObj")
public class PersonController {

    @RequestMapping(value="/person-form")
    public ModelAndView personPage() {
        return new ModelAndView("person-page", "person-entity", new Person());
    }

    @RequestMapping(value="/process-person")
    public ModelAndView processPerson(@ModelAttribute Person person) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("person-result-page");

        modelAndView.addObject("pers", person);
        modelAndView.addObject("personObj", person);

        return modelAndView;
    }

}

答案 3 :(得分:19)

以下带注释的代码会将“value”设置为“name”

@RequestMapping("/testing")
@Controller
public class TestController {
@RequestMapping(method = RequestMethod.GET)
public String testMestod(HttpServletRequest request){
    request.getSession().setAttribute("name", "value");
    return "testJsp";
  }
}

在JSP中使用相同的访问权限 ${sessionScope.name}

对于@ModelAttribute,请参阅此link

答案 4 :(得分:1)

这种方式最简单, 最短 吗?我知道它并且只是测试了它 - 在这里工作完美:

@GetMapping
public String hello(HttpSession session) {
    session.setAttribute("name","value");
    return "hello";
}

P.S。 我来到这里寻找答案&#34; 如何在Spring-mvc &#34;中使用Session属性,但读了这么多而没看到我写的最明显的我的代码。我没有看到它,所以我认为它错了,但不是没有。因此,让我们与主要问题的最简单解决方案分享这些知识。

答案 5 :(得分:1)

试试这个......

@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {

    @ModelAttribute("types")

    public Collection<PetType> populatePetTypes() {
        return this.clinic.getPetTypes();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute("pet") Pet pet, 
            BindingResult result, SessionStatus status) {
        new PetValidator().validate(pet, result);
        if (result.hasErrors()) {
            return "petForm";
        }else {
            this.clinic.storePet(pet);
            status.setComplete();
            return "redirect:owner.do?ownerId="
                + pet.getOwner().getId();
        }
    }
}

答案 6 :(得分:0)

当我尝试登录(这是一个bootstrap模式)时,我使用了@sessionattributes注释。但问题是当视图是重定向(“redirect:/ home”)时,我输入会话的值显示在url中。一些互联网消息来源建议遵循http://docs.spring.io/spring/docs/4.3.x/spring-framework-reference/htmlsingle/#mvc-redirecting但我使用了HttpSession。在您关闭浏览器之前,此会话将一直存在。 这是示例代码

        @RequestMapping(value = "/login")
        @ResponseBody
        public BooleanResponse login(HttpSession session,HttpServletRequest request){
            //HttpServletRequest used to take data to the controller
            String username = request.getParameter("username");
            String password = request.getParameter("password");

           //Here you set your values to the session
           session.setAttribute("username", username);
           session.setAttribute("email", email);

          //your code goes here
}

您不会在视图方面更改特定内容。

<c:out value="${username}"></c:out>
<c:out value="${email}"></c:out>

登录后,将以上代码添加到您网站的任何位置。如果会话设置正确,您将在那里看到值。确保你正确添加了jstl标签和El-表达式(这里是设置jstl标签的链接https://menukablog.wordpress.com/2016/05/10/add-jstl-tab-library-to-you-project-correctly/

答案 7 :(得分:0)

使用此方法非常简单易用

HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getNativeRequest();

                                                            request.getSession().setAttribute("errorMsg", "your massage");

在jsp中使用然后删除

<c:remove var="errorMsg" scope="session"/>      

答案 8 :(得分:0)

在Spring 4 Web MVC中。您可以在方法中使用@SessionAttribute,并在控制器级别使用@SessionAttributes

@Controller
@SessionAttributes("SessionKey")
public class OrderController extends BaseController {

    GetMapping("/showOrder")
    public String showPage(@SessionAttribute("SessionKey") SearchCriteria searchCriteria) {
     // method body
}