【问题标题】:Form data to rest PUT method in java表单数据在java中休息PUT方法
【发布时间】:2021-01-23 13:34:15
【问题描述】:

我是 Java 和 REST API 的初学者。我在将表单数据从 HTML 传递到 rest PUT 方法时遇到问题。当我对此进行谷歌搜索时,大多数可用的解决方案都适用于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>  

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

【问题讨论】:

标签: java eclipse rest jersey


【解决方案1】:

正如Using PUT method in HTML form 中的许多人所提到的,HTML 标准目前不支持 PUT。大多数框架会做的是提供一种解决方法。泽西岛的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("/")));
}

它应该根据我的测试工作

【讨论】:

  • 谢谢Paul,前辈也说过,HTML不支持PUT方法..所以任务使用GET方法完成。
猜你喜欢
  • 2021-10-16
  • 1970-01-01
  • 2011-12-24
  • 1970-01-01
  • 2018-06-21
  • 2014-04-24
  • 2013-02-10
  • 2014-10-29
相关资源
最近更新 更多