当前位置:   article > 正文

spring boot的学习--Springboot的Web开发(3)

spring boot的学习--Springboot的Web开发(3)

1. 简介

1.1 创建springboot应用,选中我们需要的模块

1.2 springBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来

1.3 自己编写业务代码

顺便回顾下上一篇的自动装配

 这个场景SpringBoot帮我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?

2 springBoot对静态资源的映射规则

2.1 Springboot对静态资源的映射规则

      WebMvcAuotConfiguration:

  1. @ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
  2. public class ResourceProperties implements ResourceLoaderAware {
  3. //可以设置和静态资源有关的参数,缓存时间等
  4. @Override
  5. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  6. if (!this.resourceProperties.isAddMappings()) {
  7. logger.debug("Default resource handling disabled");
  8. return;
  9. }
  10. Integer cachePeriod = this.resourceProperties.getCachePeriod();
  11. if (!registry.hasMappingForPattern("/webjars/**")) {
  12. customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META‐INF/resources/webjars/").setCachePeriod(cachePeriod));
  13. }
  14. String staticPathPattern = this.mvcProperties.getStaticPathPattern();
  15. //静态资源文件夹映射
  16. if (!registry.hasMappingForPattern(staticPathPattern)) {
  17. customizeResourceHandlerRegistration(registry.
  18. addResourceHandler(staticPathPattern).addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod));
  19. }
  20. } /
  21. /配置欢迎页映射
  22. @Bean
  23. public WelcomePageHandlerMapping welcomePageHandlerMapping(
  24. ResourceProperties resourceProperties) {
  25. return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),
  26. this.mvcProperties.getStaticPathPattern());
  27. }
  28. //配置喜欢的图标
  29. @Configuration
  30. @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
  31. public static class FaviconConfiguration {
  32. private final ResourceProperties resourceProperties;
  33. public FaviconConfiguration(ResourceProperties resourceProperties) {
  34. this.resourceProperties = resourceProperties;
  35. }
  36. @Bean
  37. public SimpleUrlHandlerMapping faviconHandlerMapping() {
  38. SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
  39. mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
  40. //所有 **/favicon.ico
  41. mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
  42. faviconRequestHandler());
  43. return mapping;
  44. }
  45. @Bean
  46. public ResourceHttpRequestHandler faviconRequestHandler() {
  47. ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
  48. requestHandler.setLocations(this.resourceProperties.getFaviconLocations());
  49. return requestHandler;
  50. }
  51. }

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

 webjars:以jar包的方式引入静态资源;WebJars - Web Libraries in Jars

                                   localhost:8080/webjars/jquery/3.3.1/jquery.js

2.3 那如何引入jquert-webjar呢?

             在访问的时候只需要写webjars下面资源的名称即可

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

 2.4 "/**" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射

  1. "classpath:/META‐INF/resources/",
  2. "classpath:/resources/",
  3. "classpath:/static/",
  4. "classpath:/public/"
  5. "/":当前项目的根路径

             localhost:8080/abc === 去静态资源文件夹里面找abc

2.5 欢迎页; 静态资源文件夹下的所有index.html页面;被"/**"映射;(localhost:8080/ index页面

3. 模版引擎

JSPVelocityFreemarkerThymeleaf

SpringBoot推荐的Thymeleaf

         语法更简单,功能更强大;

3.1 如何引入thymeleaf呢

        在pom.xml中引入:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  4. </dependency>

 注意:

        从spring父文件中能看到Springboot2.0.1所使用的thymeleaf版本是3.0.9

        springBoot启动的时候会自动配置

                org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration

而从ThymeleafAutoConfiguration的源代码中我们可以得知ThymeleafProperties

中配置了Thymeleaf的规则

3.2 ThymeleafProperties中都配置了哪些呢?

  1. public class ThymeleafProperties {
  2. private static final Charset DEFAULT_ENCODING;
  3. public static final String DEFAULT_PREFIX = "classpath:/templates/";
  4. public static final String DEFAULT_SUFFIX = ".html";
  5. private boolean checkTemplate = true;
  6. private boolean checkTemplateLocation = true;
  7. private String prefix = "classpath:/templates/";
  8. private String suffix = ".html";
  9. private String mode = "HTML";
  10. private Charset encoding;
  11. private boolean cache;

 我们使用html作为模版,而且默认的前缀是放在classpath:/template/下,后缀是.html

  当然这些属性我们都可以通过application.properties来修改我们采用默认即可。

3.3 举个例子

  3.3.1  在template下创建一个success.html

  3.3.2  在html中引入thymeleaf的命名空间

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

  3.3.3 创建一个Controller提供一个访问的方法

  1. @RequestMapping("/success")
  2. public String hello(Model model){
  3. model.addAttribute("hello","<h1>renliang</h1>");
  4. return "success";
  5. }

  3.3.4    在thymeleaf模板中取值

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  2. "http://www.w3.org/TR/html4/loose.dtd">
  3. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  4. <head>
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <div th:text="${hello}"> </div>
  9. </body>
  10. </html>

4. 现在来学习下Thymeleaf语法

4.1 变量表达式

 变量表达式即OGNL表达式或Spring EL表达式(Spring术语中也叫model attributes)

        如下所示: ${session.user.name}

       它们将以HTML标签的一个属性来表示:

 

<span th:text="${book.author.name}"> 

4.2 选择(星号作为表达式)

选择表达式很像变量表达式,不过它们用一个预先选择的对象来代替上下文变量容器(map)来执行,如下: *{customer.name}

被指定的objectth:object属性定义:

  1. <div th:object="${book}">
  2.  ...
  3.  <span th:text="*{title}">...</span>
  4.  ...
  5. </div>

4.3 文字国际化表达式

    文字国际化表达式允许我们从一个外部文件获取区域文字信息(.properties),用Key索引Value,还可以提供一组参数(可选).

           #{main.title}

4.4 URL表达式

     URL表达式指的是把一个有用的上下文或回话信息添加到URL,这个过程经常被叫做URL

        重写。不需要指定项目名字
        @{/order/list} 

        URL还可以设置参数:@{/order/details(id=${orderId})} 

    让我们看这些表达式:

  1. <form th:action="@{/createOrder}">
  2. <a href="main.html" rel="external nofollow" th:href="@{/main}" rel="external n

4.5 表达式都支持哪些语法呢?

  1. 字面(Literals)
  2. 文本文字(Text literals): 'one text', 'Another one!',…
  3. 数字文本(Number literals): 0, 34, 3.0, 12.3,…
  4. 布尔文本(Boolean literals): true, false
  5. 空(Null literal): null
  6. 文字标记(Literal tokens): one, sometext, main,…
  7. 文本操作(Text operations)
  8. 字符串连接(String concatenation): +
  9. 文本替换(Literal substitutions): |The name is ${name}|
  10. 算术运算(Arithmetic operations)
  11. 二元运算符(Binary operators): +, -, *, /, %
  12. 减号(单目运算符)Minus sign (unary operator): -
  13. 布尔操作(Boolean operations)
  14. 二元运算符(Binary operators):and, or
  15. 布尔否定(一元运算符)Boolean negation (unary operator):!, not
  16. 比较和等价(Comparisons and equality)
  17. 比较(Comparators): >, <, >=, <= (gt, lt, ge, le)
  18. 等值运算符(Equality operators):==, != (eq, ne)
  19. 条件运算符(Conditional operators)
  20. If-then: (if) ? (then)
  21. If-then-else: (if) ? (then) : (else)
  22. Default: (value) ?: (defaultvalue)
  23. 例如:'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

4.6 常用的thymeleaf标签

好了,最后整体来个例子吧!       

   模板:

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  2. "http://www.w3.org/TR/html4/loose.dtd">
  3. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  4. <head>
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <div th:text="${hello}" th:id="${hello.toUpperCase()}">xxxx</div>
  9. <input th:value="${user.getUsername()}">
  10. <hr>
  11. <div th:object="${user}">
  12. <span th:text="*{username}"></span>
  13. </div>
  14. <a th:href="" th:if="${user.getAge() == 2}" >年龄</a>
  15. <a th:class="${user.getAge() > 2}?'class1':'class2'" >年龄</a>
  16. <p th:if="${user.score >= 60 and user.score < 85}">B</p>
  17. <p th:if="${user.score < 60}">C</p>
  18. <p th:if="${user.score > 85}">优秀</p>
  19. <span th:switch="${user.gender}">
  20. <p th:case="1"></p>
  21. <p th:case="2"></p>
  22. </span>
  23. <table>
  24. <tr th:each="a,aState:${uList}">
  25. <td th:text="${a.username}"></td>
  26. <td th:text="${a.password}"></td>
  27. <td th:text="${aState.index}"></td>
  28. </tr>
  29. </table>
  30. </body>
  31. </html>

  Controller中给的数据:

  1. @RequestMapping("/success")
  2. public String hello(HttpServletRequest req, HttpSession httpSession, Model model){
  3. model.addAttribute("hello","<h1>renliang</h1>");
  4. User user = new User();
  5. user.setPassword("111");
  6. user.setUsername("renliang");
  7. user.setAge(1);
  8. user.setScore(78);
  9. user.setGender(2);
  10. List<User> uList = new ArrayList<>();
  11. for (int i = 0; i < 10; i++){
  12. User u = new User();
  13. u.setUsername("renliang"+i);
  14. u.setPassword("111"+i);
  15. uList.add(u);
  16. }
  17. // httpSession.setAttribute("user", user);
  18. model.addAttribute("user", user);
  19. model.addAttribute("uList", uList);
  20. return "success";
  21. }

5. Springboot整合springmvc

 官网资料:  https://docs.spring.io/spring-boot/docs/2.0.2.RELEASE/reference/htmlsingle/#boot-features-spring-mvc

 (学习springmvc和springboot的自动配置我们必须对springmvc的组件足够了解,起码知道怎么用。Springmvc的组件基本都被springboot来做了自动的配置。

5.1 springmvc的自动配置管理

  1. 中央转发器(DispatcherServlet)
  2. 控制器
  3. 视图解析器
  4. 静态资源访问
  5. 消息转换器
  6. 格式化
  7. 静态资源管理

5.2 中央转发器(DispatcherServlet)

注意

  1. DispatcherServlet的自动注册:
  2. Spring Boot会自动注册并配置DispatcherServlet作为前端控制器,它是Spring MVC的核心组件,负责接收HTTP请求并分发到相应的处理器(Controller)

 XML不需要配置下面的

  1. <servlet>
  2. <servlet-name>chapter2</servlet-name>
  3. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  4. <load-on-startup>1</load-on-startup>
  5. </servlet>
  6. <servlet-mapping>
  7. <servlet-name>chapter2</servlet-name>
  8. <url-pattern>/</url-pattern>
  9. </servlet-mapping>

     中央转发器被springboot自动接管,不再需要我们在web.xml中配置,我们现在的项目也不是web项目,也不存在web.xml,

 在这里自动配置的哦 -》

org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\

5.3 控制器(也就是Controller)

        控制器Controller在springboot的注解扫描范围内自动管理

5.4 视图解析器自动管理

        Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.

ContentNegotiatingViewResolver:组合所有的视图解析器的

      以前的配置文件无需配置

  1. <bean id="de" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  2. <property name="prefix" value="/WEB-INF/jsp/"></property>
  3. <property name="suffix" value="*.jsp"></property>
  4. </bean>

源码:

  1. public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {
  2. ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
  3. resolver.setContentNegotiationManager((ContentNegotiationManager)beanFactory.getBean(ContentNegotiationManager.class));
  4. resolver.setOrder(-2147483648);
  5. return resolver;
  6. }

注意:当我们做文件上传的时候我们也会发现multipartResolver自动被配置好的

 页面:

  1. <form action="/upload" method="post" enctype="multipart/form-data">
  2. <input name="pic" type="file">
  3. <input type="submit">
  4. </form>

Controller:

  1. @ResponseBody
  2. @RequestMapping("/upload")
  3. public String upload(@RequestParam("pic")MultipartFile file, HttpServletRequest request){
  4. String contentType = file.getContentType();
  5. String fileName = file.getOriginalFilename();
  6. /*System.out.println("fileName-->" + fileName);
  7. System.out.println("getContentType-->" + contentType);*/
  8. //String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
  9. String filePath = "D:/imgup";
  10. try {
  11. this.uploadFile(file.getBytes(), filePath, fileName);
  12. } catch (Exception e) {
  13. // TODO: handle exception
  14. }
  15. return "success";
  16. }
  17. public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
  18. File targetFile = new File(filePath);
  19. if(!targetFile.exists()){
  20. targetFile.mkdirs();
  21. }
  22. FileOutputStream out = new FileOutputStream(filePath+fileName);
  23. out.write(file);
  24. out.flush();
  25. out.close();
  26. }

文件上传大小可以通过配置来修改---》打开application.properties, 默认限制是10MB,我们可以任意修改

5.5 消息转换和格式化

        5.5.1 Springboot自动配置了消息转换器

   格式化转换器的自动注册

时间类型我们可以在这里修改

在配置文件中指定好时间的模式我们就可以输入了

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/812946
推荐阅读
相关标签
  

闽ICP备14008679号