JSP session.getAttribute异常错误

时间:2015-05-27 19:41:57

标签: java jsp session

所以我正在尝试使用会话制作购物车。 如果我第一次添加一个项目它会成功,但如果我添加另一个它将返回异常错误。 (当您以成员身份登录时,我已经声明了session.setAttribute(“i”,“0”))

这是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.

有没有人有解决方案?

2 个答案:

答案 0 :(得分:1)

试试这一行

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

答案 1 :(得分:0)

此行假设session [“i”]是一个字符串:

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

此行将会话[“i”]设置为整数:

session.setAttribute("i",temp2);

删除第7行并将其添加到底部,这样可以将属性保留为字符串:

session.setAttribute("i",temp);