Spring Boot开发WEB页面

在上篇Spring Boot快速入门中,我们构建了一个简单的RESTful的应用,并在在浏览器中打印出了返回的字符串,本篇则介绍一下如何将结果渲染到页面上。

静态资源的默认配置位置

    Spring Boot默认的提供的静态文件配置路径位于classpath下,目录名称需要符合以下规定:

  • /static
  • /public
  • /resources
  • /META-INF/resources

模板引擎

    Spring Boot默认提供了多种模板引擎的支持,如:Thymeleaf、Velocity、FreeMarker等。尽量不要在Spring Boot中使用JSP,否则很多特性无法使用。在Spring Boot中默认的模板引擎路径是src/main/resources/templates,当然我们也可以修改这个默认路径。

web开发

    本文以Thymeleaf为例介绍如何在Spring Boot中使用模板引擎。

    1、引入依赖

    要使用Thymeleaf,我们只需要在pom中引入Thymeleaf的起步依赖即可,如下:

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

    2、编写Controller

    我们来编写一个简单的Controller返回一个单间的json字符串,如下:

@Controller
@RequestMapping(value = "/hello")
public class HelloController {

    @RequestMapping("/helloweb")
    public String hello(ModelMap modelMap){
        //向模板中添加属性
        modelMap.put("hello","helloweb");
        // return模板文件的名称,对应src/main/resources/templates/index.html
        return "index";
    }
}

    此处注意的一点是,一定要使用@Controller这个注解才可以跳转到对应的模板中,如果使用上一篇中的@RestController,页面只返回index这个字符串,这个注解等同于使用@ResponseBody,大家在使用时一定要注意。

    3、编写模板

    我们在src/main/resources/templates目录下创建一个叫index.html的文件,如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
<h1 th:text="${hello}">Hello</h1>
</body>
</html>

    以上代码开发完成以后,启动主程序,在浏览器上输入http://localhost:8080/hello/helloweb就会显示出Controller中Set的值。

修改Thymeleaf默认配置

    如果大家想修改Thymeleaf的默认配置,只需要在application.yml或者application.properties中修改配置即可,以下以application.yml为例

spring:
  thymeleaf:
    cache: true
    check-template-location: true
    content-type: text/html
    enabled: true
    encoding: utf-8
    mode: HTML5
    prefix: classpath:/templates/
    suffix: .html
    excluded-view-names:
    template-resolver-order: 

    ps:在使用.yml配置的时候,一定要注意,所有属性的Value值要跟“:”隔开一个空格,否则配置无效。

 

    最近在使用springboot的时候发现,当项目打成jar包放到服务器启动时,如果Controller中return页面时,如果以“/”开头的话,无法跳转到指定页面

转载于:https://my.oschina.net/wangxincj/blog/807909

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值