SpringBoot web 开发整合

580 阅读7分钟

添加spring boot父版本

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starters</artifactId>
    <version>2.1.6.RELEASE</version>
  </parent>

整合web

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

实际上, 该依赖包含了spring, spring-mvc, jackson等依赖.

测试环境

  1. 添加controller

     @RestController
     @RequestMapping("/home")
     public class indexController {
         @RequestMapping(value = "/",method = RequestMethod.GET)
         public Map<String,Object> home(){
             Map<String,Object> map = new HashMap<>();
             map.put("msg","hello spring boot");
             return map;
         }
     }
    
  2. 添加springboot启动类

     @SpringBootApplication
     public class SpringBootBranchApplication {
         public static void main(String[] args) {
             SpringApplication.run(SpringBootBranchApplication.class, args);
         }
     }
    
  3. 在application.properties下修改web监听端口

     server.port=8088
    
  4. 运行main 访问http://127.0.0.1/home/

说明环境搭建成功

整合servlet

方式1:扫描注解

1. 在servlet包下创建MyServlet类继承HttpServlet

     /**
     * 传统spring开发:
     * <servlet>
     *     <servlet-name>MyServlet</servlet-name>
     *     <servlet-class>com.lcd.branch.servlet.MyServlet</servlet-class>
     * </servlet>
     * <servlet-mapping>
     *      <servlet-name>MyServlet</servlet-name>
     *      <url-pattern>/my</url-pattern>
     * </servlet-mapping>
     */
    @WebServlet(name ="MyServlet",urlPatterns = "/my")
    public class MyServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("springboot中配置servlet成功................");;
        }
    }
  1. 修改启动类

     @SpringBootApplication
     @ServletComponentScan 
     public class SpringBootBranchApplication {
         public static void main(String[] args) {
             SpringApplication.run(SpringBootBranchApplication.class, args);
         }
     }
    

在springboot启动的时候, @ServletComponentScan注解会 扫描所有@WebServle注解,并进行实例化

  1. 测试: 访问: http://localhost:8088/my,控制台输出:

  1. 说明配置成功

方式二: 通过方法并标记@Bean完成

  1. 编写BeanServlet,继承HttpServlet

     public class BeanServlet extends HttpServlet {
         @Override
         protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
             System.out.println("注册bean方法的servlet配置成功");
         }
     }
    
  2. 在启动类下编写获取servlet方法:

     @SpringBootApplication
     @ServletComponentScan //springboot启动会扫描@WebServle注解t,并进行实例化
     public class SpringBootBranchApplication {
         public static void main(String[] args) {
             SpringApplication.run(SpringBootBranchApplication.class, args);
         }
         @Bean
         public ServletRegistrationBean getServletRegistrationBean(){
             ServletRegistrationBean registrationBean = new ServletRegistrationBean(new BeanServlet());
             registrationBean.addUrlMappings("/bean");
             return registrationBean;
         }
     }
    
  3. 测试: http://localhost:8088/bean

4. 说明配置成功

springboot整合filter

跟整合servlet一样也有两种方式,注解扫描+获取beans(FilterRegisterBean),这里主要演示第一种方式

  1. 在filter包下创建Myfilter类

       //@WebFilter(filterName = "MyFilter",urlPatterns = {"*.do","*.jsp"})
       @WebFilter(filterName = "MyFilter",urlPatterns = "/filter")
       public class MyFilter implements Filter {
           @Override
           public void init(FilterConfig filterConfig) throws ServletException {
           }
           @Override
           public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
               System.out.println("进入filter");
               filterChain.doFilter(servletRequest,servletResponse);
               System.out.println("离开filter");
           }
           @Override
           public void destroy() {
           }
       }
    
  2. 启动类上添加@ServletComponentScan注解既可.

  3. 测试访问: http://127.0.0.1/8088/filter

  4. 控制台输出

  5. 说明整合filter成功

springboot整合Listener

跟整合servlet一样也有两种方式,注解扫描+获取beans(ServletListenerRegisterBean),这里主要演示第一种方式

  1. 在listen包下创建MyListener监听器, 这里演示的是监听server上下文

    @WebListener
    public class MyListener implements ServletContextListener {
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            System.out.println("servlet上下文监听器初始化");
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            System.out.println("servlet上下文监听器销毁");
        }
    }
    
  2. 启动类上添加@ServletComponentScan注解既可.

  3. 测试:项目启动的时候

  4. 说明配置listener成功

springboot整合静态资源访问

  1. 在resource的static下均可以通过http url来访问(比如在static下images下有张jwt.png图片)

springboot整合文件上传

  1. 首先编写html

         <!DOCTYPE html>
         <html lang="en">
         <head>
             <meta charset="UTF-8">
             <title>文件上传</title>
         </head>
         <body>
         <form enctype="multipart/form-data" method="post" action="/file/upload">
             文件:<input type="file" name="file"/>
             姓名:<input type="text" name="name"/>
             <input type="submit" value="上传"/>
         </form>
         </body>
         </html>
    
  2. 编写controller

     @RestController
     @RequestMapping("/file")
     public class FileUploadController {
         private final static String filePath = "E://java/logs/";
         @RequestMapping("/upload")
         public Map<String,Object> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
             // 姓名
             String name = request.getParameter("name");
             System.out.println("姓名:" + name);
             // 文件名
             String fileName = file.getOriginalFilename();
             System.out.println("文件名: " + fileName);
             // 文件后缀
             String suffixName = fileName.substring(fileName.lastIndexOf("."));
             System.out.println("文件后缀名: " + suffixName);
             // 重新生成唯一文件名,用于存储数据库
             String newFileName = UUID.randomUUID().toString()+suffixName;
             System.out.println("新的文件名: " + newFileName);
             //创建文件
             File dest = new File(filePath + newFileName);
             file.transferTo(dest);
             Map map = new HashMap();
             map.put("filePath", dest.getAbsolutePath());
             map.put("name", name);
             return map;
         }
     }
    
  3. 修改上传设置

     spring.servlet.multipart.max-file-size=1024MB
     spring.servlet.multipart.max-request-size=1024MB
    

springboot整合mybatis

包括druid数据源, druid监控

  1. 添加pom.xml 依赖

     <dependency>
         <groupId>org.mybatis.spring.boot</groupId>
         <artifactId>mybatis-spring-boot-starter</artifactId>
         <version>1.3.2</version>
     </dependency>
     <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
     </dependency>
    
  2. application.properties配置

         ##mysql连接信息
         spring.datasource.url=jdbc:mysql://localhost:3306/mmal?characterEncoding=utf-8&useSSL=false
         spring.datasource.username=root
         spring.datasource.password=xxx.xxx.xxx
         spring.datasource.driver-class-name=com.mysql.jdbc.Driver
         
         #####数据源配置#########
         ##数据源类别
         spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
         ##初始化大小
         spring.datasource.druid.initial-size=3
         ##最大
         spring.datasource.druid.max-active=20
         ##最小
         spring.datasource.druid.min-idle=2
         ##获取连接等待超时的实际,单位毫秒
         spring.datasource.druid.max-wait=60000
         ##多久进行一次检测,检测需要关闭的空闲连接,单位毫秒
         spring.datasource.druid.time-between-eviction-runs-millis=60000
         ###配置一个连接在池中最小生成的时间,单位毫秒
         spring.datasource.druid.min-evictable-idle-time-millis=300000
         spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
         spring.datasource.druid.test-while-idle=true
         spring.datasource.druid.test-on-borrow=false
         spring.datasource.druid.test-on-return=false
         ##配置监控统计拦截的filters
         spring.datasource.druid.filters=stat,wall
         ## druid sql 监控
         spring.datasource.druid.stat-view-servlet.enabled=true
         spring.datasource.druid.web-stat-filter.enabled=true
         spring.datasource.druid.filter.stat.enabled=true
         spring.datasource.druid.filter.stat.log-slow-sql=true
         spring.datasource.druid.filter.stat.slow-sql-millis=30000
         spring.datasource.druid.filter.stat.merge-sql=true
         spring.datasource.druid.web-stat-filter.url-pattern=/*
         
         
         ##控制台输出sql语句
         logging.level.com.lcd.branch.dao=debug
         ##配置mybatis
         ##映射文件位置
         mybatis.mapper-locations=classpath:mappers/*.xml
         ##类型别名包配置
         mybatis.type-aliases-package=package com.lcd.branch.pojo
    
    1. 编写配置类

       @Configuration
       public class DruidConfiguration {
           @Bean
           public ServletRegistrationBean druidStatViewServle(){
               //ServletRegistrationBean提供类注册
               ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
               //添加初始化参数 initParams
               //白名单
               servletRegistrationBean.addInitParameter("allow","127.0.0.1");
               //ip黑名单 存在共同, deny优先allow
               servletRegistrationBean.addInitParameter("loginUsername","root");
               servletRegistrationBean.addInitParameter("loginPassword","root");
               //能否重置数据
               servletRegistrationBean.addInitParameter("resetEnable","false");
               return servletRegistrationBean;
           }
       
           public FilterRegistrationBean druidStatFilter(){
               FilterRegistrationBean filterRegistrationBean
                       =new FilterRegistrationBean(new WebStatFilter());
               //添加过滤规则
               filterRegistrationBean.addUrlPatterns("/*");
               //添加忽略的格式信息
               filterRegistrationBean.addInitParameter("exclusions",
                       "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
               return filterRegistrationBean;
           }
       }
      
    2. 访问localhost:8088/druid/index.html

    3. 编写dao接口,mapperxxx.xml实现(普通的dao,xml,pojo可以通过mabatis-generator-plugin插件生成)

    4. 编写service接口以及service实现类

    5. 启动类上添加@MapperScan({"com.lcd.branch.dao"})

    springboot整合分页插件pageHelper

    1. 添加pom.xml依赖

       <dependency>
           <groupId>com.github.pagehelper</groupId>
           <artifactId>pagehelper-spring-boot-starter</artifactId>
           <version>1.2.5</version>
       </dependency>
      
    2. application.properties添加分页插件配置

       ##分页插件
       pagehelper.helper-dialect=mysql
       pagehelper.reasonable=true
       pagehelper.support-methods-arguments=true
       pagehelper.params=count=countSql
      
    3. 方法使用

       @RequestMapping(value = "/list",method = RequestMethod.GET)
       public PageInfo<User> list(){
       PageHelper.startPage(1,1);
       List<User> users = iUserService.selectUsers();
       PageInfo result = new PageInfo(users);
       return result;
       }
      

    springboot整合redis

    1. 添加pom.xml依赖

       <dependency>
       	<groupId>org.springframework.boot</groupId>
       	<artifactId>spring-boot-starter-data-redis</artifactId>
       </dependency>
      
    2. application.properties

       ## redis配置
       spring.redis.port=6379
       spring.redis.host=127.0.0.1
       ##默认redis数据库为db0
       spring.redis.database=0
       ##连接池最大连接数,使用负数表示没有限制
       spring.redis.jedis.pool.max-active=8
       ##连接池最大阻塞时间,使用负数表示没有限制
       spring.redis.jedis.pool.max-wait=-1
       ##连接池最大空闲数
       spring.redis.jedis.pool.max-idle=8
       ## 连接池最小空闲连接
       spring.redis.jedis.pool.min-idle=0
       ##连接超时时间,单位毫秒
       spring.redis.timeout=1000
      
    3. 编写controller测试

       @RequestMapping(value = "/redis",method = RequestMethod.GET)
       public String testRedis(){
           redisTemplate.opsForValue().set("name","lcd");
           String name = (String)redisTemplate.opsForValue().get("name");
           return name;
       }
      
    4. 访问localhost:8088/home/redis 返回lcd

    5. RedisTemplate操作redis的方法:

      • opsForList: 操作含有list的数据
      • opsForSet: 操作含有set的数据
      • opsForZSet: 操作含有ZSet(有序set)的数据
      • opsForHash: 操作含有hash的数据

springboot整合AOP

  1. pom.xml依赖

     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-aop</artifactId>
     </dependency>
    
  2. 编写AOP类, 加上@Aspect和@component注解即可

  • @PointCut: 切片点表达式
  • @Before("pointCut()"): 前置通知, 在目标方法运行之前 JoinPoint joinPoint
  • @After("pointCut()") :后置通知 在目标方法运行结束运行(无论方法是正常结束还是异常结束)
  • @AfterReturing("pointCut()",returning = "result"): 返回通知, 在目标方法运行正常通知 public void logReturn(Object result) ;
  • @AfterThrowing(value = "pointCut()", throwing = "exception") 异常通知,在目标方法运行出现异常通知, public void logThrown(Exception exception)
  • -@Around(value = "pointCut()") 环绕通知, 目标方法运行执行前后 public Object logAround(ProceedingJoinPoint pdj)

为了保证执行顺序,需要 AOP 继承 org.springframework.core.Ordered 接口,继承了 Ordered 接口之后需要覆写 getOrder() 方法,返回的数字越小,执行的顺序越靠前。

整合Swagger2接口文档

  1. 添加pom.xml依赖

     <dependency>
         <groupId>io.springfox</groupId>
         <artifactId>springfox-swagger2</artifactId>
         <version>2.4.0</version>
     </dependency>
     <dependency>
         <groupId>io.springfox</groupId>
         <artifactId>springfox-swagger-ui</artifactId>
         <version>2.4.0</version>
     </dependency>
    
  2. 添加配置类 这里只是添加一些简单配置,具体可以看源码

     @Configuration
     @EnableSwagger2
     public class SwaggerConfig {
     
         @Bean
         public Docket createRestApi(){
             return new Docket(DocumentationType.SWAGGER_2)
                     //指定构建API文档的返回
                     .apiInfo(apiInfo())
                     .select()
                     // 指定要生成 API 接口的包路径,这里把 Controller 作为包路径,生成 Controller 中的所有接口
                     .apis(RequestHandlerSelectors.basePackage("com.lcd.branch.controller"))
                     .paths(PathSelectors.any())
                     .build();
         }
     
         private ApiInfo apiInfo() {
             return new ApiInfoBuilder()
                     .title("springboot继承swagger2接口")
                     .description("项目接口文档")
                     .contact(new Contact("lcd","xxx.xxx.xxx","chengdong2518@163.com"))
                     //设置联系方式
                     .version("1.0")
                     .build();
         }
     }
    

注意: 这里有个坑, 这个配置类必须跟项目启动类写一个包类, 否则会错误.

常用:

    类: @Api(value="用户相关业务的接口", tags= {"用户相关业务的controller"})
    方法: @ApiOperation(value="用户上传头像", notes="用户上传头像的接口")
          @ApiImplicitParam(name="userId", value="用户id", required=true,         						dataType="String", paramType="query")