SpringBoot web development integration

SpringBoot web development integration

Add spring boot parent version

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

Integrated web

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

In fact, this dependency includes spring, spring-mvc, jackson and other dependencies.

test environment

  1. Add 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. Add springboot startup class

     @SpringBootApplication
     public class SpringBootBranchApplication {
         public static void main(String[] args) {
             SpringApplication.run(SpringBootBranchApplication.class, args);
         }
     }
     
  3. Modify the web listening port under application.properties

     server.port=8088
     
  4. Run main to visit http://127.0.0.1/home/

Shows that the environment is successfully built

Integrated servlet

Method 1: Scan annotations

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. Modify the startup class

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

When springboot starts, the @ServletComponentScan annotation will scan all @WebServle annotations and instantiate them

  1. Test: Visit: http://localhost:8088/my, console output:

  1. The configuration is successful

Method 2: Pass the method and mark @Bean to complete

  1. Write BeanServlet, inherit HttpServlet

     public class BeanServlet extends HttpServlet {
         @Override
         protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
             System.out.println(" bean servlet ");
         }
     }
     
  2. Write the get servlet method under the startup class:

     @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. Test: http://localhost:8088/bean

4. The configuration is successful

springboot integrated filter

There are two ways to integrate servlet, annotation scanning + getting beans (FilterRegisterBean), here is the first way to demonstrate

  1. Create the Myfilter class under the filter package

      //@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. Add the @ServletComponentScan annotation to the startup class.

  3. Test visit: http://127.0.0.1/8088/filter

  4. Console output

  5. Indicates that the filter is integrated successfully

springboot integrated Listener

There are two ways to integrate servlet, annotation scanning + getting beans (ServletListenerRegisterBean), here is the first way to demonstrate

  1. Create a MyListener listener under the listen package, here is the listening server context

    @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. Add the @ServletComponentScan annotation to the startup class.

  3. Testing: when the project starts

  4. It shows that the listener configuration is successful

springboot integrates static resource access

  1. It can be accessed through http url under static resource (for example, there is a jwt.png picture under images under static)

Springboot integrated file upload

  1. First write 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. Write the 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. Modify upload settings

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

springboot integrates mybatis

Including druid data source, druid monitoring

  1. Add pom.xml dependency

     <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 configuration

         ##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. Write configuration class

       @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. Visit localhost:8088/druid/index.html

    3. Write dao interface, mapperxxx.xml implementation (ordinary dao, xml, pojo can be generated through the mabatis-generator-plugin plug-in)

    4. Write service interface and service implementation class

    5. Add @MapperScan({"com.lcd.branch.dao"}) to the startup class

    springboot integrated paging plugin pageHelper

    1. Add pom.xml dependency

       <dependency>
           <groupId>com.github.pagehelper</groupId>
           <artifactId>pagehelper-spring-boot-starter</artifactId>
           <version>1.2.5</version>
       </dependency>
       
    2. application.properties add paging plugin configuration

       ## 
       pagehelper.helper-dialect=mysql
       pagehelper.reasonable=true
       pagehelper.support-methods-arguments=true
       pagehelper.params=count=countSql
       
    3. Method use

       @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 integrates redis

    1. Add pom.xml dependency

       <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. Write controller test

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

    5. RedisTemplate operation redis method:

      • opsForList: Operate data containing list
      • opsForSet: Operate data containing set
      • opsForZSet: Operate data containing ZSet (ordered set)
      • opsForHash: Operate data containing hash

Springboot integrates AOP

  1. pom.xml dependency

     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-aop</artifactId>
     </dependency>
     
  2. Write the AOP class, add @Aspect and @component annotations

  • @PointCut: slicing point expression
  • @Before("pointCut()"): pre-notification, JoinPoint joinPoint before the target method runs
  • @After("pointCut()"): The post notification is executed at the end of the target method (regardless of whether the method ends normally or abnormally)
  • @AfterReturing("pointCut()",returning = "result"): return notification, notify when the target method runs normally public void logReturn(Object result);
  • @AfterThrowing(value = "pointCut()", throwing = "exception") Exception notification, exception notification occurs when the target method is running, public void logThrown(Exception exception)
  • -@Around(value = "pointCut()") surround notification, before and after the target method is executed public Object logAround(ProceedingJoinPoint pdj)

In order to ensure the order of execution, AOP needs to inherit the org.springframework.core.Ordered interface. After inheriting the Ordered interface, you need to override the getOrder() method. The smaller the number returned, the higher the order of execution.

Integrate Swagger2 interface documentation

  1. Add pom.xml dependency

     <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. Add configuration classHere is just to add some simple configuration, you can see the source code for details

     @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();
         }
     }
     

Note: There is a pit here, this configuration class must write a package class with the project startup class, otherwise it will be wrong.

Commonly used:

     : @Api(value=" ", tags= {" controller"})
     : @ApiOperation(value=" ", notes=" ")
          @ApiImplicitParam(name="userId", value=" id", required=true,         						dataType="String", paramType="query")