Springboot進階-JDBC、Druid、Mybatis、Swagger、SpringMVC、Mail

FH-Admin發表於2021-08-26

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
  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;
            }
        }
    }
    
  2. 其他配置

@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;
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章