我正在尝试基于jersey + JPA + Glasfish 3.1 + java 6u43 + Gson lib构建基于json处理的Web服务但是我得到了一个非常令人沮丧的例外。
java.lang.ClassCastException:com.hm.model.User无法强制转换为com.hm.model.User
我不是将用户强制转换为用户,但例外情况是我将用户对象转回给用户。请帮我理解这个。
来自glasfish server.log的详细异常快照
com.sun.jersey.api.core.WebAppResourceConfig|_ThreadID=24;_ThreadName=Thread-1 Scanning for root resource and provider classes in the Web app resource paths:
/WEB-INF/lib
/WEB-INF/classes|#]
com.sun.jersey.api.core.ScanningResourceConfig|_ThreadID=24;_ThreadName=Thread-1;|Root resource classes found:
class com.hm.dam.Users|#]
com.sun.jersey.api.core.ScanningResourceConfig|_ThreadID=24;_ThreadName=Thread-1;|No provider classes found.|#]
com.sun.jersey.server.impl.application.WebApplicationImpl|_ThreadID=24;_ThreadName=Thread-1;|Initiating Jersey application, version 'Jersey: 1.5 01/14/2011 12:36 PM'|#]
javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=42;_ThreadName=Thread-1;|WEB0671: Loading application [HMWService] at [/HMWService]|#]
javax.enterprise.system.tools.admin.org.glassfish.deployment.admin|_ThreadID=42;_ThreadName=Thread-1;|HMWService was successfully deployed in 1,100 milliseconds.|#]
javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=161;_ThreadName=Thread-1;|[EL Fine]: 2013-07-19 01:05:35.01--ServerSession(233673454)--Connection(2052351957)--Thread(Thread[http-thread-pool-8080(4),5,grizzly-kernel])--SELECT user_id, DOB, EMAIL, EXPERIENCE, first_name, inser_user_id, insert_dt, join_dt, last_name, nic_passport, PASSWORD, STATUS, update_dt, update_user_id, USERNAME, gender_ref_id FROM users
com.sun.jersey.spi.container.ContainerResponse|_ThreadID=32;_ThreadName=Thread-1;|The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.ClassCastException: com.hm.model.User cannot be cast to com.hm.model.User
at com.hm.dam.Users.read(Users.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)`
这就是我的项目结构的样子。 我用数据库中的pojo类构建一个JPA项目,其中包含一个名为'users'的表 这是我的pojo和persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="HMbeans" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.hm.model.User</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/hotel_management"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="123456"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="eclipselink.logging.level" value="FINER"/>
<property name="eclipselink.logging.exceptions" value="true"/>
<property name="eclipselink.logging.session" value="true"/>
<property name="eclipselink.logging.connection" value="true"/>
</properties>
</persistence-unit>
</persistence>
现在用户实体pojo。
@Entity
@Table(name="users")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="user_id")
private String userId;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
private String password;
public User() {
}
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
现在这是我在HMWService动态网络项目中的Web服务类
package com.hm.dam;
...
@Path("/users")
public class Users
{
EntityManager em = JPAUtil.getEntityManager() ;
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("/readUser")
public String read(@FormParam("userId") String User_Id) {
// User u = em.find(User.class, User_Id);
User u=null;
Iterator<User> it = em.createQuery("SELECT u FROM User u").getResultList().iterator();
if(it.hasNext())
{
u=it.next();
System.out.println(u.getFirstName());
}
if(u!=null)
return new Gson().toJson(u);
else
return new Gson().toJson("");
}
}
最后这是我的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>HMWService</display-name>
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<!-- <persistence-context-ref>
<persistence-context-ref-name>persistence/em</persistence-context-ref-name>
<persistence-unit-name>HMentites</persistence-unit-name>
</persistence-context-ref> -->
</web-app>
我编写了一个index.jsp来测试Web服务。它包含一个带post方法的表单。在提交浏览器上显示上述异常
<h1>JAX-RS @FormQuery Testing</h1>
<form action="rest/users/readUser" method="post">
<p>
Id : <input type="text" name="userId" />
</p>
<input type="submit" value="Read User" />
</form>
例外 java.lang.ClassCastException:com.hm.model.User无法强制转换为com.hm.model.User
答案 0 :(得分:2)
对于您的glassfish服务器进行热部署可能会出现问题(如果您使用它)。尝试清理和构建项目,看看这是否有帮助。
如果没有帮助,当一个类由两个不同的Classloaders
加载时,通常会出现此问题。
有许多不同的解决方案,请查看this question或this question。