SpringBoot的WEB流程

springBoot web开发

springboot到底帮我们配置了什么?我们能不能修改?能修改那些东西?能不能扩展?

  • xxxxAutoConfiguration --> 向容器中自动配置组件

  • XXXXProperties:自动装配类,装配配置文件中的一些内容

要解决的问题:

  • 导入静态资源

  • 首页

  • jsp,模板引擎

  • 装配扩展springMVC

  • 增删改查

  • 拦截器

静态资源

   super.addResourceHandlers(registry);
if (!this.resourceProperties.isAddMappings()) {
   logger.debug("Default resource handling disabled");
} else {
   ServletContext servletContext = this.getServletContext();
   this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
   this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
       registration.addResourceLocations(this.resourceProperties.getStaticLocations());
       if (servletContext != null) {
           registration.addResourceLocations(new Resource[]{new ServletContextResource(servletContext, "/")});
      }

  });
}
  1. 在springboot中可以用以下方式访问静态资源

    • webjars: localhost:8080/wenjars(很少使用)

    • public,static, /**, resources, localhost:8080/

  2. 优先级

    resources>static(默认)>public

Thymeleaf模板引擎

Thymeleaf是跟Velocity、FreeMarker类似的模板引擎,它可以完全替代JSP,相较与其他的模板引擎,它主要有以下几个特点:

  1. Thymeleaf在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以thymeleaf的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

  2. Thymeleaf开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

  3. Thymeleaf提供spring标准方言和一个与SpringMVC完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

Thymeleaf官网:http://www.thymeleaf.org

Thymeleaf整合SpringBoot

  1. 在pom.xml文件引入thymeleaf

<dependency> 
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 在application.properties(application.yml)文件中配置thymeleaf

    # thymeleaf 
    spring.thymeleaf.prefix=classpath:/templates/
    spring.thymeleaf.check-template-location=true
    spring.thymeleaf.suffix=.html
    spring.thymeleaf.encoding=UTF-8
    spring.thymeleaf.content-type=text/html
    spring.thymeleaf.mode=HTML5
    spring.thymeleaf.cache=false
  2. 在html中添加命名空间

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
       <meta charset="UTF-8">
       <title>Title</title>
    </head>
    <body>
    <div th:text="${msg}">Test</div>
    </body>
    </html>

    html中的元素都可以被Thymeleaf替接管 , th:元素名

Thymeleaf语法

  • thymeleaf接管属性,以href为例:

    •     <!-- Bootstrap core CSS -->
      <link th:href="@{/asserts/css/bootstrap.min.css}" rel="stylesheet">
      <!-- Custom styles for this template -->
      <link th:href="@{/asserts/css/signin.css}" rel="stylesheet">
     ```

    @{路径名}

  • thymeleaf从后端的取值操作,和jsp中的jstl语法差不多

    • ${要取出的值}

    • 要用thymeleaf自带的工具类的话要用#开头

    • //标签内容为msg封装的内容,后面用strings类判断,如果msg为空则不显示该标签,不为空则显示
      <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
  • thymeleaf向后端传递参数

    • <!--注意要使用a标签,否则可能点击无效-->
      <a class="btn btn-sm btn-success" th:href="@{/employee/toUpdateEmp/}+${employee.getId()}">编辑</a>
      <a  class="btn btn-sm btn-danger" th:href="@{/employee/deleteEmp/}+${employee.getId()}">删除</a>
    • @{路径}+${参数},注意要使用a标签

  • thymeleaf引用公共页面代码

    • <!--顶部导航栏-->
      <nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topBar">
        页面部分
      </nav>


      <nav class="col-md-2 d-none d-md-block bg-light sidebar" th:fragment="sideBar">
      侧边栏部分
      </nav>



      引用部分:
      <div th:replace="~{commons/commons::topBar}"></div>
      <div th:replace="~{commons/commons::sideBar}"></div>
  • thymeleaf实现数据回显

    • <form th:action="@{/employee/updateEmp}" method="post">
                     <input type="hidden" name="id" th:value="${employee.getId()}">
                     <div class="form-group">
                         <label for="LastName">LastName</label>
                         <input th:value="${employee.getLastName()}" type="text" class="form-control" id="LastName" name="lastName" placeholder="LastName">
                     </div>
                     <div class="form-group">
                         <label for="Email">Email</label>
                         <input th:value="${employee.getEmail()}" type="email" class="form-control" id="Email" name="email" placeholder="Email">
                     </div>
                     <div class="form-group">
                         <label >Gender</label><br>
                         <div class="form-check form-check-inline">
                             <input th:checked="${employee.getGender()==1}" class="form- check- input" type= "radio" name= "gender" value="1" >
                             <label class= "form-check -label">男</label>
                         </div>
                         <div class="form-check form-check-inline">
                             <input th:checked="${employee.getGender()==0}" class="form- check- input" type= "radio" name= "gender" value="0" >
                             <label class= "form-check -label">女</label>
                         </div>
                     </div>
                     <div class="form-group">
                         <label>department</label>
                         <!--                   我们在controller中接受的是一个员工对象,所以我们要提交的是其中的一个属性(所属部门的一个属性)-->
                         <select class="form-control" name="department.id">
                             <option th:selected="${depart.getId()==employee.getDepartment().getId()}" th:each="depart:${departments}" th:text="${depart.getDepartmentName()}" th:value="${depart.getId()}"></option>
                         </select>
                     </div>
                     <div class="form-group">
                         <label>Birth</label>
                         <input th:value="${#dates.format(employee.getBirth(),'yyyy-MM-dd')}" type="text" name="birth" class="form-control" placeholder="BirthDay">
                     </div>
                     <button type="submit" class="btn btn-default">修改</button>
                 </form>
    • 单选框和下拉框的回显,用到了表达式。 三元运算符也很常见来动态显示标签内容

公共页面抽取

为了代码复用,将页面的公共部分抽取出来

在templates下面创建commons里面放置公用页面代码

错误页面配置

在templates文件夹创建一个error包,里面放置404,500等页面。springboot会自动的配置错误页面,

再次体现了约定大于配置的核心思想。

扩展springMVC

在config包下创建一个MvcConfig,功能如下:

  • 如果你想DIY定制化一些功能,只要写这个组件,然后把他交给springboot,spring boot就会自动帮我们装配,比如添加视图控制和拦截器。

  • 扩展springMVC 其实和重写springMVC差不多。

  • //如果你想diy定制化一些功能,只要写这个组件,然后把他交给springboot,spring boot就会自动帮我们装配
    //扩展springMVC 其实和重写springMVC差不多
    @Configuration
    // @EnableWebMvc //这个注解就是导入了一个类 :DelegatingWebMvcConfiguration:从容器中获取所有的webmvcconfig
    public class MyMvcConfig implements WebMvcConfigurer {
       //添加视图控制
       @Override
       public void addViewControllers(ViewControllerRegistry registry) {
           registry.addViewController("/").setViewName("index");
           registry.addViewController("/index.html").setViewName("index");
           registry.addViewController("/main.html").setViewName("dashboard");
      }
       
       @Override
       public void addInterceptors(InterceptorRegistry registry) {
           registry.addInterceptor(new LoginInterceptor())
                  .addPathPatterns("/**")
                  .excludePathPatterns("/","/index.html","static/**","/login");
      }
    }

     

原文地址:https://www.cnblogs.com/g414056667/p/14700967.html