springboot-web开发

138 阅读2分钟

访问静态资源

在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。 默认配置 Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:

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

image.png

image.png

微服务项目

前后端分离

前端----vue----前端工程师

后端---springboot--后端工程师

动静分离 部署cdn上--Cdn 减少带宽距离传输 减少自己服务器带宽;

YML与Properties用法

SpringBoot支持两种配置方式,一种是properties文件,一种是yml。 使用yml可以减少配置文件的重复性--使用较多。

properties文件

@RestController
public class PropertiesTest {
    @Value("${kkk.name}")
    private String name;
    @Value("${kkk.age}")
    private String age;
    @RequestMapping("/getProperties")
    public String getProperties(){
      return name+"=="+age;
    }

}
# properties文件
kkk.name=kkk
kkk.age=24

结果

image.png

YML文件

@RestController
public class PropertiesTest {
    @Value("${kkk.name}")
    private String name;
    @Value("${kkk.age}")
    private String age;

    @RequestMapping("/getYml")
    public String getYml(){
        return name+"=="+age;
    }
# YML文件
kkk:
  name: kkk2
  age: 25

结果

image.png

如何读取yml文件

#application.yml文件
kkk:
  name: kkk2
  age: 25
@RestController
public class ReadYml {
    @Value("${kkk.name}")
    private String name;
    @Value("${kkk.age}")
    private int age;
    @RequestMapping("/read")
    public String read(){
        return "name:"+name+"\n"+"age:"+age;
    }
}

结果:

image.png

渲染web页面

com.kkk.controller---视图层 渲染我们页面 com.kkk.service---业务逻辑层 com.kkk.dao---数据库访问层

前后端

渲染Web页面

在之前的示例中,我们都是通过@RestController来处理请求,所以返回的内容为json对象。那么如果需要渲染html页面的时候,要如何实现呢?

模板引擎 能够非常好的帮助seo搜索到该网页

在动态HTML实现上Spring Boot依然可以完美胜任,并且提供了多种模板引擎的默认配置支持,所以在推荐的模板引擎下,我们可以很快的上手开发动态网站。

Spring Boot提供了默认配置的模板引擎主要有以下几种:

  • Thymeleaf
  • FreeMarker
  • Velocity

Spring Boot建议使用这些模板引擎,避免使用JSP,若一定要使用JSP将无法实现Spring Boot的多种特性,具体可见后文:支持JSP的配置

当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。

使用FreeMarker模板引擎渲染web视图

举例

引入FreeMarker的依赖包

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath />
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--引入FreeMarker的依赖包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
    </dependencies>

编写controller类

@Controller
public class FreemarkerIndexController {
    @RequestMapping("/freemarkerIndex")
    public String freemarkerIndex(Map<String,String> result){
        //转发到页面需要展示的数据 key = name,value = kkk
        result.put("name","kkk");
        return "freemarkerIndex";
    }
}

编写ftl页面

在resources文件夹下创建templates文件夹,并新建freemarkerIndex.ftl文件,如下图所示:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
    ${name}
</body>
</html>

结果

image.png

Freemarker的其他用法--

两种方法

  • 用符号代替: > gt , >= gte ,< lt , <= lte
  • 加括号 <#if(x>y)>

举例

新建application.yml文件

spring:
  http:
    encoding:
      force: true
      ### 模版引擎编码为UTF-8
      charset: UTF-8
  freemarker:
    allow-request-override: false
    cache: false
    check-template-location: true
    charset: UTF-8
    content-type: text/html; charset=utf-8
    expose-request-attributes: false
    expose-session-attributes: false
    expose-spring-macro-helpers: false
    ## 模版文件结尾.ftl
    suffix: .ftl
    ## 模版文件目录
    template-loader-path: classpath:/templates

编写controller层

@Controller
public class FreemarkerIndexController {
    @RequestMapping("/freemarkerIndex")
    public String freemarkerIndex(Map<String,Object> result){
        //转发到页面需要展示的数据 key = name,value = kkk
        result.put("name","kkk");
        //假设0为男,1为女
        result.put("sex","0");
        result.put("age",23);
        ArrayList<String> list = new ArrayList<>();
        list.add("kkk");
        list.add("yyy");
        list.add("xxx");
        result.put("userlist",list);
        return "freemarkerIndex";
    }
}

编写freemarkerIndex.ftl页面

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
    ${name}
    <#if sex == '0'>
            男
        <#elseif sex == '1'>
            女
        <#else>
            其他
    </#if>
    <#if age gte 18>
        已经成年
    <#else>
        未成年
    </#if>
    <#list userlist as user>
        ${user}
    </#list>
</body>
</html>

结果

image.png

使用thymeleaf模板引擎渲染web视图

入门举例

pom文件引入依赖

<!--Spring SpringMVC  -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--引入thymeleaf的依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

写配置文件application.yml

###ThymeLeaf配置
spring:
  thymeleaf:
    #prefix:指定模板所在的目录
    prefix: classpath:/templates/
    #check-tempate-location: 检查模板路径是否存在
    check-template-location: true
    #cache: 是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。
    cache: true
    suffix:  .html
    encoding: UTF-8
    mode: HTML5

controller层

@Controller
public class MyThymeleafController {
    @RequestMapping("/myThymeleaf")
    public String myThymeleaf(Map<String,Object> result){
        result.put("user",new User("kkk", 22));
        return "myThymeleaf";
    }
}

//实体类
public class User {
    private String username;
    private int age;

    public User(String username, int age) {
        this.username = username;
        this.age = age;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

html页面

注意:一定要在HTML文件引入th标签 <html lang="en" xmlns:th="http://www.thymeleaf.org">

<!DOCTYPE html>
<!--需要在HTML文件中加入以下语句:引入th标签-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Show User</title>
</head>
<body>
<table>
    姓名:<span th:text="${user.username}"></span>
    年龄:<span th:text="${user.age}"></span>
</table>
</body>
</html>

结果

image.png

thymeleaf高级写法--each、if标签

controller层

@Controller
public class MyThymeleafController {
    @RequestMapping("/myThymeleaf")
    public String myThymeleaf(Map<String,Object> result){
        result.put("user",new User("kkk", 22));
        ArrayList<User> users = new ArrayList<>();
        users.add(new User("kkk1", 22));
        users.add(new User("kkk2", 23));
        users.add(new User("kkk3", 24));
        result.put("users",users);
        return "myThymeleaf";
    }
}

html页面

<!DOCTYPE html>
<!--需要在HTML文件中加入以下语句:引入th标签-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Show User</title>
</head>
<body>
<table>
    姓名:<span th:text="${user.username}"></span>
    年龄:<span th:text="${user.age}"></span>
    <ul th:each="userEach:${users}">
        <li th:text="${userEach.username}"></li>
        <li th:text="${userEach.age}"/>
        <li th:if="${userEach.age > 17}">已经成年</li>
        <li th:if="${userEach.age <= 17}">未成年</li>
    </ul>
</table>
</body>
</html>

结果

image.png