gpt4 book ai didi

spring-boot - SpringBoot 中使用@PathVariable 的方法返回空响应

转载 作者:行者123 更新时间:2023-12-02 01:11:18 29 4
gpt4 key购买 nike

我正在尝试编写一个采用@PathVariable 参数并将用户重定向到jsp 文件的方法。

@Controller
public class MainController
{

@RequestMapping("/user/{customerId}")
// http://localhost:8080/Test/user/5
public String getCustomerById(@PathVariable("customerId") String customerId, Model model)
{
model.addAttribute("customer_id", customerId);
// this is the user_details.jsp file, I need to show this jsp file to visitor
return "user_details";
}
}

当我尝试导航 http://localhost:8080/SpringBlog/user/5 时它向我展示了一个空洞的回应。 (甚至在页面源代码中也没有)

当我查看 Spring 输出控制台时,它在我尝试导航时向我显示以下消息:

2017-07-19 13:24:56.191 ERROR 6772 --- [io-8080-exec-75]

o.s.boot.web.support.ErrorPageFilter

Cannot forward to error page for request [/user/5] as the response has already been committed. As a result, the response may have the wrong status code. If your application is running on WebSphere Application Server you may be able to resolve this problem by setting com.ibm.ws.webcontainer.invokeFlushAfterService to false

我已经尝试过如下参数描述:

@PathVariable(value="customerId") String customerId

@PathVariable(name="customerId") String customerId

@PathVariable("customerId") String customerId

@PathVariable String customerId

它们都不起作用,总是有相同错误消息的空响应。

我确定所有文件都在正确的位置,在我的 MainController 类中我有几种没有参数、RequestParams 等的方法。它们都按预期工作。但是,如果我想使用 @PathVariable 创建 RequestMapping,它总是在输出控制台中返回空响应和相同的错误消息。

但是如果我用@RestController 尝试相同的方法,它会按预期工作:

@RestController
public class RestApi
{
// http://localhost:8080/Test/api/user/56
// Is Working, Returns Hello 56 As Response
@RequestMapping("api/user/{customerId}")
public String apiTest(@PathVariable("customerId") String customerId)
{
return "Hello "+customerId;
}
}

我错过了什么?

申请详情:

<packaging>war</packaging>
...
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
...

Apache Tomcat/7.0.56
JVM 1.8.0_131-b11

感谢您的帮助。

最佳答案

注释 @RestController 自动将 @ResponseBody 添加到您的方法中。

@ResponseBody 所做的是使用 HttpMessageConverter 将传出的返回值绑定(bind)到 HTTP 响应主体。如果您不添加 @RestController@ResponseBody 注释,那么 Spring 将尝试将其解析为 View ,通常是 JSP 页面。

所以在你的情况下,Spring 试图找到匹配 "Hello"+customerId 的 View ,而不是打印出 "Hello"+customerId 的结果。

所以您正确地使用了@PathVariable 注释。 :)

您可以阅读更多 here

关于spring-boot - SpringBoot 中使用@PathVariable 的方法返回空响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45189324/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com