用java将数据格式化为rest PUT方法



我是Java和REST API的初学者。我在将表单数据从HTML传递到restPUT方法时遇到问题。当我在谷歌上搜索时,大多数可用的解决方案都是POST方法,建议使用FormParam。在我的情况下,它显示以下错误:

原始服务器知道在请求行中接收到的方法,但目标资源不支持该方法。

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

原始服务器知道在请求行中接收到的方法,但目标资源不支持该方法。

以及一些针对Spring Boot的解决方案。但我没有用那个。

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>  

那么,如何在泽西岛的PUT方法中获取表单数据呢?

正如许多人在以HTML形式使用PUT方法中提到的那样,PUT目前不受HTML标准的支持。大多数框架都会提供一个变通方法。Jersey的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@FormParams作为参数

@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("/")));
}

它应该从我测试的开始工作

最新更新