2015-05-27 58 views
1

所以我試圖用會話製作購物車。 如果我第一次添加一個項目,它會成功,但如果我添加另一個它會返回爲異常錯誤。 (我已經宣佈session.setAttribute( 「我」, 「0」),當你登錄成爲會員)JSP session.getAttribute異常錯誤

這裏的doAddCart.jsp

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %> 
<% 
    String id = request.getParameter("id"); 
    String qty = request.getParameter("qty"); 
    String temp = (String)session.getAttribute("i"); 
    int temp2 = Integer.parseInt(temp)+1; 
    session.setAttribute("i",temp2); 
    temp = Integer.toString(temp2); 
    session.setAttribute(temp,id); 
    session.setAttribute("q"+temp,qty); 
    response.sendRedirect("../product.jsp"); 
%> 

這裏的錯誤,我得到

org.apache.jasper.JasperException: An exception occurred processing JSP page /Controller/doAddCart.jsp at line 5 

2: <% 
3: String id = request.getParameter("id"); 
4: String qty = request.getParameter("qty"); 
5: String temp = (String)session.getAttribute("i"); 
6: int temp2 = Integer.parseInt(temp)+1; 
7: session.setAttribute("i",temp2); 
8: temp = Integer.toString(temp2); 


Stacktrace:  org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)  org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) javax.servlet.http.HttpServlet.service(HttpServlet.java:722) root cause 

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String org.apache.jsp.Controller.doAddCart_jsp._jspService(doAddCart_jsp.java:68) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:722) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)  org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) javax.servlet.http.HttpServlet.service(HttpServlet.java:722) note The full stack trace of the root cause is available in the Apache Tomcat/7.0.29 logs. 

沒有人有解決這個問題嗎?

回答

0

這行假定會話[ 「我」]是一個字符串:

String temp = (String)session.getAttribute("i"); 

此行設置會話[ 「I」]爲Integer:

session.setAttribute("i",temp2); 

刪除第7行並將其添加到底部,而不是將該屬性保留爲字符串:

session.setAttribute("i",temp); 
+0

但它不會執行增量。 – EJP

+0

這解決了這個問題非常感謝你! –

1

嘗試此線

session.setAttribute("i", String.valueOf(temp2));