English 中文(简体)
与PPOST JSON一起向泽西岛教育学院提供服务
原标题:Issue with POST JSON to a Jersey REST service

我在把JSON派到泽西岛理工学院服务方面存在问题,GET正在完美地工作,但POST似乎trick。 现在,我一直在处理这个问题,迄今没有解决办法。 任何帮助都受到高度赞赏!

似乎无法找到U RL来派 j子? 这里,PeBug conole显示:

    POST http://localhost:9998/data 400 Bad Request
    Post source: name=Tony
    **Response Headers**
    Connection  close
    Content-Length  0
    Content-Type    text/html; charset=iso-8859-1
    Date    Fri, 20 Apr 2012 10:13:24 GMT
    **Request Headers**
    Accept  application/json, text/javascript, */*; q=0.01
    Accept-Encoding gzip, deflate
    Accept-Language sv-se,sv;q=0.8,en-us;q=0.5,en;q=0.3
    Connection  keep-alive
    Content-Length  9
    Content-Type    application/json; charset=UTF-8
    Host    localhost:9998
    Referer http://localhost:9998/static/page.html
    User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0
    X-Requested-With    XMLHttpRequest

I m 做以下工作:

<button id= btn  value="knapp" name="knapp" />
    <script type="text/javascript">
    $( #btn ).click(function(){
        $.ajax({
            url:  /data ,
            type:  POST ,
            contentType:  application/json ,
            data: {name:"Tony"},
            dataType:  json 
        });
    })
</script>

Javabean同@XmlRootElement:

@XmlRootElement
public class StatusBean {
    private String name;

    public StatusBean() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

资源方法:

@Path("/data")
public class PostData {
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public StatusBean post(StatusBean sb) {
        System.out.println(sb);
        return sb;
    }
}

服务器,与Grezzly建立:

public class Main {
    public static final URI BASE_URI = getBaseURI();

    public static void main(String[] args) throws IOException {
        HttpServer httpServer = startServer();

        Map<String,String> initParams = new HashMap<String, String>();
        initParams.put("com.sun.jersey.config.property.packages", "server");
        SelectorThread selector = GrizzlyWebContainerFactory.create("http://localhost:9998/", initParams );

        System.out.println(String.format("Jersey app started with WADL available at "
                + "%sapplication.wadl
Try out %shelloworld
Hit enter to stop it...",
                BASE_URI, BASE_URI));

        System.in.read();
        httpServer.stop();
    }

    protected static HttpServer startServer() throws IOException {
        System.out.println("Starting grizzly...");

        ClassNamesResourceConfig rc = new ClassNamesResourceConfig(PostData.class);

//        rc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);

        HttpServer server = GrizzlyServerFactory.createHttpServer(BASE_URI, rc);

        server.getServerConfiguration().addHttpHandler(new StaticHttpHandler(new File(".").getAbsolutePath()), "/static");

        return server;
    }

    private static int getPort(int defaultPort) {
        String port = System.getProperty("jersey.test.port");
        if (null != port) {
            try {
                return Integer.parseInt(port);
            } catch (NumberFormatException e) {
            }
        }
        return defaultPort;
    }

    private static URI getBaseURI() {
        return UriBuilder.fromUri("http://localhost/").port(getPort(9998)).build();
    }
}
问题回答
  1. 引证您的目录。

    @XmlRootElement
    
    public class StatusBean implements Serializable {
    ....
    }
    
  2. 检查你的办公室。 ......

    http:// localhost:9998/{projectname}/{restservletmapping}/data

    例如,如果我的网络xml喜欢,我的项目名称是Sample Project。

    <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
    

    URL将:

    http://www.eviware.com/%22SOAP%20UI%22”rel=“nofollow” browser Addons,如POSTMAN、RESTCONOLE等。

  3. If above things are fine and REST service is giving response with testing tools. Then it could be problem of Cross Origin Policy in ajax.

I had the same problem. The issue is that your data is not converted to JSON string automatically. So you just need to call JSON.stringify(...) on your data before posting it:

<button id= btn  value="knapp" name="knapp" />
<script type="text/javascript">
$( #btn ).click(function(){
    $.ajax({
        url:  /data ,
        type:  POST ,
        contentType:  application/json ,
        data: JSON.stringify({name:"Tony"}),
        dataType:  json 
    });
})
</script>

这应当行之有效。

你们重新定位的道路是否完整? 您应界定另一个<代码>Path 说明post方法,并在URL中重新定位如下:

@Path("/data")
public class PostData {
    @Path("/postStatus")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public StatusBean post(StatusBean sb) {
        System.out.println(sb);
        return sb;
    }
}

然后使用<代码>/数据/数据/数据/数据/密码>,请你:

<button id= btn  value="knapp" name="knapp" />
<script type="text/javascript">
    $( #btn ).click(function(){
        $.ajax({
            url:  /data/postStatus ,

            type:  POST ,
            contentType:  application/json ,
            data: {name:"Tony"},
            dataType:  json 
        });
    })
</script>




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签