【问题标题】:Store and retrieve an object in session through @Scope("session")通过@Scope("session") 在会话中存储和检索对象
【发布时间】:2022-01-18 16:36:47
【问题描述】:

我有一个春季购物项目,我正在开发一个购物车,我可以向其中添加新产品并将其存储在会话中。我创建了一个 Cart 类将其存储在会话中

import java.util.HashMap;

import org.springframework.stereotype.Component;

import org.springframework.context.annotation.Scope;

@Component
@Scope("session")
public class Cart {
    
    // key: product id
    // value: product information
    private HashMap<Integer,Product> productlist;

    public HashMap<Integer, Product> getProductlist() {
        return productlist;
    }

    public void setProductlist(HashMap<Integer, Product> productlist) {
        this.productlist = productlist;
    }
    
}

我创建了一个控制器类来从会话中获取购物车并向其中添加产品

@Controller
@Scope("request")
public class AddToCartController {

    @Autowired
    private Cart cart;
    
    @Autowired
    ProductService proService;
    
    @RequestMapping("/cart/add")
    public String addToCart(@RequestParam Optional<String> pid) {
        
        if(pid.isPresent()) {
            
            Product productinfo = proService.getProductByPid(pid.get());
            
            if(productinfo.getQuantity()>0) { 
                
                int pidInteger = Integer.parseInt(pid.get());
                
                
                try {
                    Product product = cart.getProductlist().get(pidInteger);
                    
                    // there is already product in cart. add 1 to quantity

                    cart.getProductlist().get(pidInteger).setQuantity(product.getQuantity()+1);
                    
                } catch(NullPointerException e) {

                    // add the new product to cart with quantity 1

                    productinfo.setQuantity(1);
                    cart.getProductlist().put(pidInteger, productinfo);
                    
                }
                
            }
            
        } 
        
        return "redirect:/cart";
    }
}

但是当我调用这个控制器时,它会返回一个错误

java.lang.NullPointerException: null
    at com.example.phonestore.controller.AddToCartController.addToCart(AddToCartController.java:45) ~[classes/:na]

【问题讨论】:

    标签: java spring-mvc


    【解决方案1】:

    我认为 NullPointerException 是由于您没有初始化“产品列表”引起的。你可以试试这样的:“private HashMap productlist = new HashMap();”。

    如果“请求范围”控制器是唯一依赖于它的 bean,则可以在不指定“@Scope”注释的“proxyMode”属性的情况下使用购物车上的“会话范围”。

    但通常控制器应该是“单例”范围,除非您有充分的理由选择另一种范围。而如果Controller是“singleton”作用域,则需要指定“@Scope”注解的“proxyMode”属性。

    【讨论】:

      【解决方案2】:

      您可以尝试使用代理,

             @Scope(value = WebApplicationContext.SCOPE_SESSION,
              proxyMode = ScopedProxyMode.TARGET_CLASS)
      

      例子:

      @Component
      @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
      public class VisitorInfo implements Serializable {
        private String name;
        private int visitCounter;
        private LocalDateTime firstVisitTime;
        //getters/setters
          .............
      }
      

      你也可以使用注解@SessionScope,和上面的配置一样:

      具体来说,{@code @SessionScope} 是一个组合 注释 作为 {@code> @Scope("session")} 的快捷方式,默认 {@link #proxyMode} 设置为 {@link ScopedProxyMode#TARGET_CLASS TARGET_CLASS}。

      https://github.com/Hunoob/Spring-Framework/blob/a7aa3dd2927e4e2ae470a639bc4b1fccd6315273/spring-web/src/main/java/org/springframework/web/context/annotation/SessionScope.java

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-17
        • 1970-01-01
        • 1970-01-01
        • 2019-02-05
        • 1970-01-01
        • 2017-08-25
        • 2020-07-13
        相关资源
        最近更新 更多