Skip to content

11. Spring Boot的Web开发支持

使用spring-boot-starter-web启动器,开始web支持,内嵌一个Tomcat,添加了对于SpringMVC的支持。Spring Boot默认servlet容器为tomcat。

Spring Boot supports the following embedded servlet containers:

NameServlet Version
Tomcat 9.04.0
Jetty 9.43.1
Undertow 2.04.0

11.1. 常用的服务器配置

配置端口号Spring Boot 默认端口是8080,如果想要进行更改的话,在配置文件中加入:server.port=8081 配置context-pathserver.servlet.context-path=/spring-boot访问地址就是http://ip:port/spring-boot

配置session的超时时间server.servlet.session.timeout=2M

全量的配置内容

点我查看--common-application-properties

11.2. 替换Tomcat

使用jetty服务器替换Tomcat

11.2.1. 创建springboot的项目,编写Controller测试

  1. 创建maven项目(quickstart)

  2. Maven项目添加parent

  3. 添加web启动器、

4 编写Controller 测试

java
package com.neuedu.jetty.contoller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JettyController {


    /**
     * http://127.0.0.1/index
     * @return
     */
    @GetMapping("/index")
    String jettyMain(){

        return "欢迎访问 jetty..";
    }
}
  1. 编写入口程序
java
package com.neuedu.jetty;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App03 {
    public static void main(String[] args) {
        SpringApplication.run(App03.class, args);
    }
}

9.2.2. 测试Tomcat

img

9.2.3. 引入jetty的启动器

排除Tomcat的启动器

也不能引入jasper,因为jasper会依赖Tomcat。

xml
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

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

11.3. Jetty对jsp的支持

springboot中的jetty为内嵌的jetty,支持jsp需要添加额外的依赖

xml
  <!--jetty容器支持jsp start-->
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>apache-jsp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>apache-jstl</artifactId>
        </dependency>
 <!--jetty容器支持jsp end-->

11.3.1. 创建了一个控制器

11.3.2. 编写了一个jsp

img

11.4. 自动配置的ViewResolver

在WebMvcAutoConguration类中有一个内置的Bean InternalResourceViewResolver

img

通过WebMvcProperties配合所有的mvc的属性前缀spring.mvc

在属性文件中配置视图解析器解析jsp的前后缀

11.4.1. 配置视图解析器:

img

11.5打包时对jsp的影响

boot程序打包是需要添加maven插件

xml
  <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>

boot默认打jar包,没有编译jsp的目录,如果需要使用jsp,则修改打包方式为 war,启动的命令

sh
java -jar xxxxxx.war

11.6. 对静态资源的配置

在 WebMvcAutoConfiguration 类中的静态类 WebMvcAutoConfigurationAdapter 中,可以找到其对静态资源的相关自动配置,包括

11.6.1. 类路径文件:

把类路径下的 /static、/public、/resources 和 /META-INF/resources 文件夹下的静态文件直接映射为 /,可以直接通过 http://localhost:8080/ 访问。和 Spring MVC 中自定义 addResourceHandler、addResourceLocations 的原理一样。

11.6.2. webjar:

就是一种 jar 包,即将常用的 web 脚本框架封装在 jar 包中,然后再整个封装的 jar 包。关于更多可以访问官网http://www.webjars.org

把 webjar 的 /META-INF/resources/webjars/ 下的静态文件映射为 /webjar/,,可以通过 http://localhost:8080/webjar/ 访问。

img

资源文件的配置类ResourceProperties

img

静态资源文件位置

img

img

11.6.3. 自定义静态资源的映射关系

Spring Boot的静态资源配置有两项

  • spring.mvc.static-path-pattern:

    • 代表的含义是我们应该以什么样的路径来访问静态资源,即用于阐述HTTP请求地址
  • spring.resources.static-locations

    • 配置Spring Boot应该在何处查找静态资源文件,这是一个列表性的配置,查找文件时会依赖于配置的先后顺序依次进行,默认的官方配置如下

,默认的官方配置如下

properties
spring.mvc.static-path-pattern=/
spring.resources.static-locations= classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resources
  • 自定义配置静态资源的映射关系
properties
spring.mvc.static-path-pattern=/st/

spring.resources.static-locations=classpath:/mystatic,classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resources

img

11.7. Convert和Formatter

Convert、Formatter

:用于接收浏览器请求的参数自动转化成响应类型的数据Stirng(1988-01-01)-Date(1988-01-01)

11.7.1. User实体

11.7.2. UserController接受实体参数

java
package com.neuedu.entity;

import java.util.Date;

//@Data
public class User {

    private String id;
    private Integer age;
    private String address;
    private Date createTime;


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Integer getAge() {
        return age;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                ", createTime=" + createTime +
                '}';
    }
}



package com.neuedu.controller;

import com.neuedu.entity.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConverterController {
    
    /**
     * http://127.0.0.1:8080/user?createTime=2021-04-07
     * @param user
     * @return
     */
    @GetMapping("/user")
    User getUserInfo(User user){

        return user;
    }
    

}

11.7.3. 请求路径:

http
http://127.0.0.1:8080/user?createTime=2021-04-07

默认接受日期类型是报错(原因是string类型没有自动转换成java.util.Date)

img

9.6.4. 配置自定义的Convert解决日期类型的参数转换

声明一个Bean类型Convert的子类

java
package com.neuedu.config;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConverter implements Converter<String, Date> {

    static String[] pattens = {
            "yyyy-MM-dd",
            "yyyy/MM/dd",
            "yyyy-MM-dd HH:mm:ss",
            "yyyy/MM/dd HH:mm:ss"
    };


    @Override
    public Date convert(String source) {
        Date date = null;
        try {

            if(source.matches("\\d{4}-\\d{1,2}-\\d{1,2}")){
                date = new SimpleDateFormat(pattens[0]).parse(source);
            }else if(source.matches("\\d{4}/\\d{1,2}/\\d{1,2}")){
                date = new SimpleDateFormat(pattens[1]).parse(source);
            }else if(source.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")){
                date = new SimpleDateFormat(pattens[2]).parse(source);
            }else if(source.matches("\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}")){
                date = new SimpleDateFormat(pattens[3]).parse(source);
            }

            return date;
        } catch (ParseException e) { }

        return null;
    }
    
}

11.8. HttpMessageConverters

作用:将不同类型的对象转换成http消息输出到浏览器中:

自动注册的 HttpMessageConverter,

除了 Spring MVC 默认的

ByteArrayHttpMessageConverter

StringHttpMessageConverter

ResourceHttpMessageConverter 文件下载的时候可以依赖

SourceHttpMessageConverter

AllEncompassingFormHttpMessageConverter

在类路径上自动配置了一些其他的类型

img

11.9. Jackson的配置

  1. 配置格式化字符串 (全局)

  2. 设置时区 GMT+8

img

11.9.1. 对Controller设置日期格式

请求的时候绑定变量,将当前的Controller中所有日期都使用一种格式

img

11.9.2. 对实体中的属性进行单独设置格式

  1. 接受字符串格式的设置

在实体的属性上添加@DateFormat注解

  1. 响应字符串的格式设置

在实体的属性上添加@JsonFormat注解

img

11.9.3. 响应json字符串中日期设置:

1 使用spring.jackcon.dataFormat设置全局的

2 对于特殊的格式单独使用JsonFormat注解实现个性化的日期格式

11.10. 日期格式的总结:

11.10.1. 请求:

  1. 使用DateFormat注解 可以指定格式

在某一个字段上指定

  1. 在Controller中添加@InitBinder注解方法,注册Controller全局的格式编辑器

当前Controller都会生效,无论什么字段都按照一个格式处理,有局限性

  1. 使用Convert

全局的转换器,可以自定义转换方式,实现多种日期格式的接受

11.10.2. 响应(Jackson):

1 ) 在全局配置文件中定义jsckson的dateFormat

所有日期都会按照一个格式响应,可以将比较常用的格式在dateFormat中声明

2) 在实体的属性上声明@JsonFormat注解(优先级比配置文件的声明高)

将个性化的日期使用JsonFormat去格式化。

Released under the MIT License.