【发布时间】:2017-08-03 11:12:22
【问题描述】:
我有一个带有以下详细信息的 Spring MVC 应用程序
- war 文件名为 forms.war。 web.xml 中的 url 模式是
"/" - 控制器操作的@RequestMapping 是
"/" - 如果 localhost:8080/forms 被命中,RequestMethod.GET 操作会正常工作
- 如果发布数据与
localhost:8080/forms匹配,则不会触发 RequestMethod.POST 操作 - POST 请求提供 302 重定向
- 当我点击
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