SpringBoot - Web开发

发布时间 2023-03-25 04:34:03作者: 家兴Java

SpringBoot Web开发

自动装配

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

  • xxxAutoConfiguration...向容器中自动配置组件
  • xxxProperties:自动配置类,装配配置文件中自定义的一些内容

web开发要解决的问题:

  1. 导入静态资源(html,css,js……)

  2. 首页

  3. jsp(模版引擎Thymeleaf)

  4. 装配扩展SpringMVC

  5. 增删改查

  6. 拦截器

  7. 国际化

(5.6.7见后续)

静态资源

总结:

  1. 在springboot中,我们可以使用一下方式处理静态资源
    • wabjars 映射路径为:localhost:8080/webjars/(下面的目录结构)
    • public,static,/**,resources 映射路径为:localhost:8080/(可以直接访问)
  2. 优先级:resources > static(默认) > public

模板引擎

要使用thymeleaf,只需要导入对应的依赖就可以了,将html放在templates目录下即可

依赖:

<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring5 -->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-java8time -->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
  1. 导入约束

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <!--链接以@开头,文本用#取出-->    
    <!--html的所有标签都可以被thymeleaf替换接管: th: + 标签名称 |接管后就可以使用表达式了-->
    
  2. 编写Controller类

    @Controller
    public class IndexController {
    
        @RequestMapping("test")
        public String index(Model model){
            model.addAttribute("msg","<h1>hello,springboot</h1>");
            model.addAttribute("users", Arrays.asList("qinjiang","zhangsan","kuangshen"));
            return "test";
        }
    }
    
  3. 在html取值

    <!--html的所有标签都可以被thymeleaf替换接管: th: + 标签名称 |接管后就可以使用表达式了-->
    <div th:text="${msg}"></div>
    <div th:utext="${msg}"></div>
    
    <hr/>
    
    <h3 th:each="user:${users}" th:text="${user}"></h3>
    <!--<h3 th:each="user:${users}">[[${user}]]</h3>
    
类型 取值方式
变量 $
选择变量 *
消息 #
URL @
片段表达式 ~

扩展MVC

  1. 创建config文件夹下MyMVCConfig类

  2. 实现WebMvcConfigurer

    // 扩展springmvc
    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer {
    }
    
  • 接管视图解析器

    如果想自定义一些定制化的功能,只要写这个组件,让后将它交给springboot,springboot就会帮我们自动装配

    // 扩展springmvc
    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer {
    
        @Bean
        public ViewResolver myViewResolver(){
            return new MyViewResolver();
        }
    
        // 自定义了一个自己的视图解析器 MyViewResolver
        public static class MyViewResolver implements ViewResolver{
    
            @Override
            public View resolveViewName(String viewName, Locale locale) throws Exception {
                return null;
            }
        }
    
    }