当前位置: 首页 > 知识库问答 >
问题:

意外字符(“a”(代码97)):应为有效值(数字、字符串、数组、对象、“true”、“false”或“null”)

艾心远
2023-03-14
<%@ 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>
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();
    }

}
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)

共有1个答案

姚晋
2023-03-14

尝试将对象更改为JSON行:

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

致:

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

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

    null
 类似资料:
  • 我有一个字符串,可以是两种形式之一: 或 其中<代码> {...}和< code>[...]是任何有效的JSON。我只对解析出字符串的JSON部分感兴趣,但是我不确定最好的方法是什么(特别是因为我不知道字符串将是两种形式中的哪一种)。这是我目前的方法: 这是有效的,但我忍不住觉得可以做得更好。我想可能是regex,但我在匹配子对象和数组时遇到了问题,而不是最外部的json对象或数组。有什么建议吗?

  • 当我们调用时,它会抛出一个异常,说明。我能做什么?

  • 问题内容: 我正在尝试找到一种将String拆分为String数组的方法,并且每当遇到白色香料时就需要对其进行拆分,例如 “嗨,我是保罗” 进入” “嗨”“我”“保罗” 如何使用RegularExpression在split()方法中表示空格? 问题答案: 您需要一个正则表达式,例如,这意味着: 每当遇到至少一个空格时就进行拆分 。完整的Java代码是:

  • 问题内容: 谁能从此链接http://www.javatpoint.com/corejava-interview- questions-3 解释问题87和89 87)在下面的代码中将创建多少个对象? 答案是:只有一个物体 89)在下面的代码中将创建多少个对象? 答案是:两个对象,一个在字符串常量池中,另一个在非池(堆)中。 问题答案: 尽管是用Java编写的类,但它是一种与JVM有特殊关系的特殊类

  • 问题内容: 我需要将一个String拆分为单个字符String的数组。 例如,拆分“ cat”将得到数组“ c”,“ a”,“ t” 问题答案: 这将产生