Springboot advanced-01

Time:2022-8-3

Springboot advanced JDBC, Druid, mybatis, swagger, springmvc, mail

1.Springboot-JDBC

  1. After integrating JDBC with springboot, spring boot starter JDBC is introduced to operate the database through jdbctemplate.

  2. Import dependency

org.springframework.boot
    spring-boot-starter-jdbc
  1. Operate the database through jdbctemplate to add, delete, modify and query
@RestController
public class UserController {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/delete")
    public String delete() {
        String sql = "delete from tb_user where id = 9";
        jdbcTemplate.update(sql);
        return "delete ok";
    }

    @GetMapping("/update")
    public String update() {
        String sql = "update tb_user set name= 'tom9' where id = 9";
        jdbcTemplate.update(sql);
        return "update ok";
    }

    @GetMapping("/insert")
    public String insert() {
        String sql = "insert into tb_user (id,name,age) values (10,'tom10',10)";
        jdbcTemplate.update(sql);
        return "insert ok";
    }

    @GetMapping("/get")
    public List> getList() {
        String sql = "select * from tb_user";
        List> list = jdbcTemplate.queryForList(sql);
        return list;
    }
}

2.Springboot-Druid

  1. Import dependency
com.alibaba
    druid
    1.2.6





    log4j
    log4j
    1.2.17
  1. Application.yaml configure Druid connection pool
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
    type: com.alibaba.druid.pool.DruidDataSource

    #Spring boot does not inject these attribute values by default, and needs to be bound through druiddatasource
    #Druid data source proprietary configuration
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    #Configure filters for monitoring statistics interception, stat: monitoring statistics, log4j: logging, wall: Defense SQL injection
    #If it is allowed, the error java.lang.classnotfoundexception: org.apache.log4j.priority will be reported
    #Then import log4j dependency. Maven address: https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  1. Druid connection pool configuration and druiddatasource binding in yaml
@Configuration
public class DruidConfiguration {

    /**
     *Other Druid configurations in yaml will not be imported by default. They need to be loaded when creating druiddatasource
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return new DruidDataSource();
    }
}
  1. Configure the servlet that accesses Druid
@Configuration
public class DruidConfiguration {

    /**
     *Configure the servlet accessed by Druid
     *Springboot project has no web.xml configuration. Servlets and filters can be configured through
     *Servletregistrationbean and filterregistrationbean are added to the container.
     * @return
     */
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean registrationBean = new ServletRegistrationBean<>();
        //Add statviewservlet
        registrationBean.setServlet(new StatViewServlet());
        //Configure the access path, and the background access path of Druid
        registrationBean.setUrlMappings(Arrays.asList("/druid/*"));

        //These parameters can be found in com.alibaba.druid.support.http.statviewservlet
        //The parent class of com.alibaba.druid.support.http Found in resourceservlet
        //Druid access login password
        Map map = new HashMap<>();
        map.put("loginUsername", "root");
        map.put("loginPassword", "123456");

        //Only this machine can access
        //An error occurs when the configuration is localhost. Java.lang.illegalargumentexception: invalid IP address [localhost]
        //It can be configured as map put("allow", "127.1.0.0");
        // map.put("allow", "localhost");
        map.put("allow", "127.1.0.0");

        //Allow= "", anyone can access
        //map.put("allow", "");

        //No access
        map.put("tom", "192.168.133.125");

        registrationBean.setInitParameters(map);
        return registrationBean;
    }
}
  1. Configure the filter monitored by Druid
@Configuration
public class DruidConfiguration {

    /**
     *Configure the filter monitored by Druid
     *Springboot project has no web.xml configuration. Servlets and filters can be configured through
     *Servletregistrationbean and filterregistrationbean are added to the container.
     * @return
     */
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new WebStatFilter());

        /*
        
            DruidWebStatFilter
            com.alibaba.druid.support.http.WebStatFilter
            
            exclusions
            *.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
            
       
        
            DruidWebStatFilter
            /*
        
         */

        //The configuration result is equivalent to the above configuration in web.xml
        Map map = new HashMap<>();
        //Filtered resources, filtered resources, and webstatfilter will not monitor these resources.
        map.put("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");

        //Filter all requests. Webstatfilter will monitor this request. And it is displayed under Druid's web application.
        registrationBean.setUrlPatterns(Arrays.asList("/*"));
        registrationBean.setInitParameters(map);
        return registrationBean;
    }
}

3.Springboot-Mybatis

  1. Import dependency
org.mybatis.spring.boot
    mybatis-spring-boot-starter
    2.2.0
  1. Mapper.xml storage location
mybatis:
  #Alias package
  type-aliases-package: com.my.springboot.pojo
  #Location of mapper.xml
  mapper-locations: classpath:/mapper/*.xml
  1. Two ways to configure Dao layer interface

    1. Use @mapper annotation
    @Mapper
    @Repository
    public interface UserDao {
    
        List getList();
    }
    1. Configure through @mapperscans on the startup class
    @SpringBootApplication
    @MapperScans({
            @MapperScan("com.my.springboot.dao")
    })
    public class Demo05Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Demo05Application.class, args);
        }
    
    }

4.Springboot-Swagger

  1. Import dependency
io.springfox
    springfox-boot-starter
    3.0.0
  1. to configure
@Configuration
//Turn on swagger
@EnableSwagger2
public class SwaggerConfig {

    /**
     *Build swagger configuration
     * @param environment
     * @return
     */
    @Bean
    public Docket docket(Environment environment) {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                //Configure packages to scan
                .apis(RequestHandlerSelectors.basePackage("com.my.springboot"))
                //Filter requests only scan requests related to /index
                //.paths(PathSelectors.ant("/index"))
                .build();
    }

    /**
     *Configure swagger page display
     * @return
     */
    private ApiInfo apiInfo() {
        Contact contact = new Contact("tom", "www.tom.com", "[email protected]");
        return new ApiInfo(
                // title
                "Swagger2 exercise",
                // description
                "Swagger2 whole springboot exercise",
                // version
                "1.0",
                //Website access path
                "www.www.www",
                //Personal information
                contact,
                // license
                "Apache 2.0",
                // licenseUrl
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<>());
    }
}
  1. Swagger access address.http://localhost:8080/swagger-ui/index.html
  2. Configuration is accessible only in swagger and Dev and test environments
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket docket(Environment environment) {
        Profiles profiles = Profiles.of("dev", "test");
        //Dev and test environments return true. You can use swagger
        //Prod environment returns false, not applicable to swagger
        boolean flag = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                //Configure whether to enable swagger
                .enable(flag)
                .select()
                //Configure packages to scan
                .apis(RequestHandlerSelectors.basePackage("com.my.springboot"))
                .build();
    }
}
  1. Swagger configuration grouping
@Configuration
@EnableSwagger2
public class SwaggerConfig {

     /**
     *Configure multiple groups, create multiple docket objects, and set different gruopname ().
     * @return
     */
    @Bean
    public Docket docker1() {
        return new Docket(DocumentationType.OAS_30).groupName("bob");
    }
    
    @Bean
    public Docket docker2() {
        return new Docket(DocumentationType.OAS_30).groupName("tom");
    }
}
  1. Swagger annotation
//The entity class will not be scanned. The interface that needs to be scanned and the entity class object can be configured by swagger
@Data
@Apimodel (value = "user", description = "user class")
public class User {

    @ApiModelProperty(value = "id")
    private Integer id;
    @ApiModelProperty(value = "name")
    private String name;
    @ApiModelProperty(value = "age")
    private Integer age;
}

@RestController
@API (tags = {"control user URL"}, produces = "application/json")
public class UserController {

    //Method description
    @Apioperation ("get a user")
    //Parameter description
    @ApiImplicitParams({
            @Apiimplicitparam (name = "user name", DefaultValue = "Tom", required = true)
    })
    @GetMapping("/user")
    public String user() {
        return "user";
    }
}

5.Springboot-SpringMVC

  1. Configure the servlet and filter in web.xml into the container.
@Configuration
public class DruidConfiguration {

    /**
     *Configure the servlet accessed by Druid
     *Springboot project has no web.xml configuration. Servlets and filters can be configured through
     *Servletregistrationbean and filterregistrationbean are added to the container.
     * @return
     */
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean registrationBean = new ServletRegistrationBean<>();
        //Add statviewservlet
        registrationBean.setServlet(new StatViewServlet());
        //Configure the access path, and the background access path of Druid
        registrationBean.setUrlMappings(Arrays.asList("/druid/*"));

        //These parameters can be found in com.alibaba.druid.support.http.statviewservlet
        //The parent class of com.alibaba.druid.support.http Found in resourceservlet
        //Druid access login password
        Map map = new HashMap<>();
        map.put("loginUsername", "root");
        map.put("loginPassword", "123456");

        //Only this machine can access
        //An error occurs when the configuration is localhost. Java.lang.illegalargumentexception: invalid IP address [localhost]
        //It can be configured as map put("allow", "127.1.0.0");
        // map.put("allow", "localhost");
        map.put("allow", "127.1.0.0");

        //Allow= "", anyone can access
        //map.put("allow", "");

        //No access
        map.put("tom", "192.168.133.125");

        registrationBean.setInitParameters(map);
        return registrationBean;
    }
    
    /**
     *Configure the filter monitored by Druid
     *Springboot project has no web.xml configuration. Servlets and filters can be configured through
     *Servletregistrationbean and filterregistrationbean are added to the container.
     * @return
     */
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new WebStatFilter());

        /*
        
            DruidWebStatFilter
            com.alibaba.druid.support.http.WebStatFilter
            
            exclusions
            *.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
            
       
        
            DruidWebStatFilter
            /*
        
         */

        //The configuration result is equivalent to the above configuration in web.xml
        Map map = new HashMap<>();
        //Filtered resources, filtered resources, and webstatfilter will not monitor these resources.
        map.put("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");

        //Filter all requests. Webstatfilter will monitor this request. And it is displayed under Druid's web application.
        registrationBean.setUrlPatterns(Arrays.asList("/*"));
        registrationBean.setInitParameters(map);
        return registrationBean;
    }
}
  1. Configure view parser

    1. Mode 1
    @Configuration
    public class MyWebMvcConfigurer implements WebMvcConfigurer {
    
        /**
         *Custom view parser mode 1
         * @return
         */
        @Bean
        public ViewResolver viewResolver() {
            return new MyViewResolver();
        }
    
        public static class MyViewResolver implements ViewResolver {
    
            @Override
            public View resolveViewName(String viewName, Locale locale) throws Exception {
                return null;
            }
        }
    }
    1. Mode II
    public class MyWebMvcConfigurer implements WebMvcConfigurer {
    
        /**
         *Custom view parser method 2
         * @param registry
         */
        @Override
        public void configureViewResolvers(ViewResolverRegistry registry) {
            registry.viewResolver(new MyViewResolver());
        }eturn new MyViewResolver();
        }
    
        public static class MyViewResolver implements ViewResolver {
    
            @Override
            public View resolveViewName(String viewName, Locale locale) throws Exception {
                return null;
            }
        }
    }
  2. Other configurations

@Configuration
//@Enablewebmvc // disable springboot automatic configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //When the URL accesses /hello, jump to templates/index.html
        registry.addViewController("/hello").setViewName("index");
    }
}
  1. exception handling
@ControllerAdvice
@Slf4j
public class ControllerExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ModelAndView handlerException(HttpServletRequest request, Exception e) throws Exception {
        log.error("request url {}, error info {}", request.getRequestURL(), e);

        //If there is a responsestatus annotation on the caught exception, it indicates that it is an exception that the page cannot find, and it is thrown directly here,
        //Leave it to springboot to return error/404.html.
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("url", request.getRequestURL());
        mv.addObject("exception", e);
        mv.setViewName("error/error.html");
        return mv;
    }
}

6. Springboot email sending

  1. Import dependency
org.springframework.boot
    spring-boot-starter-mail
  1. Configure mail service
[email protected]
spring.mail.password=xxxxxx
spring.mail.host=smtp.qq.com
#QQ mailbox needs to enable encryption verification
spring.mail.properties.mail.smtp.ssl.enbale=true
  1. Mail sending
@SpringBootTest
class Demo10ApplicationTests {

    @Autowired
    private JavaMailSender mailSender;

    @Test
    void contextLoads() {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //Message title
        Mailmessage.setsubject ("send mail");
        //Body
        Mailmessage.settext ("message body");

        mailMessage.setFrom("[email protected]");

        mailMessage.setTo("[email protected]");
        mailSender.send(mailMessage);
    }


    /**
     *Send a complex email
     */
    @Test
    void contextLoads2() throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        //You need to set multiple file sending. If you do not set sending email, an error will be reported
        // java.lang.IllegalStateException:
        // Not in multipart mode - create an appropriate MimeMessageHelper via a constructor that takes a 'multipart' flag if you need to set alternative texts or add inline elements or attachments.
        MimeMessageHelper mailMessage = new MimeMessageHelper(mimeMessage);
        //Message title
        Mailmessage.setsubject ("send mail");
        //Body,会解析html
        mailMessage. Settext ("your email was sent", true);


        //Add file
        mailMessage.addAttachment("1.jpg", new File("E:\\Temp\.jpg"));
        mailMessage.setFrom("[email protected]");
        mailMessage.setTo("[email protected]");

        mailSender.send(mimeMessage);
    }
}