SpringBoot与Web开发(thymeleaf&servlet)

    技术2022-07-11  100

    文章目录

    SpringBoot与Web开发1 SpringBoot对静态资源的映射规则2 Thymeleaf模版引擎和使用2.1 引入thymeleaf依赖2.2 HTML导入thymeleaf的名称空间2.3 表达式2.4 例子 3 SpringBoot对SpringMVC的自动配置嵌入式Servlet容器

    SpringBoot与Web开发

    1 SpringBoot对静态资源的映射规则

    该类对web项目进行自动配置 public class WebMvcAutoConfiguration {}

    其中的方法addResourceHandlers对资源进行获取

    @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); return; } Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl(); if (!registry.hasMappingForPattern("/webjars/**")) { customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern) .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())) .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)); } } 其中/webjars/**,都去"classpath:/META-INF/resources/webjars/"找资源; webjars:以jar包的方式引入静态资源,webjars官网可以以maven依赖的方式,帮助我们导入需要的包 <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.5.1</version> </dependency>

    如图,自动在META-INF下的resource.webjars下找到jquery的包。想访问时只用写webjars下的资源名即可。 想访问时只用写webjars下的资源名即可。 运行项目在地址http://localhost:8080/webjars/jquery/3.5.1/jquery.js下可以访问到包内容。

    访问任何路径private String staticPathPattern = "/**";获取CLASSPATH_RESOURCE_LOCATIONS也就是默认路径 这就是静态资源的文件夹,默认处理 "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" "/" spring.resources.static-location = classpath:/hello/,classpath:/myself/ 访问localhost:8080默认打开的页面,就是静态资源为文件夹下的index.xml页面

    2 Thymeleaf模版引擎和使用

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

    2.1 引入thymeleaf依赖

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

    只需将HTML页面放在lasspath:/templates/文件下就能访问到,不需要在对SpringMVC的视图解析器InternalResourceViewResolver进行配置

    @RequestMapping("/success") public String success(){ //返回success页面,默认在classpath:/templates/success.html return "success"; }

    2.2 HTML导入thymeleaf的名称空间

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

    <!--th:text 将div里面的文本内容设置为${hello},覆盖"这是欢迎信息"--> <div id="div1" class="myDiv" th:id="${hello}" th:class="${hello}" th:text="${hello}">这是欢迎信息</div> 前端标签中的信息,都可以通过th:***对原生属性进行替换

    2.3 表达式

    简单表达式

    --VariableExpressions: ${...} 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 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) --SelectionVariableExpressions: *{...} 配合${...}使用 --MessageExpressions: #{...} 获取国际化内容 --LinkURLExpressions: @{...} 获取链接地址。格式:@{/order/process(execId=${execId},execType='FAST')} --Fragment Expressions: ~{...} 片段引用

    2.4 例子

    @RequestMapping("/success") public String success(Map<String,Object> map){ //发送到success页面 map.put("hello","<h1>你好</h1><br>"); map.put("users", Arrays.asList("张三","李四","王五")); //返回success页面,默认在classpath:/templates/success.html return "success"; } <!DOCTYPE html> <html lang="en" html xmlns:th="http://www.thymeleaf.org" > <head> <meta charset="UTF-8"> <title>成功</title> </head> <body> <a>操作成功</a> <!--th:text 将div里面的文本内容设置为${hello},覆盖"这是欢迎信息"--> <div id="div1" class="myDiv" th:id="${hello}" th:class="${hello}" th:text="${hello}">这是欢迎信息</div> <hr/> <!--转义,显示<h1>你好</h1><br>--> <div th:text="${hello}"></div> <!--不转义--> <div th:utext="${hello}"></div> <hr/> <!--遍历users--> <!--th:each遍历,每次遍历都生成标签--> <h4 th:text="${user}" th:each="user:${users}"></h4><br> <hr/> <a> <!--[[...]]等同于th :text [(...)]等同于th:utext--> <span th:each="users:${users}">[[${users}]]</span> </a> </body> </html>

    输出

    3 SpringBoot对SpringMVC的自动配置

    Spring Boot provides auto-configuration for Spring MVC that works well with most applications.

    The auto-configuration adds the following features on top of Spring’s defaults:

    Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans. 自动配置ViewResolver(视图解析器:根据方法的返回值得到视图对象View,视图对象决定如何渲染(转发/重定向))ContentNegotiatingViewResolver:组合所有的视图解析器自己给容器中添加视图解析器;自动将其组合进来 Support for serving static resources, including support for WebJars (covered later in this document))Static index.html support.Custom Favicon support (covered later in this document). 静态页面的访问 WebJars、index.heml、favicon.ico(图标) Automatic registration of Converter, GenericConverter, and Formatter beans. Converter转换器:页面传来的数据,封装时进行类型转换Formatter格式化器:2020.1.1 ->Date自己添加格式化器也可以加入容器 Support for HttpMessageConverters (covered later in this document). SpringMVC用来转换Http请求和响应:User->json Automatic registration of MessageCodesResolver (covered later in this document). 定义错误代码生成规则 Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).

    If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.

    如果想扩展SpringMVC,使用@Configuration,是WebMvcConfigurer类型,不能标注@EnableWebMvc。既保留了自动配置,也能使用扩展配置 //实现WebMvcConfigurer接口可以扩展SpringMVC功能 @Configuration public class MyMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { //浏览器发送/ok 请求来到 /success registry.addViewController("/ok").setViewName("success"); } }

    If you want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations and use it to provide custom instances of those components.

    If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc, or alternatively add your own @Configuration-annotated DelegatingWebMvcConfiguration as described in the Javadoc of @EnableWebMvc.

    加@EnableWebMvc完全替换SpringBoot的配置,只是用自己的配置

    嵌入式Servlet容器

    SpringBoot使用嵌入式Servlet容器(Tomcat)。以前的项目使用外置Tomcat作为Servlet容器。

    问题:

    定制和修改Servlet容器配置: - 修改和server相关的设置 - server: port: 8080 servlet: session: timeout: 10s #路径 context-path: /web #tomcat配置 tomcat: uri-encoding: utf-8 SpringBoot支持其他Servlet容器:
    Processed: 0.012, SQL: 9