我有一個 Spring 購物專案,我正在處理一個購物車,我可以向它添加新產品并將其存盤在會話中。我創建了一個 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 類來從會話中獲取購物車并向其中添加產品
@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]
uj5u.com熱心網友回復:
我認為 NullPointerException 是由您沒有初始化“productlist”引起的。您可以嘗試這樣的操作:“ private HashMap<Integer,Product> productlist = new HashMap<>(); ”。
如果“請求范圍”控制器是唯一依賴它的 bean,則可以在購物車上使用“會話范圍”而不指定“@Scope”注釋的“proxyMode”屬性。
但通常控制器應該是“單一”范圍,除非您有充分的理由選擇另一種范圍。如果 Controller 是“singleton”范圍,您應該指定“@Scope”注釋的“proxyMode”屬性。
uj5u.com熱心網友回復:
你可以嘗試使用代理,
@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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385843.html
