spring - @RestController 返回空白
问题描述
我正在构建我的第一个 Spring Boot 应用程序。但我无法让我的 requestMapping 控制器正确回答。
这是我的主要课程:
package com.hello.world;
@SpringBootApplication
public class HelloWorld implements CommandLineRunner{
public static void main(String[] args) {
SpringApplication.run(HelloWorld.class, args);
}
@Override
public void run(String... args) throws Exception {
....
}
}
这是我的 RestController:
package com.hello.world.controllers;
@RestController
public class UrlMappingControllers {
@RequestMapping("/hi")
String home() {
return "Hello World!";
}
}
如果我查看日志,我可以看到“/hi”映射:
restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hi]}" onto java.lang.String com.hello.world.controllers.UrlMappingControllers.home()
但是当我访问: http:localhost:8080/hi 时,我得到一个空白页面,我希望看到“Hello World”文本。
为什么我得到一个空白页?
- - 编辑 - -
我刚刚意识到只有在添加 cxf 服务时才会得到空白页。我认为这是因为这个类上的@configuration注解:
package com.hello.world.helloWorld.configuration;
@Configuration
public class CXFConfiguration {
@Bean
public ServletRegistrationBean dispatcherServlet() {
return new ServletRegistrationBean(new CXFServlet(), "/services/*");
}
@Bean(name=Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
SpringBus springBus = new SpringBus();
return springBus;
}
@Bean
public Endpoint endpointGreentingService() {
EndpointImpl endpoint = new EndpointImpl(springBus(), new GreetingServiceImpl());
endpoint.getFeatures().add(new LoggingFeature());
endpoint.publish("/GreetingService");
return endpoint;
}
}
会不会有关系?
解决方案
@RestController = @Controller + @ResponseBody
这意味着当您http:localhost:8080/hi
在响应正文中调用您的 api 时,将包含home()
处理程序的结果,即“Hello world”。
@RestController
在幕后使 Spring MVC 使用 Json 消息转换器(默认情况下),并且带有注释的类中的所有处理程序方法都@RestController
将返回 JSON,这就是您在浏览器上看不到文本的原因。
您可以使用 Postman 或 ARC 来测试您的应用程序。某些 Web 浏览器(如 Firefox)直接显示 JSON。
推荐阅读
- json - 即使在代码编辑器中手动替换这些文本引号后,双引号在 JSON 验证器中也无效
- spring-security - 在本地开发中访问 Pivotal SSO 磁贴
- apache-camel - Camel rest JSON 使用 START_ARRAY 反序列化
- ruby-on-rails - Rails 控制器:调用关联模型记录以索引视图
- javascript - 如何在 SVG.js 中同时为多个属性设置动画?
- bash - 使用 bash 脚本中的 gnuplot 打印
- angularjs - 如何在 AngularJS (v1.6.10) 中使用来自 Angular (v7) 的组件?
- javascript - 如果单击按钮,则向前或向后进度轮播,否则会定时向前
- java - 在 ConnectableObservable 中执行异步查询的线程问题
- delphi - 是否可以在单独的单元中使用表单属性?