【问题标题】:Java Spring MVC application accepts POST requests only with trailing slashJava Spring MVC 应用程序仅接受带有斜杠的 POST 请求
【发布时间】:2017-08-03 11:12:22
【问题描述】:

我有一个带有以下详细信息的 Spring MVC 应用程序

  1. war 文件名为 forms.war。 web.xml 中的 url 模式是"/"
  2. 控制器操作的@RequestMapping 是"/"
  3. 如果 localhost:8080/forms 被命中,RequestMethod.GET 操作会正常工作
  4. 如果发布数据与localhost:8080/forms 匹配,则不会触发 RequestMethod.POST 操作
  5. POST 请求提供 302 重定向
  6. 当我点击localhost:8080/forms/ 时,POST 请求工作正常

任何解决方案可以使 POST 请求在没有斜杠的情况下工作?

这是我用来测试 POST api 的代码:

public class HttpPostExample {
    public static void main(String[] args) {
        HttpClient httpClient = HttpClientBuilder.create().build();
        try {

            HttpPost request = new HttpPost("http://localhost:8080/forms");
            StringEntity params =new StringEntity("{\"form_url\":\"admin\",\"website\":\"US_WEBSITE\",\"email\":\"testelascrip1@gmail.com\",\"cis_name\":\"testscrip1\"} ");
            request.addHeader("content-type", "application/x-www-form-urlencoded");
            request.setEntity(params);
            HttpResponse response = httpClient.execute(request);

            System.out.println("Printing the response code " + response.getStatusLine().getStatusCode());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

将 url 更改为 /forms/ 适用于 POST 请求,但不适用于 /forms

【问题讨论】:

  • 可以添加控制器代码吗?
  • 可能的不同是因为在GET请求中你没有发送参数,所以不介意你添加或不添加斜杠,但是在POST中你会添加一些参数,你需要添加一个适当的附加所有参数的 URL 操作
  • 您可以使用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.setUseTrailingSlashMatch(boolean) 全局控制此行为。您是否在某处将其设置为 false?
  • @cralfaro 这里是控制器代码 \@Controller public class JSONController { \@RequestMapping(value="/",method = RequestMethod.GET) public \@ResponseBody String handleGET(HttpServletRequest request ) { } \@RequestMapping(value="/",method = RequestMethod.POST) public \@ResponseBody String handlePOST(HttpServletRequest request) { } }

标签: java spring spring-mvc


【解决方案1】:

@RequestMapping 更改为无映射(所以不要输入任何值,甚至"/")或"/*"

【讨论】:

  • 都试过了。没用。就像在 RequestMapping 中甚至没有值一样,也没有值“/*”。
  • GET 请求根据您共享的链接正常工作。面临的问题是 POST 请求。它只是得到一个 302。但是 /forms/ 的 POST 请求工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-28
  • 2015-09-15
  • 2018-01-10
  • 2016-08-12
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
相关资源
最近更新 更多