Springboot進階-JDBC、Druid、Mybatis、Swagger、SpringMVC、Mail
阿新 • • 發佈:2021-09-06
1.Springboot-JDBC
-
Springboot整合JDBC後,引入spring-boot-starter-jdbc,通過JdbcTemplate來操作資料庫。
-
匯入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
- 通過JdbcTemplate來操作資料庫,進行增刪改查
@RestControllerpublicclassUserController{ @ResourceprivateJdbcTemplatejdbcTemplate; //fromfhadmin.cn @GetMapping("/delete")publicStringdelete(){ Stringsql="deletefromtb_userwhereid=9"; jdbcTemplate.update(sql);return"deleteok"; } @GetMapping("/update")publicStringupdate(){ Stringsql="updatetb_usersetname='tom9'whereid=9"; jdbcTemplate.update(sql);return"updateok"; } @GetMapping("/insert")publicStringinsert(){ Stringsql="insertintotb_user(id,name,age)values(10,'tom10',10)"; jdbcTemplate.update(sql);return"insertok"; } @GetMapping("/get")publicList<Map<String,Object>>getList(){ Stringsql="select*fromtb_user"; List<Map<String,Object>>list=jdbcTemplate.queryForList(sql);returnlist; } }
2.Springboot-Druid
- 匯入依賴
<!-- <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.6</version> </dependency> <!--druid需要輸出日誌fromfhadmin.cn--> <!-- <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
- 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 #SpringBoot預設是不注入這些屬性值的,需要通過DruidDataSource繫結 #druid資料來源專有配置 initialSize:5 minIdle:5 maxActive:20 maxWait:60000 timeBetweenEvictionRunsMillis:60000 minEvictableIdleTimeMillis:300000 validationQuery:SELECT1FROMDUAL testWhileIdle:true testOnBorrow:false testOnReturn:false poolPreparedStatements:true #配置監控統計攔截的filters,stat:監控統計、log4j:日誌記錄、wall:防禦sql注入 #如果允許時報錯java.lang.ClassNotFoundException:org.apache.log4j.Priority #則匯入log4j依賴即可,Maven地址: filters:stat,wall,log4j maxPoolPreparedStatementPerConnectionSize:20 useGlobalDataSourceStat:true connectionProperties:druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
- yaml中Druid連線池配置和DruidDataSource繫結
@ConfigurationpublicclassDruidConfiguration{ /** *yaml中druid其他配置預設是不會匯入的,需要建立DruidDataSource時載入 *@return */ @Bean @ConfigurationProperties(prefix="spring.datasource")publicDataSourcedataSource(){returnnewDruidDataSource(); } }
- 配置訪問Druid的Servler
@ConfigurationpublicclassDruidConfiguration{ /** *配置Druid訪問的Serlvet *Springboot專案沒有web.xml配置,servlet和filter可以通過 *ServletRegistrationBean和FilterRegistrationBean加入到容器中。 *@return */ @BeanpublicServletRegistrationBean<StatViewServlet>statViewServlet(){ ServletRegistrationBean<StatViewServlet>registrationBean=newServletRegistrationBean<>(); //將StatViewServlet加入 registrationBean.setServlet(newStatViewServlet()); //配置訪問的路徑,druid的後臺訪問路徑 registrationBean.setUrlMappings(Arrays.asList("/druid/*")); //這些引數可以在com.alibaba.druid.support.http.StatViewServlet //的父類com.alibaba.druid.support.http.ResourceServlet中找到 //druid訪問登入密碼 Map<String,String>map=newHashMap<>(); map.put("loginUsername","root"); map.put("loginPassword","123456"); //只有本機可以訪問 //當配置是localhost時會出錯java.lang.IllegalArgumentException:InvalidIPAddress[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);returnregistrationBean; } }
- 配置Druid監控的Filter
@ConfigurationpublicclassDruidConfiguration{ /** *配置Druid監控的Filter *Springboot專案沒有web.xml配置,servlet和filter可以通過 *ServletRegistrationBean和FilterRegistrationBean加入到容器中。 *@return */ @BeanpublicFilterRegistrationBean<WebStatFilter>webStatFilter(){ FilterRegistrationBean<WebStatFilter>registrationBean=newFilterRegistrationBean<>(); registrationBean.setFilter(newWebStatFilter()); /* <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=newHashMap<>(); //過濾的資源,過濾的資源,WebStatFilter不會對這些資源進行監控。 map.put("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); //過濾所有的請求。WebStatFilter會監控這個請求。並且展示在druid的web應用下。 registrationBean.setUrlPatterns(Arrays.asList("/*")); registrationBean.setInitParameters(map);returnregistrationBean; } }
3.Springboot-Mybatis
- 匯入依賴
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency>
- mapper.xml存放位置
mybatis: #別名包 type-aliases-package:com.my.springboot.pojo #mapper.xml的位置 mapper-locations:classpath:/mapper/*.xml
-
配置dao層介面的兩種方式
- 使用@Mapper註解
@Mapper @RepositorypublicinterfaceUserDao{ List<User>getList(); }
- 啟動類上通過@MapperScans配置
@SpringBootApplication @MapperScans({ @MapperScan("com.my.springboot.dao") })publicclassDemo05Application{publicstaticvoidmain(String[]args){ SpringApplication.run(Demo05Application.class,args); } }
4.Springboot-Swagger
- 匯入依賴
<!--3.0和springboot整合,直接匯入starter--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
- 配置
@Configuration //開啟Swagger //fromfhadmin.cn @EnableSwagger2publicclassSwaggerConfig{ /** *構建Swagger配置 *@paramenvironment *@return */ @BeanpublicDocketdocket(Environmentenvironment){returnnewDocket(DocumentationType.OAS_30) .apiInfo(apiInfo()) .select() //配置要掃描的包 .apis(RequestHandlerSelectors.basePackage("com.my.springboot")) //過濾請求只掃描/index有關的請求 //.paths(PathSelectors.ant("/index")) .build(); } /** *配置swagger頁面顯示 *@return */privateApiInfoapiInfo(){ Contactcontact=newContact("tom",");returnnewApiInfo( //title "swagger2練習", //description "swagger2整個Springboot練習", //version "1.0", //網站訪問路徑 " //個人資訊 contact, //license "Apache2.0", //licenseUrl "()); } }
- Swagger訪問地址。
。
- 配置只在swagger在dev和test環境可以訪問
//fromfhadmin.cn @Configuration @EnableSwagger2publicclassSwaggerConfig{ @BeanpublicDocketdocket(Environmentenvironment){ Profilesprofiles=Profiles.of("dev","test"); //dev和test環境返回true,可以使用swagger //prod環境返回false,不適用swaggerbooleanflag=environment.acceptsProfiles(profiles);returnnewDocket(DocumentationType.OAS_30) .apiInfo(apiInfo()) //配置是否啟用swagger .enable(flag) .select() //配置要掃描的包 .apis(RequestHandlerSelectors.basePackage("com.my.springboot")) .build(); } }
- Swagger配置分組
//fromfhadmin.cn @Configuration @EnableSwagger2publicclassSwaggerConfig{ /** *配置多個分組,就建立多個Docket物件,設定不同的gruopName()。 *@return */ @BeanpublicDocketdocker1(){returnnewDocket(DocumentationType.OAS_30).groupName("bob"); } @BeanpublicDocketdocker2(){returnnewDocket(DocumentationType.OAS_30).groupName("tom"); } }
- Swagger註解
//實體類不會被掃描到,需要掃描到的介面,返回實體類物件,才能被Swagger配置fromfhadmin.cn @Data @ApiModel(value="使用者",description="使用者類")publicclassUser{ @ApiModelProperty(value="id")privateIntegerid; @ApiModelProperty(value="name")privateStringname; @ApiModelProperty(value="age")privateIntegerage; } @RestController @Api(tags={"控制使用者url"},produces="application/json")publicclassUserController{ //方法說明 @ApiOperation("獲取一個使用者") //引數說明 @ApiImplicitParams({ @ApiImplicitParam(name="使用者名稱",defaultValue="tom",required=true) }) @GetMapping("/user")publicStringuser(){return"user"; } }
5.Springboot-SpringMVC
- 將web.xml中的Servlet和Filter配置到容器中。
@ConfigurationpublicclassDruidConfiguration{ /**fromfhadmin.cn *配置Druid訪問的Serlvet *Springboot專案沒有web.xml配置,servlet和filter可以通過 *ServletRegistrationBean和FilterRegistrationBean加入到容器中。 *@return */ @BeanpublicServletRegistrationBean<StatViewServlet>statViewServlet(){ ServletRegistrationBean<StatViewServlet>registrationBean=newServletRegistrationBean<>(); //將StatViewServlet加入 registrationBean.setServlet(newStatViewServlet()); //配置訪問的路徑,druid的後臺訪問路徑 registrationBean.setUrlMappings(Arrays.asList("/druid/*")); //這些引數可以在com.alibaba.druid.support.http.StatViewServlet //的父類com.alibaba.druid.support.http.ResourceServlet中找到 //druid訪問登入密碼 Map<String,String>map=newHashMap<>(); map.put("loginUsername","root"); map.put("loginPassword","123456"); //只有本機可以訪問 //當配置是localhost時會出錯java.lang.IllegalArgumentException:InvalidIPAddress[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);returnregistrationBean; } /**fromfhadmin.cn *配置Druid監控的Filter *Springboot專案沒有web.xml配置,servlet和filter可以通過 *ServletRegistrationBean和FilterRegistrationBean加入到容器中。 *@return */ @BeanpublicFilterRegistrationBean<WebStatFilter>webStatFilter(){ FilterRegistrationBean<WebStatFilter>registrationBean=newFilterRegistrationBean<>(); registrationBean.setFilter(newWebStatFilter()); /* <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=newHashMap<>(); //過濾的資源,過濾的資源,WebStatFilter不會對這些資源進行監控。 map.put("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); //過濾所有的請求。WebStatFilter會監控這個請求。並且展示在druid的web應用下。 registrationBean.setUrlPatterns(Arrays.asList("/*")); registrationBean.setInitParameters(map);returnregistrationBean; } }
-
配置檢視解析器
- 方式一
@ConfigurationpublicclassMyWebMvcConfigurerimplementsWebMvcConfigurer{ /**fromfhadmin.cn *自定義檢視解析器方式一 *@return */ @BeanpublicViewResolverviewResolver(){returnnewMyViewResolver(); }publicstaticclassMyViewResolverimplementsViewResolver{ @OverridepublicViewresolveViewName(StringviewName,Localelocale)throwsException{returnnull; } } }
- 方式二
publicclassMyWebMvcConfigurerimplementsWebMvcConfigurer{ /**fromfhadmin.cn *自定義檢視解析器方法二 *@paramregistry */ @OverridepublicvoidconfigureViewResolvers(ViewResolverRegistryregistry){ registry.viewResolver(newMyViewResolver()); }eturnnewMyViewResolver(); }publicstaticclassMyViewResolverimplementsViewResolver{ @OverridepublicViewresolveViewName(StringviewName,Localelocale)throwsException{returnnull; } } }
-
其他配置
@Configuration //@EnableWebMvc//讓springboot自動配置失效fromfhadmin.cnpublicclassMyWebMvcConfigurerimplementsWebMvcConfigurer{ @OverridepublicvoidaddViewControllers(ViewControllerRegistryregistry){ //當URL訪問/hello時,跳轉到templates/index.html registry.addViewController("/hello").setViewName("index"); } }
- 異常處理
@ControllerAdvice @Slf4jpublicclassControllerExceptionHandler{ @ExceptionHandler(Exception.class)publicModelAndViewhandlerException(HttpServletRequestrequest,Exceptione)throwsException{ log.error("requesturl{},errorinfo{}",request.getRequestURL(),e); //如果捕獲到的異常上有ResponseStatus註解,說明是頁面找不到的異常,這裡直接丟擲, //交給springboot去處理,來返回error/404.html。if(AnnotationUtils.findAnnotation(e.getClass(),ResponseStatus.class)!=null){throwe; } ModelAndViewmv=newModelAndView(); mv.addObject("url",request.getRequestURL()); mv.addObject("exception",e); mv.setViewName("error/error.html");returnmv; } }