Springboot进阶-JDBC、Druid、Mybatis、Swagger、SpringMVC、Mail
回到顶部
1.Springboot-JDBC
-
Springboot整合JDBC后,引入spring-boot-starter-jdbc,通过JdbcTemplate来操作数据库。
-
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
- 通过JdbcTemplate来操作数据库,进行增删改查
@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<Map<String, Object>> getList() {
String sql = "select * from tb_user";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
return list;
}
}
回到顶部
2.Springboot-Druid
- 导入依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
<!-- druid 需要输出日志 -->
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<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
#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
- yaml中Druid连接池配置和DruidDataSource绑定
@Configuration
public class DruidConfiguration {
/**
* yaml中druid其他配置默认是不会导入的,需要创建DruidDataSource时加载
* @return
*/
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return new DruidDataSource();
}
}
- 配置访问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;
}
}
- 配置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
- 导入依赖
<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 @Repository public interface UserDao { List<User> getList(); }
- 启动类上通过@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
- 导入依赖
<!-- 3.0和springboot整合,直接导入starter -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
- 配置
@Configuration
// 开启Swagger
@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<>());
}
}
-
Swagger访问地址。
http://localhost:8080/swagger-ui/index.html
。 - 配置只在swagger在dev和test环境可以访问
@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();
}
}
- Swagger配置分组
@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");
}
}
- Swagger注解
// 实体类不会被扫描到,需要扫描到的接口,返回实体类对象,才能被Swagger配置
@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
- 将web.xml中的Servlet和Filter配置到容器中。
@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;
}
/**
* 配置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;
}
}
-
配置视图解析器
- 方式一
@Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer { /** * 自定义视图解析器 方式一 * @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; } } }
- 方式二
public class MyWebMvcConfigurer implements WebMvcConfigurer { /** * 自定义视图解析器 方法二 * @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; } } }
-
其他配置
@Configuration
//@EnableWebMvc // 让springboot自动配置失效
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 当URL访问/hello时,跳转到 templates/index.html
registry.addViewController("/hello").setViewName("index");
}
}
- 异常处理
@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;
}
}
回到顶部
6.Springboot-邮件发送
- 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
- 配置邮件服务
spring.mail.username=2193056xxx@qq.com
spring.mail.password=xxxxxx
spring.mail.host=smtp.qq.com
# qq邮箱需要开启加密验证
spring.mail.properties.mail.smtp.ssl.enbale=true
- 邮件发送
@SpringBootTest
class Demo10ApplicationTests {
@Autowired
private JavaMailSender mailSender;
@Test
void contextLoads() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
// 邮件标题
mailMessage.setSubject("发送邮件");
// 正文
mailMessage.setText("邮件正文");
mailMessage.setFrom("2193056xxx@qq.com");
mailMessage.setTo("m158295xxx@163.com");
mailSender.send(mailMessage);
}
/**
* 发送一个复杂的邮件
*/
@Test
void contextLoads2() throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
// 需要设置多文件发送,如果没有设置发送邮件会报错
// 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);
// 邮件标题
mailMessage.setSubject("发送邮件");
// 正文,会解析html
mailMessage.setText("<h2>你的邮件发送了</h2>", true);
// 添加文件
mailMessage.addAttachment("1.jpg", new File("E:\\Temp\\1.jpg"));
mailMessage.setFrom("219305xxxx@qq.com");
mailMessage.setTo("m158295xxxx@163.com");
mailSender.send(mimeMessage);
}
}