2016-12-21 4 views
0

私はJava EEで初心者ですが、JSPとサーブレットの間でオブジェクトを転送しようとするとセッションが使用されます。 宿題については、私は電子商取引のウェブサイトを作成する必要があります。 私はちょうど私のjspでこれを持っている:2セッションオブジェクトjava ee null例外

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

produitsは "produit" オブジェクトのArrayListのです。私のサーブレットで

:私がここにいるとき

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

、すべての作品が、私は、オブジェクトパンやP1の良い属性を表示することができます起こします。しかし、メソッド "ajouterProduit"(addProductを英語)を使用すると、野蛮なnullポインタ例外が表示されます。

マイクラス "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; 
} 
} 

は私のクラス "パニエ"(英語でのバスケット):助けを事前に

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ストックトンproduitダンスラセッション"produit"、パートディレムセッション "prod"、qui n'existe pas。

p1は、したがって、nullです。