2016-12-21 7 views
0

Я начинаю с Java EE, когда пытаюсь передать объект между JSP и сервлетом, я использую сеанс. Для домашней работы я должен создать сайт электронной коммерции. я просто это в моем JSP:2 объект сеанса java ee null exception

HttpSession sess = request.getSession();    
Panier pan = new Panier(); 
sess.setAttribute("panier", pan); 
sess.setAttribute("produit", produits.get(0)); 

Produits является ArrayList из "Produit" объекта.

В моей Servlet:

HttpSession sess = request.getSession(); 
Panier pan = (Panier) sess.getAttribute("panier"); 
Produit p1 = (Produit) sess.getAttribute("prod"); 

Когда я здесь, все работы вызывают, я могу показать хорошие атрибуты объекта сковороду или p1. Но, когда я использую свой метод «ajouterProduit» (addProduct на английском языке), появляется исключение дикого нулевого указателя.

Мой класс "Produit":

public class Produit implements java.io.Serializable{ 
private String nom; 
private int prix; 

public Produit(String name, int price){ 
    this.nom = name; 
    this.prix = price; 
} 

public void setNom(String n){ 
    this.nom = n; 
} 

public void setPrix(int p){ 
    this.prix = p; 
} 

public String getNom(){ 
    return this.nom; 
} 

public int getPrix(){ 
    return this.prix; 
} 
} 

Мой класс "Panier" (корзина на английском языке):

public class Panier implements Serializable{ 
private List<Produit> panier; 
private static int montant = 0; 

public Panier(){ 
    panier = new ArrayList<>(); 
} 

public void ajouterProduit(Produit p1){ 
    panier.add(p1); 
    montant = montant + p1.getPrix(); 
} 

public void ajouterProduit(Produit p1, Produit p2){ 
    panier.add(p1); 
    montant = montant + p1.getPrix(); 
    panier.add(p2); 
    montant = montant + p2.getPrix(); 
} 

public void ajouterProduit(Produit p1, Produit p2,Produit p3){ 
    panier.add(p1); 
    montant = montant + p1.getPrix(); 
    panier.add(p2); 
    montant = montant + p2.getPrix(); 
    panier.add(p3); 
    montant = montant + p3.getPrix(); 
} 

public List<Produit> getPanier(){ 
    return panier; 
} 

public int getMontantTotal(){ 
    return montant; 
} 
} 

Заранее спасибо за помощь! ;)

ответ

1

Вы добавить свой "Produit" вот так:

sess.setAttribute("produit", produits.get(0)); 

Но получить его так:

Produit p1 = (Produit) sess.getAttribute("prod"); 

"prod" и "produit" 2 разные сессии имена. Ваш «продукт» не находится в сеансе "prod".

Tu stock ton produit dans la session "produit", mais tu le récupére à partir d'une сеанс "prod", qui n'existe pas.

p1 есть, поэтому, null.

Смежные вопросы