java 中的表单数据以放置 PUT 方法

Form data to rest PUT method in java

我是 Java 和 REST API 的初学者。我在将表单数据从 HTML 传递到 rest PUT 方法时遇到问题。当我google关于这个的时候,大多数可用的解决方案都是针对POST方法,建议使用FormParam。就我而言,它显示以下错误:

The method received in the request-line is known by the origin server but not supported by the target resource.

即使我使用PathParam,也返回同样的错误:

The method received in the request-line is known by the origin server but not supported by the target resource.

以及 Spring 引导的一些解决方案。但是我没有用那个。

PUT 方法:

@PUT
@Path("/update")
@Produces(MediaType.TEXT_HTML)
public String updCard(@PathParam("cardNo") String cardNo,  
        @PathParam("reportId") int reportId
        ) throws SQLException { 

    Card c = new Card(cardNo, reportId); 

    System.out.println(cardNo + reportId);
    
    return "";
}

形式:

 <form method="PUT" action="rest/card/update">
  <label for = "cardNo">Card No: </label> <input type="text" name = "cardNo" id = "cardNo"><br/>
  <label for = "reportId">Report Id:</label> <input type="text" name = "reportId" id = "reportId"> <br/>
  <button type="submit">Update</button>  

那么,如何在 Jersey 的 PUT 方法中获取表单数据?

正如 Using PUT method in HTML form, PUT is not currently supported by the HTML standard. What most frameworks will do is offer a workaround. Jersey has such a workaround with its HttpMethodOverrideFilter 中许多人提到的那样。您必须做的是使用 POST 方法并添加 _method=put 查询参数,过滤器会将 POST 切换为 PUT。

您首先需要注册过滤器。如果您使用的是 ResourceConfig,只需执行

@ApplicationPath("api")
public class JerseyConfig extends ResourceConfig {

    public JerseyConfig() {
        ...
        register(HttpMethodOverrideFilter.class);
    }
}

如果您使用的是 web.xml,则执行

<init-param>
    <param-name>jersey.config.server.provider.classnames</param-name>
    <param-value>org.glassfish.jersey.server.filter.HttpMethodOverrideFilter</param-value>
</init-param>

然后在您的 HTML 中,您只需将 _method=put 查询参数添加到 URL。下面是我用来测试的例子

<form method="post" action="/api/form?_method=put">
    <label>
        Name:
        <input type="text" name="name"/>
    </label>
    <label>
        Age:
        <input type="number" name="age"/>
    </label>
    <br/>
    <input type="submit" value="Submit"/>
</form>

并且在您的资源方法中,您将使用 @PUT@FormParam 作为参数

@PUT
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response form(@FormParam("name") String name,
                     @FormParam("age") String age,
                     @Context UriInfo uriInfo) {

    URI redirectUri = UriBuilder
            .fromUri(getBaseUriWithoutApiRoot(uriInfo))
            .path("redirect.html")
            .queryParam("name", name)
            .queryParam("age", age)
            .build();
    return Response.temporaryRedirect(redirectUri).build();
}

private static URI getBaseUriWithoutApiRoot(UriInfo uriInfo) {
    String baseUri = uriInfo.getBaseUri().toASCIIString();
    baseUri = baseUri.endsWith("/")
            ? baseUri.substring(0, baseUri.length() - 1)
            : baseUri;
    return URI.create(baseUri.substring(0, baseUri.lastIndexOf("/")));
}

根据我的测试应该可以工作