2017-04-06 149 views
3

我使用的是春天启动1.5.2和我的弹簧安置控制器弹簧安置控制器看起来像这样没有返回HTML

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

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

} 

当我去http://localhost:8090/assessment/到达我的控制器,但不回我的索引。 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/,他们使用百里香。我是否必须使用百里香或类似的东西来让我的弹簧控制器恢复我的视野?

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

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

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

当我添加到我的类路径中thymeleaf依赖我得到这个错误(500响应代码)

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

我想我需要thymeleaf?我现在要尝试正确配置它。

它可以改变我的控制器方法后返回的index.html像这样

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

我觉得thymeleaf或软件,如它可以让你不用输入这些文件的扩展名,不知道虽然。

+2

对于初学者来说,让它成为['Controller'](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Controller.html)而不是' RestController' –

+0

现在它仍然到达控制器,但是我得到了一个404,无论index.html是在src/main/resources还是在src/main/resources/static中。 http:// localhost:8090/assessment/index.html仍然有效 – gary69

回答

2

你的例子是这样的:

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

@Controller 
public class HomeController { 

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

} 

在你Thymeleaf模板 “的src /主/资源/模板/ index.html的”

<!DOCTYPE HTML> 
<html xmlns:th="http://www.thymeleaf.org"> 
<head> 
    <title>Getting Started: Serving Web Content</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
</head> 
<body> 
    <p>Hello World!</p> 
</body> 
</html> 
9

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

+0

我已将其更改为@Controller,现在我得到了404,但请求映射仍在工作。我是否需要添加视图解析器bean? http:// localhost:8090/assessment/index.html仍然有效 – gary69

+0

网址http:// localhost:8090/assessment/working? –

+0

没有什么是什么给了我404 – gary69