从控制器中删除@ResponseBody 时,收到 404 not found 错误消息 [英] When @ResponseBody is removed from the controller, getting 404 not found error message
问题描述
我有一个 spring boot 应用程序,我在其中创建了一个带有 @Controller
注释的控制器,当我尝试使用它显示的 url 访问资源时,它显示 404,未找到"
.但是一旦我在类级别或方法级别添加注释 @ResponseBody
,它就会给我所需的输出.我想在这里了解 @Responsebody
的作用,为什么它会影响 url 识别.据我所知 @ResponseBody
处理响应.
I have a spring boot application in which I am creating a controller with @Controller
annotation, when I tried to access the resource using the url it is showing me 404, "not found"
. But as soon as I add annotation @ResponseBody
at class level or method level, it gives me desired output. I want to understand the role of @Responsebody
here why it is affecting the url identification. As far as I know @ResponseBody
deals with the responses.
当我有如下代码时 -
When I have code like below -
@Controller
@RequestMapping(value = "test")
public class TestController {
@RequestMapping(value = "/m1")
public @ResponseBody String testMethod(){
return "Hello First Application";
}
}
它给了我一个精确的输出 Hello First Application
It is giving me an exact output as Hello First Application
当我从方法 testMethod()
中删除 @ResponseBody
时,它给了我以下输出.
when I remove @ResponseBody
from the method testMethod()
it gives me the following output.
{
"timestamp": "2019-06-13T06:36:14.510+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/test/m1"
}
我期待一个字符串作为响应.
I am expecting a string as a response.
推荐答案
此链接可能会解释您的需求:https://www.baeldung.com/spring-request-response-body
This link might explain what you need: https://www.baeldung.com/spring-request-response-body
基本上,注释告诉控制器对象格式正确.@Controller
通常用于返回视图,@RestController
用于JSON,不再需要@ResponseBody
.
Basically, the annotation tells the controller that the object is well formatted. @Controller
is usually used for returning views, and @RestController
is used for JSON, and no longer needs @ResponseBody
.
这篇关于从控制器中删除@ResponseBody 时,收到 404 not found 错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!