gpt4 book ai didi

java - 意外字符 ('a'(代码 97)) : expected a valid value (number, 字符串、数组、对象、 'true'、 'false' 或 'null')

转载 作者:行者123 更新时间:2023-12-01 13:14:27 26 4
gpt4 key购买 nike

我刚刚尝试调用index.jsp它使用 http POST 将 json 发送到我的 rest 项目。
但这给我带来了这个错误:
我无法弄清楚问题出在哪里
任何提示?我对此没有想法。

org.apache.catalina.core.StandardWrapperValve invokeGRAVE: 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 causeorg.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": "Address 12", "name": "twelve", "id": 12,"surname": "twelve"};
var people={"address": "hello"};
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>
人员服务。 java
package com.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 com.dao.*;
import com.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 com.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.model.Person;
import com.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)

最佳答案

尝试更改ObjectJSON线:

var people={"address": "ciao"};

到:
var people=JSON.stringify(eval({"address": "ciao"}));

确保 Person类具有您传递给它的相同参数构造函数。

根据您在评论中的图像堆栈跟踪异常,错误发生在 Hibernate异常(exception) StaleStateException意思是:

Thrown when a version number or timestamp check failed, indicating that the Session contained stale data (when using long transactions with versioning). Also occurs if we try delete or update a row that does not exist


  • 这可以通过从数据库中更新对象来解决,例如 hibernate 中的刷新方法,然后提交会将对象持久保存在数据库中。
  • 您可以使用合并方法和提交,但在这里您将覆盖当前数据。
  • 使用锁也可以解决改变状态。
  • 关于java - 意外字符 ('a'(代码 97)) : expected a valid value (number, 字符串、数组、对象、 'true'、 'false' 或 'null'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33631523/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com