SpringBoot及Thymeleaf快速入门

1.为什么使用SpringBoot

  • 因为Spring、SpringMVC的使用需要大量的配置文件,还要配置各种对象,将使用的对象放入Spring容器才能使用对象过于麻烦。
  • SpringBoot就相当于不需要配置文件的Spring+SpringMVC。常用的框架和第三方库都已经配置好了;拿来就可以使用了。
  • 使用方便、开发效率高

2.JavaConfig

JavaConfig:使用java类作为xml配置文件的替代,是配置spring容器的纯java的方式。在这个java类中可以创建java对象,把对象放入spring容器中(注入到容器)

使用到两个注解:

  1. @configuration:放在一个类的上面,表示这个类是作为配置文件使用的

  2. @Bean:声明对象,将对象注入到容器中

    @Configuration//当前类用做配置文件使用,配置容器
    public class SpringConfig {
         
    //    创建方法,方法的返回值是对象,方法上@Bean
    //    方法的返回值就注入到容器中了
        @Bean//将对象注入到spring容器中,相当于<bean>
    //    @Bean(name = "zsStu")指定名称id,不指定名称则默认是方法名
        public Student creatStudent(){
         
            Student student = new Student("张三",26,"男");
            return student;
        }
    }
    

    使用:

    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    Student student = (Student) ctx.getBean("creatStudent");//未指定id是方法名
    

3.@ImportResource

@ImportResource是导入xml配置,等同于xml文件的resource

//在配置类上添加该注释,导入xml文件配置,要带classes
@ImportResource(value = {
   "classes:beans.xml",..})

4.@PropertyResource

@PropertyResource是读取properties属性配置文件,实现外部化配置

  • resources目录下存放properties文件,k=v格式

  • @PropertyResource指定properties文件位置

  • 使用:@Value(value=“${key}”)

    @Configuration//当前类用做配置文件使用,配置容器
    @ImportResource(value = {
         "classes:beans.xml"})//xml导入
    @PropertySource(value = "classpath:config.properties")//properties文件读取
    @ComponentScan(basePackages = "jv.com.vo")//包扫描
    public class SpringConfig {
         ..}
    //使用properties文件读取的数据tiger.name
    @value("${tiger.name}")String name;
    

5.什么是SpringBoot

​ SpringBoot是Spring家族中的一个成员,可以简化Spring、SpringMVC的使用。他的核心还是IOC容器。

​ 特点:

  1. 创建Spring应用
  2. 内嵌的Tomcat、jetty,undertow服务器
  3. 提供了starter起步依赖,简化应用的配置
  4. 尽可能去配置spring和第三方库,称为自动配置(spring和第三方的对象都创建好放入容器中,开发时可直接使用)
  5. 提供了健康检查、统计、外部化配置
  6. 无需生成代码、无需使用xml,做配置

6.创建SpringBoot项目

  1. 使用Spring提供的初始化器,向导创建SpringBoot应用
  2. 使用国内地址:https://start.springboot.io 快速构建springboot框架
  3. 使用普通maven项目

7.注解的使用

  • ​ @SpringBootApplication:是个复合注解,由以下三个注解组成

    1. @SpringBootConfiguration: //注解标注的类可当作配置文件使用,可用@Bean声明对象并注入到容器
    2. @EnableAutoConfiguration: //启用自动配置,把java对象配置好注入到spring容器中,例如可把mybatis对象创建好,放入容器中
    3. @ComponentScan://扫描器,找到注解根据注解的功能创建对象,给属性赋值等等;默认扫描的包:@ComponentScan所在的包和子包。

8.SpringBoot的配置文件

​ 配置文件名称:application

扩展名有:

  1. properties(k=v)

    #设置端口号
    server.port=8080
    #设置应用上下文路径 contextpath
    server.servlet.context-path=/myboot
    
  2. 和 yml(k:v)

    server:
      port: 8082
      servlet:
        context-path: /myboot2
    

9.多环境配置

  • 开发者环境、测试环境、上线环境
  • 每个环境有不同的配置信息,如上下文文件、端口、数据库url、用户名、密码等等
  • 使用多环境配置文件,可以方便的切换不同的配置
  • 使用方式:(创建多个配置文件 ,名称规则:application-环境名称.yml(properties))
    • 创建开发环境的配置文件:application-dev.yml(properties)
    • 创建测试环境的配置文件:application-test.yml(properties)
    • 创建上线环境的配置文件:application-online.yml(properties)

10.@ConfigurationProperties读取配置文件

@ConfigurationProperties:读取配置文件中的数据交给一个java实体类,对其属性赋值。

@ConfigurationProperties(prefix = "school")

11.使用容器

想通过代码从容器中获取对象,可通过SpringApplication.run(Applicattion.class,args);返回值获取容器。

12.CommandLineRunner和ApplicationRunner接口

  • 这俩个接口都有一个run方法;执行时间是在容器对象创建好之后自动执行run()方法,可完成自定义的在容器对象创建好的一些操作。

13.Web组件——拦截器

  • 拦截器是SpringMVC中的一种对象,能拦截Controller的请求。

  • 拦截器框架中有系统的拦截器,还可以自定义拦截器,实现对请求的预先处理。

  • Springmvc中自定义拦截器:

    1. 创建类去实现springmvc中的HandlerInterceptor接口,实现其中方法

    2. 声明拦截器

      <mvc:interceptors>
      	<mvc:interceptor>
          	<mvc:path="url"></mvc:path>
              <bean class="拦截器类全限定名"></bean>
          </mvc:interceptor>
      </mvc:interceptors>
      
  • 在springboot中自定义拦截器:

    • 创建类去实现springmvc中的HandlerInterceptor接口,实现其中方法
    • 配置类中实现WebMvcConfigurer接口实现addInterceptor方法
    @Configuration
    public class SpringConfig implements WebMvcConfigurer {
         
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
         
            LInterceptor interceptor = new LInterceptor();//拦截器
            registry.addInterceptor(interceptor)
                    .addPathPatterns("/user/**")
                    .excludePathPatterns("/user/login");
        }
    }
    

14.Web组件——Servlet

  1. 创建自定义Servlet类

    public class MyServlet extends HttpServlet {
         
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.print("执行Servlet");
        }
    }
    
  2. 在配置类中注册Servlet

    @Configuration
    public class WebApplicationConfig {
         
        @Bean
        public ServletRegistrationBean servletRegistrationBean(){
         
            ServletRegistrationBean<Servlet> b = new ServletRegistrationBean<>();
            b.setServlet(new MyServlet());
            b.addUrlMappings("/test","/login");
            return b;
        }
    

15.Web组件——Filter过滤器

Filer是Servlet规范中的过滤器,可以处理请求,对请求的参数、属性进行调整。常常在过滤器中处理字符编码

在框架中使用过滤器:

  1. 创建自定义过滤器类

    public class MyFilter implements Filter {
         
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
         
            System.out.println("执行了MYFilter doFilter");
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }
    
  2. 注册Filter过滤器对象

    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
         
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new MyFilter());
        bean.addUrlPatterns("/user/*");
        return bean;
    }
    

16.字符集过滤器

  • CharacterEncodiongFilter:解决post请求中乱码问题

  • 在MVC中,是在web.xml注册过滤器,配置属性。

  • 在Spring中默认配置了CharacterEncodiongFilter编码是ISO-8859-1,因此我们重新设置字符集的话就必须在application.yml核心配置中写上:server.servlet.encoding.enabled=false //关闭系统默认的过滤器,使用自定义的字符集过滤器

    第一种方式:

  • 步骤:

    配置类中注册设置字符集的Filter

    //配置类中注册设置字符集的Filter
    @Bean
    public FilterRegistrationBean filterCharacterRegistrationBean(){
         
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        //使用框架中的Filter: CharacterEncodingFilter
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("utf-8");//指定编码
        filter.setForceEncoding(true);// req、res都应用
        bean.setFilter(filter);
        bean.addUrlPatterns("/*");
        return bean;
    }
    

    修改application.properties核心配置,关闭系统默认的过滤器,使用自定义的字符集过滤器

    server.servlet.encoding.enabled=false
    

    第二种方式:直接在application.properties配置(推荐)

    #指定编码
    server.servlet.encoding.charset=utf-8  
    #req、res都应用
    server.servlet.encoding.force=true  
    

17.ORM(对象关系映射)操作数据库

  • 使用MyBatis框架操作数据库,在SpringBoot框架中集成的MyBatis

  • 步骤:

    1. mybatis起步依赖:完成MyBatis对象自动配置,对象放在容器中

    2. pom.xml文件中指定src/main/java目录中的xml文件包含到classpath中

    3. 创建实体类

    4. 创建Dao接口及对应的Mapper文件,写sql语句

    5. 创建Service层接口及实现类,需要拿到dao对象去调用方法完成数据库操作

    6. 创建Controller对象,访问Service

    7. 写application.properties文件,配置数据库

      server.port=9001
      server.servlet.context-path=/orm
      #连接数据库连接池,cj.的驱动版本更新
      spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
      spring.datasource.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
      spring.datasource.username=root
      spring.datasource.password=hsp
      
  • 第一种方式:@Mapper

    放在dao接口上,每个接口都需要注解

    @Mapper//告诉MyBatis,这是dao接口,创建此接口的代理对象
    public interface StudentDao {
         
        Student queryById(@Param("stuId") Integer id);
    }
    
  • 第二种方式:@MapperScan扫描

    在SpringBootApplication类上添加@MapperScan

    /**
     * @MapperScan :找到Dao接口和mapper.xml文件
     *        basePackages:dao接口所在的包名
     */
    @SpringBootApplication
    @MapperScan(basePackages = "com.jv.dao")
    public class Application {
         
       public static void main(String[] args) {
         
          SpringApplication.run(Application.class, args);
       }
    }
    
  • 第三种方式:可将Dao接口和Mapper文件分开

    1. 在resource资源目录下新建目录mapper(自定义)用来保存XXDao.xml文件

    2. 在application.properties中指定mapper文件的目录:(编译后会放到target的classes文件中,所以用关键字classpath指定文件目录)

      #指定mapper文件位置
      mybatis.mapper-locations=classpath:mapper/*.xml
      
    3. pom中将src/main/resources的文件都放到target文件中

      <build>
      <!--      resources插件-->
            <resources>
               <resource>
                  <directory>src/main/resources</directory>
                  <includes>
                     <include>**/*.*</include>
                  </includes>
               <
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值