简体   繁体   English

在 jax-rs 中传递 post 数据参数并由 ajax 调用

[英]passing post data parameters in jax-rs and calling by ajax

I've delved into StackOverflow for days and went through these links 1 and 2 and 3 but all to no avail.我已经研究 StackOverflow 好几天了,并浏览了这些链接1、23 ,但都无济于事

I am a newbie in java web applications.我是 java web 应用程序的新手。 I am using Tomcat 9.0.4 and Jersey 1.18 in my project.我在我的项目中使用 Tomcat 9.0.4 和 Jersey 1.18。 I want to pass 4 parameters as 4 points to a post web service written in JAX-RS and get back the area and perimeter in response.我想将 4 个参数作为 4 个点传递给用 JAX-RS 编写的 web 后服务,并取回面积和周长作为响应。 This is my server-side web service:这是我的服务器端 web 服务:

    @path("/geo")
    public class geonodes{
      static double area(double x1,double y1,double x2,double y2){
      //do area calculation
      }
      static double perimeter(double x1,double y1,double x2,double y2){
      //do perimeter calculation
      }
      @POST
      @Produces(MediaType.APPLICATION_JSON)
      public Response calculate(@QuerParam("x1") Double x1,@QuerParam("y1") Double y1,@QuerParam("x2") Double x2,@QuerParam("y2") Double y2){
        JSONObject obj = new JSONObject();
        obj.put("area",area(x1,y1,x2,y2));
        obj.put("perimeter",perimeter(x1,y1,x2,y2));
        result = JSONObject.toJSONString(obj);
        return Response.status(201).entity(result).build();
    }

and this is my ajax client-side call:这是我的 ajax 客户端调用:

$.ajax({
    url:'http://localhost:8080/api/geo',
    type:'POST',
    dataType:'json',
    contentType:'application/json',
    data:JSON.stringify({x1:22.1,y1:44.19,x2:55.33,y2:49.72}),
    success:function(data){console.log(data);},
    error:function(errMsg){console.log(errMsg);},
});

I use a non-maven project including these jar files:我使用一个非 Maven 项目,包括这些 jar 文件:

库

And this is my web.xml这是我的 web.xml

    <servlet>
        <servlet-name>Geo Nodes API</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>

        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>example,com.fasterxml.jackson.jaxrs.json</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>
        <servlet-name>Geo Nodes API</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>CorsFilter</filter-name>
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/api/*</url-pattern>
    </filter-mapping>

The response was always null and after a long search and google, I found the problem in parameters so in response I returned them.响应始终是 null 并且经过长时间的搜索和谷歌,我在参数中发现了问题,所以作为响应我返回了它们。 when I call the address by the postman the result returns correctly as below:当我通过 postman 调用地址时,结果正确返回如下: postman_200 But invoking by ajax or another system, the parameters are always null.但是通过ajax或其他系统调用,参数总是null。 阿贾克斯

Whenever I use something except @QueryParam ie the class with getter and setter like below code the postman gets the 415 error either.每当我使用除@QueryParam 之外的其他东西时,即带有 getter 和 setter 的 class 如下代码 postman 也会出现 415 错误。 The Coordinats.java class:坐标.java class:

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Coordinates {
    private Double x1;
    private Double y1;
    private Double x2;
    private Double y2;

    public Double getX1() {
        return x1;
    }
    public void setX1(Double x1) {
        this.x1 = x1;
    }
    public Double getY1() {
        return y1;
    }
    public void setY1(Double y1) {
        this.y1 = y1;
    }
    public Double getX2() {
        return x2;
    }
    public void setX2(Double x2) {
        this.x2 = x2;
    }
    public Double getY2() {
        return y2;
    }
    public void setY2(Double y2) {
        this.y2 = y2;
    }

}

The server-side code snippet:服务器端代码片段:

import model.Coordinates;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

@Path("geo")
public class Geo {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Coordinates request(Coordinates coordinates){
        Double x1 = coordinates.getX1();
        Double y1 = coordinates.getY1();
        Double x2 = coordinates.getX2();
        Double y2 = coordinates.getY2();
        return coordinates;
    }
}

邮递员_415 This is the stack trace:这是堆栈跟踪:

04-Dec-2020 05:53:14.771 SEVERE [http-nio-8080-exec-7] com.sun.jersey.spi.container.ContainerRequest.getEntity A message body reader for Java class model.Coordinates, and Java type class model.Coordinates, and MIME media type application/json was not found.
The registered message body readers compatible with the MIME media type are:
application/json ->
  com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$App
  com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$App
  com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$App
*/* ->
  com.sun.jersey.core.impl.provider.entity.FormProvider
  com.sun.jersey.core.impl.provider.entity.StringProvider
  com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
  com.sun.jersey.core.impl.provider.entity.FileProvider
  com.sun.jersey.core.impl.provider.entity.InputStreamProvider
  com.sun.jersey.core.impl.provider.entity.DataSourceProvider
  com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General
  com.sun.jersey.core.impl.provider.entity.ReaderProvider
  com.sun.jersey.core.impl.provider.entity.DocumentProvider
  com.sun.jersey.core.impl.provider.entity.SourceProvider$StreamSourceReader
  com.sun.jersey.core.impl.provider.entity.SourceProvider$SAXSourceReader
  com.sun.jersey.core.impl.provider.entity.SourceProvider$DOMSourceReader
  com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$General
  com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General
  com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General
  com.sun.jersey.core.impl.provider.entity.XMLRootObjectProvider$General
  com.sun.jersey.core.impl.provider.entity.EntityHolderReader
  com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$General
  com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$General

I added every jar file that is needed and now I'm confusing what's wrong??我添加了每个需要的 jar 文件,现在我很困惑出了什么问题? When I pass an object I get a 415-error and when I pass @QueryParam the parameters are accessible by the postman call not accessible by ajax call though!!!当我传递 object 时,我得到一个 415 错误,当我传递 @QueryParam 时,参数可以通过 postman 调用访问,但 ajax 调用无法访问!

If you want to send JSON, then what you have here is correct如果您要发送 JSON,那么您这里的内容是正确的

@Path("geo")
public class Geo {

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Coordinates request(Coordinates coordinates){
        Double x1 = coordinates.getX1();
        Double y1 = coordinates.getY1();
        Double x2 = coordinates.getX2();
        Double y2 = coordinates.getY2();
        return coordinates;
    }
}

You have all the Jackson jars.您拥有所有 Jackson jars。 You should remove the POJOMappingFeature in your web.xml and remove the jersey-json jar as this might cause some conflict.您应该删除 web.xml 中的 POJOMappingFeature 并删除jersey-json jar ,因为这可能会导致一些冲突。

Then add the following in the web.xml然后在web.xml中添加如下

<init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>
        example,
        com.fasterxml.jackson.jaxrs.json
    </param-value>
</init-param>

This will tell Jersey to scan the Jackson package for the JSON provider.这将告诉 Jersey 扫描 Jackson package 以获取 Z0ECD11C1D7A287401D148A28Z 提供程序。

Now in your Postman call, do not use the "params" as that will not create JSON.现在在您的 Postman 调用中,不要使用“参数”,因为这不会创建 JSON。 you should use the "body" tab and then manually type in the JSON you want to send您应该使用“正文”选项卡,然后手动输入您要发送的 JSON

{
  "x1": 1.1,
  "y1": 2.2,
  "x2": 3.3,
  "y2": 4.4
}

Then set the Content-Type header to application/json然后将Content-Type header 设置为application/json

After doing all this, it should work.完成所有这些之后,它应该可以工作。 As an aside, I highly suggest you learn to use a dependency manager, either Maven or Gradle.顺便说一句,我强烈建议您学习使用依赖管理器,Maven 或 Gradle。 Trying to add jars, you often will miss adding the jars that that jar depends on, which will cause that jar not to work.尝试添加 jars 时,您经常会错过添加 jar 所依赖的 jars,这将导致 jar 无法正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM