0%

SpringBoot-Web开发

SpringBoot-Web开发

1、使用SpringBoot

  1. 创建SpringBoot应用,选中需要的模块
  2. SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行
  3. 自己编写业务代码

2、SpringBoot对静态资源的映射规则

  1. 所有/webjars/**,都去classpath::/META-INF/resources/webjars/找资源

    webjars:以jar包的方式引入静态资源

    1
    2
    3
    4
    5
    6
    7
    8
    <!--        引入jquery-webjar
    在访问时,只需要写webjars下面的资源名称即可
    -->
    <dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.4.1</version>
    </dependency>

  2. "/**",访问当前项目的任何资源(静态资源文件夹)

    "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" "/":当前项目的根路径

    即:

    src->main->resources->public/resources/static

    访问路径:localhost:8080/xxx

  3. 欢迎页;静态资源文件夹下的所有index.html页面,被"/**"映射

    localhost:8080/找到index页面

  4. 所有的**/favicon.ico都是在静态资源文件夹下找

3、模板引擎

JSP、Velocity、Freemarker、Thymeleaf

SpringBoot推荐Thymeleaf:语法更简单,功能更强大

Thymeleaf使用

  1. 引入依赖

    1
    2
    3
    4
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
  2. 只需要把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染

  3. 引入<html xmlns:th="http://www.thymeleaf.org">

Thymeleaf语法

  1. th:text:改变当前元素里面的文本内容

    th:任意html属性;来替换原生属性的值

    Order Feature Attributes 解释
    1 Fragment inclusion th:insert th:replace 片断包含:jsp:include
    2 Fragment iteration th:each 遍历:c:forEach
    3 Conditional evaluation th:if th:unless th:switch th:case 条件判断c:if
    4 Local variable definition th:object th:with 声明变量:c:set
    5 General attribute modification th:attr th:attrprepend th:attrappend 任意属性修改,支持前后追加
    6 Specific attribute modification th:value th:href th:src ... 修改指定属性默认值
    7 Text (tag body modification) th:text th:utext 修改标签体内容,utext不转义特殊字符
    8 Fragment specification th:fragment 声明片断
    9 Fragment removal th:remove 移除片断
  2. 表达式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    Simple expressions: (表达式语法)
    Variable Expressions: ${...}:获取变量值:OGNL
    1)、获取对象属性、调用方法
    2)、使用内置的基本对象
    #ctx: the context object.
    #vars: the context variables.
    #locale: the context locale.
    #request: (only in Web Contexts) the HttpServletRequest object.
    #response: (only in Web Contexts) the HttpServletResponse object.
    #session: (only in Web Contexts) the HttpSession object.
    #servletContext: (only in Web Contexts) the ServletContext object.
    3)、内置的一些工具对象:
    #execInfo: information about the template being processed.
    #messages: methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
    #uris: methods for escaping parts of URLs/URIs
    #conversions: methods for executing the configured conversion service (if any).
    #dates: methods for java.util.Date objects: formatting, component extraction, etc.
    #calendars: analogous to #dates, but for java.util.Calendar objects.
    #numbers: methods for formatting numeric objects.
    #strings: methods for String objects: contains, startsWith, prepending/appending, etc.
    #objects: methods for objects in general.
    #bools: methods for boolean evaluation.
    #arrays: methods for arrays.
    #lists: methods for lists.
    #sets: methods for sets.
    #maps: methods for maps.
    #aggregates: methods for creating aggregates on arrays or collections.
    #ids: methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
    Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样的
    补充:配合th:object="${}使用
    Message Expressions: #{...}:获取国际化内容
    Link URL Expressions: @{...}:定义URL
    @{/order/process(execId=${execId};execType='FAST')}
    Fragment Expressions: ~{...}:片断引用表达式

    Literals(字面量)
    Text literals: 'one text', 'Another one!',…
    Number literals: 0, 34, 3.0, 12.3,…
    Boolean literals: true, false
    Null literal: null
    Literal tokens: one, sometext, main,…

    Text operations:(文本操作)
    String concatenation: +
    Literal substitutions: |The name is ${name}|

    Arithmetic operations:(数学运算)
    Binary operators: +, -, *, /, %
    Minus sign (unary operator): -

    Boolean operations:(布尔运算)
    Binary operators: and, or
    Boolean negation (unary operator): !, not

    Comparisons and equality:(比较运算)
    Comparators: >, <, >=, <= (gt, lt, ge, le)
    Equality operators: ==, != (eq, ne)

    Conditional operators:(条件运算)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)
    Special tokens:(特殊)
    No-Operation: _

4、RestfulCRUD

  1. 默认访问首页

  2. 国际化

    步骤:

    1. 编写国际化配置文件,抽取页面需要显示的国际化消息

    2. SpringBoot自动配置好了管理国际化资源文件的组件

      1
      spring.messages.basename=i18n.login
    3. 1
      #{login.username}

      效果:根据浏览器语言设置的信息切换国际化

      原理:国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象),默认就是根据请求头带来的区域信息获取Locale进行国际化

    4. 点击链接切换国际化

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      public class MyLocaleResolver implements LocaleResolver {
      @Override
      public Locale resolveLocale(HttpServletRequest httpServletRequest) {
      String l = httpServletRequest.getParameter("l");
      Locale locale = Locale.getDefault();
      if(!StringUtils.isEmpty(l)){
      String[] s = l.split("_");
      locale = new Locale(s[0], s[1]);
      }
      return locale;
      }

      @Override
      public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

      }
      }
      1
      2
      3
      4
      @Bean
      public LocaleResolver localeResolver(){
      return new MyLocaleResolver();
      }
  3. 登录

    开发期间模板引擎页面修改后要实时生效

    • 禁用模板引擎的缓存

      1
      2
      # 禁用缓存
      spring.thymeleaf.cache=false
    • 页面修改后,ctrl+f9,重新编译

    • 登录错误消息的显示

      1
      <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
  4. 拦截器进行登录检查

    1
    2
    3
    4
    5
    6
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    // 注册拦截器
    registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
    .excludePathPatterns("/index.html","/","/user/login","/webjars/**");
    }
  5. CRUD-员工列表

    1. RestfulCRUD:CRUD满足Rest风格

      URI:/资源名称/资源标识 HTTP请求方式区分对资源CRUD操作

      普通CRUD(uri来区分操作) RestfulCRUD
      查询 getEmp emp---GET
      添加 addEmp?xxx emp---POST
      修改 updateEmp?id=xxx&xxx=xx emp/{id}---PUT
      删除 deleteEmp?id=xx emp/{id}---DELETE
    2. 请求架构

      请求URI 请求方式
      查询所有员工 emps GET
      查询某个员工 emp/{id} GET
      来到添加页面 emp GET
      添加员工 emp POST
      来到修改页面(查出员工进行信息回显) emp/{id} GET
      修改员工 emp PUT
      删除员工 emp/{id} DELETE
    3. 员工列表

      • thymeleaf公共页面元素抽取

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        <!-- 1、抽取公共片断-->
        <div th:fragment="copy">

        </div>

        <!-- 2、引入公共片断 -->
        <div th:insert="~footer::copy">

        </div>
        ~{templatename::selector}:模板名:选择器
        ~{templatename::fragmentname}:模板名:片断名

        默认效果:
        insert的公共片段在div标签中
        如果使用th:insert等属性进行引入,可以不定~{}
        行内写法可以加上:[[~{}]];[(~{})]

        三种引入公共片断的th属性:

        th:insert:将公共片断整个插入到声明引入的元素

        th:replace:将声明引入的元素替换为公共片断

        th:include:将被引入的片断的内容包含进这个标签中

        引入片断的时候传入参数: