您的位置:首页 > 编程语言 > Java开发

Spring boot返回静态页面初识

2018-01-18 16:43 344 查看
转发请注明来源,谢谢!

背景:需要使用Spring boot做一点前端,不知道怎么访问HTML。。。一番疯狂搜索,看到有直接各种版本,但自己模仿实现又不行,一番焦灼,做点总结

一.不使用任何模板框架(thymeleaf等)返回HTML



说明: Spring Boot 默认配置的/**映射到/static(或/public ,/resources,/META-INF/resources),借用的其他博客说明,我只测试了static,其他路径有兴趣的可以试试,也就是说这些路径下的资源都是静态的。

1. maven配置,新建项目,默认配置

```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!-- 下面配置可以不用 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>1.5.8.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
```


2. 配置文件application第一个是空的,第二个是我的数据库配置,和本次测试无关

3. 直接controller返回static路径下的HTML(indexs.html内容在最后)

```
@RequestMapping(value = "/indexs",method = RequestMethod.GET)
//@ResponseBody
public String showIndexs(){
return "/indexs.html";
}
```


4. 不使用模板默认访问static下的资源,返回必须要带.html,必须是/indexs.html(亲测)

5. 说明一点,这里注解应该用@Controller,而不是@RestController(会直接返回一个字符串而不是HTML内容),区别自己查咯

二.使用thymeleaf模板返回HTML

添加maven配置

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>


修改Controller,下面三种方式都可行,亲测,注意返回的文件路径

@RequestMapping(value = "/html",method = RequestMethod.GET)
public ModelAndView showlist(){
ModelAndView mv =  new ModelAndView("index");
return mv;
}

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

@RequestMapping("/hello")
public String helloHtml(HashMap<String, Object> map) {
map.put("hello", "欢迎进入HTML页面");
return "/index";
}


return 有没有“/”都可以;不需要配置任何东西(正式项目可能需要配置缓存等等其他);不能带.html后缀

index.html和indexs.html内容一样

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>

95d5
<meta charset="UTF-8"/>
<title>第一个HTML页面</title>
</head>
<body>
<h1>Hello Spring Boot!!!</h1>
<p th:text="${hello}"></p>
</body>
</html>


理解还是很浅,待以后深入了再来做补充。

有问题欢迎私信或者评论
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: