我刚刚尝试调用index.jsp
,它使用POST将json发送到我的休息项目。
但这是错误:
似乎问题不在我的代码中,而是在catalina中。
有提示吗?我不知道这个
nov 10, 2015 2:30:37 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [jersey-serlvet] in context with path [/HibernateTutorialWeb] threw exception [org.codehaus.jackson.JsonParseException: Unexpected character ('a' (code 97)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
at [Source: org.apache.catalina.connector.CoyoteInputStream@24097548; line: 1, column: 2]] with root cause
org.codehaus.jackson.JsonParseException: Unexpected character ('a' (code 97)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
at [Source: org.apache.catalina.connector.CoyoteInputStream@24097548; line: 1, column: 2]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1213)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:375)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportUnexpectedChar(JsonParserMinimalBase.java:306)
at org.codehaus.jackson.impl.Utf8StreamParser._handleUnexpectedValue(Utf8StreamParser.java:1536)
at org.codehaus.jackson.impl.Utf8StreamParser._nextTokenNotInObject(Utf8StreamParser.java:432)
at org.codehaus.jackson.impl.Utf8StreamParser.nextToken(Utf8StreamParser.java:318)
at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2168)
at org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2106)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1004)
at org.codehaus.jackson.jaxrs.JacksonJsonProvider.readFrom(JacksonJsonProvider.java:410)
at com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.readFrom(JacksonProviderProxy.java:139)
at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:474)
at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123)
at com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:46)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
的index.jsp :
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Send jSon - put method</title>
</head>
<body>
<script>
//var people = {"address": "Indirizzo 12", "name": "dodici", "id": 12,"surname": "dodici"};
var people={"address": "ciao"};
function sendobject(){
$.ajax({
type: "POST",
url: "http://localhost:8080/HibernateTutorialWeb/rest/person/post",
data: people,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" onclick="sendobject()" value="invia"> </input>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</body>
</<html>
PersonService。的java
package it.zerob.ws.service;
import java.util.List;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import it.zerob.dao.*;
import it.zerob.model.*;
@Path("/person")
public class PersonService {
// try hello data
// http://localhost:8080/HibernateTutorialWeb/rest/person/hello/mario
@GET
@Path("/hello/{param}")
public Response getMsg(@PathParam("param") String msg) {
String output = "Jersey say hello : " + msg;
return Response.status(200).entity(output).build();
}
// http://localhost:8080/HibernateTutorialWeb/rest/person/2
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Person getPersonById(@PathParam("id") int id) {
return new PersonDao().getPersonById(id);
// error for type of response incorrect
/*
* public ResponseBuilder getPersonById(@PathParam("id") int id){
* PersonDao pDao = new PersonDao (); if(pDao.getPersonById(id) != null)
* {return Response.status(200).entity(new
* PersonDao().getPersonById(id));} else{ return
* Response.status(200).entity("Utente id: "+ id + ", Rimosso"); }
*/
}
// //http://localhost:8080/HibernateTutorialWeb/rest/person/getAllJson
@GET
@Path("/getAllJson")
@Produces(MediaType.APPLICATION_JSON)
public List<Person> getAllJson() {
return new PersonDao().getAllPerson();
}
@GET
@Path("/xml/{id}")
@Produces(MediaType.APPLICATION_XML)
public Person getPersonByIdXML(@PathParam("id") int id) {
return new PersonDao().getPersonById(id);
}
@POST
@Path("/post")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response createUtenteJSON(Person person) {
new PersonDao().saveOrUpdate(person);
String result = "Person saved : " + person;
return Response.status(201).entity(result).build();
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response updateUtente(Person person) {
if (person.getId() != 0) {
new PersonDao().saveOrUpdate(person);
return Response.ok(person, MediaType.APPLICATION_JSON).build();
} else {
return Response.status(Response.Status.BAD_REQUEST)
.entity("Specificare l'id dell'utente").build();
}
}
@DELETE
@Path("{id}")
public Response removePerson(@PathParam("id") Integer id) {
new PersonDao().deletePerson(id);
return Response.status(200).entity("Utente id: " + id + ", Rimosso")
.build();
}
}
PersonDao.java
package it.zerob.dao;
//import javax.transaction.Transaction;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import it.zerob.model.Person;
import it.zerob.util.SessionFactoryUtil;
public class PersonDao {
public void saveOrUpdate(Person person) {
Transaction trns = null;
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
if (person.getId() != 0) {
//if exists update obj
session.update(person);
} else {
session.save(person);
}
session.getTransaction().commit();
} catch (RuntimeException e) {
if (trns != null) {
trns.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
}
public void deletePerson(int id) {
Transaction trns = null;
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
Person person = (Person) session.load(Person.class, new Integer(id));
System.out.println("Deleted person :"+person.toString());
session.delete(person);
session.getTransaction().commit();
} catch (RuntimeException e) {
if (trns != null) {
trns.rollback();
}
e.printStackTrace();
} finally {
session.flush();
session.close();
}
}
public List<Person> getAllPerson() {
List<Person> people = new ArrayList<Person>();
Transaction trns = null;
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
people = session.createQuery("from Person").list();
//session.getTransaction().commit();
} catch (RuntimeException e) {
if (trns != null) {
trns.rollback();
}
} finally {
session.flush();
session.close();
}
System.out.println("People list : \n");
for(int i=0;i<people.size();i++){
System.out.println(people.get(i));
}
return people;
}
public Person getPersonById(int id) {
Person person = null;
Transaction trns = null;
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
String queryString = "FROM Person WHERE id = :id";
Query query = session.createQuery(queryString);
query.setInteger("id", id);
person = (Person) query.uniqueResult();
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
session.flush();
session.close();
}
return person;
}
}
已更新:
在index.jsp上
var people = JSON.parse({"address": "Indirizzo 12", "name": "dodici", "id": 12,"surname": "dodici"});
现在错误是这样的:
HTTP Status 500 - java.io.EOFException: No content to map to Object due to end of input
type Exception report
message java.io.EOFException: No content to map to Object due to end of input
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: java.io.EOFException: No content to map to Object due to end of input
com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:420)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.io.EOFException: No content to map to Object due to end of input
org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2173)
org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2106)
org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1004)
org.codehaus.jackson.jaxrs.JacksonJsonProvider.readFrom(JacksonJsonProvider.java:410)
com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.readFrom(JacksonProviderProxy.java:139)
com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:474)
com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123)
com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:46)
com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203)
com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
答案 0 :(得分:2)
尝试将Object
更改为JSON
行:
var people={"address": "ciao"};
要:
var people=JSON.stringify(eval({"address": "ciao"}));
确保Person
类具有与传递给它的相同的param构造函数。
根据评论中的图像堆栈跟踪异常,错误发生在Hibernate
,异常StaleStateException,这意味着:
当版本号或时间戳检查失败时抛出,指示 Session包含过时数据(使用长事务时) 版本化)。如果我们尝试删除或更新一行,也会发生 不存在
答案 1 :(得分:0)
错误消息的内容是服务器收到的POST输入不是有效的JSON。
可能是JQuery根据此输入产生的内容:var people={"address": "ciao"};
不是您所期望的。您可以尝试通过HTTP请求嗅探实际传输的内容(使用Firebug,Wireshark等)。
尝试使用:
var people='{"address": "ciao"}';
而不是
var people={"address": "ciao"};
答案 2 :(得分:0)
由我解决,
jsp上有错误。 我正在检查他是否是来自id的新用户。
所以这是我的后端
if (person.getId() != 0) {
//if exists update obj
session.update(person);
} else {
session.save(person);
}
这是我的jsp:
var people = JSON.stringify
(eval({"address": "Indirizzo 12", "name": "dodici", "id": 12, "surname": "dodici"}));
所以使用id
,dao尝试更新db上不存在的记录,给我错误。
现在你的是jsp中的people
var:
var people =
JSON.stringify(eval({"address": "Indirizzo 12", "name": "dodici","surname": "dodici"}));
效果很好。