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

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

直接向会话添加一个属性

@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");

使您的控制器会话具有作用域

@Controller
@Scope("session")

定义对象的范围,例如您有应该在每次会话中使用的用户对象:

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

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

   @Autowired
   private User user

使课程保持在会话中。

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>

如何在Spring-MVC中使用会话属性-代码日志