Spring rest controller不返回html

时间:2017-04-06 18:59:03

标签: spring-mvc spring-boot thymeleaf

我正在使用弹簧启动1.5.2,我的弹簧控制器看起来像这样

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>

当我转到http://localhost:8090/assessment/它到达我的控制器但没有返回我的index.html,它位于src / main / resources或src / main / resources / static下的maven项目中。如果我转到此网址http://localhost:8090/assessment/index.html,则会返回我的index.html。我查看了这个教程https://spring.io/guides/gs/serving-web-content/,他们使用百里香。我是否必须使用百日咳或类似的东西让我的春季休息控制器回复我的观点?

我的应用程序类看起来像这样

@RestController
@RequestMapping("/")
public class HomeController {

    @RequestMapping(method=RequestMethod.GET)
    public String index() {
        return "index";
    }

}

当我将百万美元依赖项添加到我的类路径时,我收到此错误(500响应代码)

@SpringBootApplication
@ComponentScan(basePackages={"com.pkg.*"})
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

我想我确实需要百里香?我现在要尝试正确配置它。

在更改我的控制器方法以返回index.html后,它可以正常工作

org.thymeleaf.exceptions.TemplateInputException: Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

我认为百里香或类似的软件可以让你不用文件扩展名,但不确定。

4 个答案:

答案 0 :(得分:20)

RestController注释从方法而不是HTML或JSP返回json。它是@ Controller和@ResponseBody的结合体。 @RestController的主要目的是创建RESTful Web服务。对于返回html或jsp,只需使用@Controller注释控制器类。

答案 1 :(得分:6)

你的例子是这样的:

您的控制器方法与您的路线“评估”

.xml

“src / main / resources / templates / index.html”

中的Thymeleaf模板
@Controller
public class HomeController {

    @RequestMapping(value = "/assessment", method = RequestMethod.GET)
    public String index() {
        return "index";
    }

}

答案 2 :(得分:1)

请在thymeleaf documentation

中找到此链接以获取详细信息。

出现错误,因为您可能没有根据 “ springcofigration适配器” 制作MvcConfig类(需要添加视图解析器) 和用户@controller
如果您想使用json类型(作为AnjularJs项目),请使用@RestController)

答案 3 :(得分:0)

我通过从配置类中删除@EnableWebMvc注释解决了这个问题。

  

Spring MVC自动配置提供了静态index.html支持。

     

如果您想完全控制Spring MVC,可以添加您的   自己的@Configuration并用@EnableWebMvc注释。

Spring MVC Auto-configuration中获取更多细节。