Springboot进阶-JDBC、Druid、Mybatis、Swagger、SpringMVC、Mail

1.Springboot-JDBC

  1. Springboot整合JDBC后,引入spring-boot-starter-jdbc,通过JdbcTemplate来操作数据库。
  2. 导入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
  1. 通过JdbcTemplate来操作数据库,进行增删改查
@RestController
public class UserController {
    @Resource
    private JdbcTemplate jdbcTemplate;
    //from fhadmin.cn
    @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<Map<String, Object>> getList() {
        String sql = "select * from tb_user";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }
}

回到顶部

2.Springboot-Druid

  1. 导入依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.6</version>
</dependency>
<!-- druid 需要输出日志 from fhadmin.cn -->
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
  1. application.yaml配置Druid连接池
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 默认是不注入这些属性值的,需要通过DruidDataSource绑定
    #druid 数据源专有配置
    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
    #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  1. yaml中Druid连接池配置和DruidDataSource绑定
@Configuration
public class DruidConfiguration {
    /**
     * yaml中druid其他配置默认是不会导入的,需要创建DruidDataSource时加载
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return new DruidDataSource();
    }
}
  1. 配置访问Druid的Servler
@Configuration
public class DruidConfiguration {
    /**
     * 配置Druid访问的Serlvet
     * Springboot项目没有web.xml配置,servlet和filter可以通过
     * ServletRegistrationBean和FilterRegistrationBean加入到容器中。
     * @return
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServlet() {
        ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>();
        // 将StatViewServlet加入
        registrationBean.setServlet(new StatViewServlet());
        // 配置访问的路径,druid的后台访问路径
        registrationBean.setUrlMappings(Arrays.asList("/druid/*"));
        // 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet
        // 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
        // druid访问登录密码
        Map<String, String> map = new HashMap<>();
        map.put("loginUsername", "root");
        map.put("loginPassword", "123456");
        // 只有本机可以访问
        // 当配置是localhost时会出错java.lang.IllegalArgumentException: Invalid IP Address [localhost]
        // 可以配置为map.put("allow", "127.1.0.0");
        // map.put("allow", "localhost");
        map.put("allow", "127.1.0.0");
        // allow="",谁都可以访问
        //map.put("allow", "");
        // 禁止访问
        map.put("tom", "192.168.133.125");
        registrationBean.setInitParameters(map);
        return registrationBean;
    }
}
  1. 配置Druid监控的Filter
@Configuration
public class DruidConfiguration {
    /**
     * 配置Druid监控的Filter
     * Springboot项目没有web.xml配置,servlet和filter可以通过
     * ServletRegistrationBean和FilterRegistrationBean加入到容器中。
     * @return
     */
    @Bean
    public FilterRegistrationBean<WebStatFilter> webStatFilter() {
        FilterRegistrationBean<WebStatFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new WebStatFilter());
        /*
        <filter>
            <filter-name>DruidWebStatFilter</filter-name>
            <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
            <init-param>
            <param-name>exclusions</param-name>
            <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
            </init-param>
       </filter>
        <filter-mapping>
            <filter-name>DruidWebStatFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
         */
        // 配置结果相等于web.xml中的如上配置
        Map<String, String> map = new HashMap<>();
        // 过滤的资源,过滤的资源,WebStatFilter不会对这些资源进行监控。
        map.put("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        // 过滤所有的请求。 WebStatFilter会监控这个请求。并且展示在druid的 web应用下。
        registrationBean.setUrlPatterns(Arrays.asList("/*"));
        registrationBean.setInitParameters(map);
        return registrationBean;
    }
}

回到顶部

3.Springboot-Mybatis

  1. 导入依赖
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
  1. mapper.xml存放位置
mybatis:
  # 别名包
  type-aliases-package: com.my.springboot.pojo
  # mapper.xml的位置
  mapper-locations: classpath:/mapper/*.xml
  1. 配置dao层接口的两种方式
    1. 使用@Mapper注解
@Mapper
@Repository
public interface UserDao {
    List<User> getList();
}
    1. 启动类上通过@MapperScans配置
@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. 导入依赖
<!-- 3.0和springboot整合,直接导入starter -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
  1. 配置
@Configuration
// 开启Swagger
//from fhadmin.cn
@EnableSwagger2
public class SwaggerConfig {
    /**
     * 构建Swagger配置
     * @param environment
     * @return
     */
    @Bean
    public Docket docket(Environment environment) {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                // 配置要扫描的包
                .apis(RequestHandlerSelectors.basePackage("com.my.springboot"))
                // 过滤请求 只扫描 /index 有关的请求
                //.paths(PathSelectors.ant("/index"))
                .build();
    }
    /**
     * 配置swagger页面显示
     * @return
     */
    private ApiInfo apiInfo() {
        Contact contact = new Contact("tom", "www.tom.com", "tom@163.com");
        return new ApiInfo(
                // title
                "swagger2练习",
                // description
                "swagger2整个Springboot练习",
                // version
                "1.0",
                // 网站访问路径
                "www.www.www",
                // 个人信息
                contact,
                // license
                "Apache 2.0",
                // licenseUrl
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<>());
    }
}
  1. Swagger访问地址。http://localhost:8080/swagger-ui/index.html
  2. 配置只在swagger在dev和test环境可以访问
//from fhadmin.cn
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket docket(Environment environment) {
        Profiles profiles = Profiles.of("dev", "test");
        // dev和test环境 返回true,可以使用swagger
        // prod环境返回false,不适用swagger
        boolean flag = environment.acceptsProfiles(profiles);
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                // 配置是否启用 swagger
                .enable(flag)
                .select()
                // 配置要扫描的包
                .apis(RequestHandlerSelectors.basePackage("com.my.springboot"))
                .build();
    }
}
  1. Swagger配置分组
//from fhadmin.cn
@Configuration
@EnableSwagger2
public class SwaggerConfig {
     /**
     * 配置多个分组,就创建多个Docket对象,设置不同的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注解
// 实体类不会被扫描到,需要扫描到的接口,返回实体类对象,才能被Swagger配置 from fhadmin.cn
@Data
@ApiModel(value = "用户", description = "用户类")
public class User {
    @ApiModelProperty(value = "id")
    private Integer id;
    @ApiModelProperty(value = "name")
    private String name;
    @ApiModelProperty(value = "age")
    private Integer age;
}
@RestController
@Api(tags = {"控制用户url"}, produces = "application/json")
public class UserController {
    // 方法说明
    @ApiOperation("获取一个用户")
    // 参数说明
    @ApiImplicitParams({
            @ApiImplicitParam(name = "用户名", defaultValue = "tom", required = true)
    })
    @GetMapping("/user")
    public String user() {
        return "user";
    }
}

回到顶部

5.Springboot-SpringMVC

  1. 将web.xml中的Servlet和Filter配置到容器中。
@Configuration
public class DruidConfiguration {
    /**from fhadmin.cn
     * 配置Druid访问的Serlvet
     * Springboot项目没有web.xml配置,servlet和filter可以通过
     * ServletRegistrationBean和FilterRegistrationBean加入到容器中。
     * @return
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServlet() {
        ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>();
        // 将StatViewServlet加入
        registrationBean.setServlet(new StatViewServlet());
        // 配置访问的路径,druid的后台访问路径
        registrationBean.setUrlMappings(Arrays.asList("/druid/*"));
        // 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet
        // 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
        // druid访问登录密码
        Map<String, String> map = new HashMap<>();
        map.put("loginUsername", "root");
        map.put("loginPassword", "123456");
        // 只有本机可以访问
        // 当配置是localhost时会出错java.lang.IllegalArgumentException: Invalid IP Address [localhost]
        // 可以配置为map.put("allow", "127.1.0.0");
        // map.put("allow", "localhost");
        map.put("allow", "127.1.0.0");
        // allow="",谁都可以访问
        //map.put("allow", "");
        // 禁止访问
        map.put("tom", "192.168.133.125");
        registrationBean.setInitParameters(map);
        return registrationBean;
    }
    
    /**from fhadmin.cn
     * 配置Druid监控的Filter
     * Springboot项目没有web.xml配置,servlet和filter可以通过
     * ServletRegistrationBean和FilterRegistrationBean加入到容器中。
     * @return
     */
    @Bean
    public FilterRegistrationBean<WebStatFilter> webStatFilter() {
        FilterRegistrationBean<WebStatFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new WebStatFilter());
        /*
        <filter>
            <filter-name>DruidWebStatFilter</filter-name>
            <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
            <init-param>
            <param-name>exclusions</param-name>
            <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
            </init-param>
       </filter>
        <filter-mapping>
            <filter-name>DruidWebStatFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
         */
        // 配置结果相等于web.xml中的如上配置
        Map<String, String> map = new HashMap<>();
        // 过滤的资源,过滤的资源,WebStatFilter不会对这些资源进行监控。
        map.put("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        // 过滤所有的请求。 WebStatFilter会监控这个请求。并且展示在druid的 web应用下。
        registrationBean.setUrlPatterns(Arrays.asList("/*"));
        registrationBean.setInitParameters(map);
        return registrationBean;
    }
}
  1. 配置视图解析器
    1. 方式一
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    /**from fhadmin.cn
     * 自定义视图解析器 方式一
     * @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. 方式二
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    /**from fhadmin.cn
     * 自定义视图解析器 方法二
     * @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;
        }
    }
}
  1. 其他配置
@Configuration
//@EnableWebMvc // 让springboot自动配置失效 from fhadmin.cn
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 当URL访问/hello时,跳转到 templates/index.html
        registry.addViewController("/hello").setViewName("index");
    }
}
  1. 异常处理
@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);
        // 如果捕获到的异常上有ResponseStatus注解,说明是页面找不到的异常,这里直接抛出,
        // 交给springboot去处理,来返回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;
    }
}
上一篇:Problem24


下一篇:Problem25