【发布时间】: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