小编典典

如何在Spring-MVC中使用会话属性

spring-mvc

您能帮我写出这段代码的Spring MVC风格模拟吗?

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

以及如何在@ModelAttribute会话中添加带有注释的元素,然后对其进行访问?


阅读 692

收藏
2020-06-01

共1个答案

小编典典

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

如果要在用户会话期间保留对象,可以采用以下几种方法:

  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");
  1. 使您的控制器会话范围

    @Controller
    

    @Scope(“session”)

  2. 作用域对象,例如,您有应该在每次会话中使用的用户对象:

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

然后在所需的每个控制器中注入类

@Autowired
private User user

使课程保持在会话中。

  1. AOP代理注入:在spring -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.将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类,例如,

@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>
2020-06-01