我是java bean和JSP的新手。 在我的項目中,我做的是創建了多個bean,如LoginBean,RegisterBean,AddCourseBean等。在Java中實現Bean類時遇到困難 - ClassCastException
假設頁面A.jsp上的m正在使用bean LoginBean獲取和設置一些屬性。 之後m移動到頁面B.jsp使用另一個bean說RegisterBean設置某些屬性或添加數據到數據庫。
當從網頁A移動到B M讓錯誤在Tomcat中
HTTP Status 500 - java.lang.ClassCastException: ankit.ShowCourseBean cannot be cast to ankit.LoginBean
type Exception report
message java.lang.ClassCastException: ankit.ShowCourseBean cannot be cast to ankit.LoginBean
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.ClassCastException: ankit.ShowCourseBean cannot be cast to ankit.LoginBean
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
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:728)
root cause
java.lang.ClassCastException: ankit.ShowCourseBean cannot be cast to ankit.LoginBean
org.apache.jsp.components.jsp.Login_jsp._jspService(Login_jsp.java:72)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
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:728)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.42 logs.
我在JSP頁面中使用這個bean代碼如下: 頁A.jsp
<%@ page language="java" %>
<%@ page import="java.sql.*;" %>
<%!
ResultSet rs;
String coursename,courseid;
%>
<jsp:useBean id="obj" scope="application" class="ankit.ShowCourseBean" />
<%
rs=obj.getCourse();
%>
//my remaining Html and logic
頁B.jsp
<%@ page language="java" %>
<%!
boolean b;
String myemail, mypassword,userName,userType;
%>
<jsp:useBean id="obj" scope="application" class="ankit.LoginBean" />
<jsp:setProperty name="obj" property="myemail" />
<jsp:setProperty name="obj" property="mypassword" />
<%
myemail=request.getParameter("myemail");
mypassword=request.getParameter("mypassword");
try{
b=obj.checkLogin(myemail,mypassword);
System.out.println(b);
if(b)
{
userName=obj.checkUserName();
userType=obj.checkUserType();
System.out.println(userName);
session.setAttribute("loggedUserName",userName);
session.setAttribute("loggedUserType",userType);
response.sendRedirect("http://localhost:8080/vt/index.jsp");
}
else
{
out.println("Wrong User Name and Password");
}
}catch(Exception e)
{
out.println("Wrong User Name and Password");
e.printStackTrace();
}
%>
實際重新考慮:這是因爲scope =「application」 – Joeblade