首页 > 解决方案 > @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;
        }
}

会不会有关系?

标签: springspring-mvcspring-boot

解决方案


@RestController = @Controller + @ResponseBody这意味着当您http:localhost:8080/hi在响应正文中调用您的 api 时,将包含home()处理程序的结果,即“Hello world”。

@RestController在幕后使 Spring MVC 使用 Json 消息转换器(默认情况下),并且带有注释的类中的所有处理程序方法都@RestController将返回 JSON,这就是您在浏览器上看不到文本的原因。

您可以使用 Postman 或 ARC 来测试您的应用程序。某些 Web 浏览器(如 Firefox)直接显示 JSON。


推荐阅读