SpringBoot整合jdbc,整合mybatis,配置嵌入式Servlet容器

    技术2022-07-29  86

    文章目录

    一、SpringBoot实现增删改查的操作二、springboot异常处理三、配置嵌入式Servlet容器(1)注册Servlet(2)注册过滤器(3)注册监听器 四、springboot整合jdbc五、springboot整合druid数据源(1)druid数据源的相关配置(2)配置数据源监控 六、springboot整合mybatis

    一、SpringBoot实现增删改查的操作

    1.导入依赖

    <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-java8time</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies>

    2.前期准备:将静态资源导入到项目中 3.导入pojo实体类

    package com.bianyiit.pojo; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; //员工表 @Data @NoArgsConstructor public class Employee { private Integer id; private String lastName; private String email; private Integer gender; // 0女 1男 private Department department; private Date birth; public Employee(Integer id, String lastName, String email, Integer gender, Department department) { this.id = id; this.lastName = lastName; this.email = email; this.gender = gender; this.department = department; //默认创建日期 this.birth = new Date(); } } package com.bianyiit.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; //部门表 @Data @NoArgsConstructor @AllArgsConstructor public class Department { private Integer id; private String departmentName; }

    4.导入dao(为了方便测试,不连接数据库,使用map集合保存员工信息)

    package com.bianyiit.dao; import com.bianyiit.pojo.Department; import com.bianyiit.pojo.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.HashMap; import java.util.Map; //员工dao @Repository public class EmployeeDao { //模拟数据 private static Map<Integer, Employee> employees = null; @Autowired private DepartmentDao departmentDao; static { employees = new HashMap<Integer, Employee>(); //创建一个功能数据表 employees.put(1001, new Employee(1001, "AA", "A126491@qq.com", 0, new Department(101, "教学部"))); employees.put(1002, new Employee(1002, "BB", "B126491@qq.com", 1, new Department(102, "市场部"))); employees.put(1003, new Employee(1003, "CC", "C126491@qq.com", 0, new Department(103, "教研部"))); employees.put(1004, new Employee(1004, "DD", "D126491@qq.com", 1, new Department(104, "运营部"))); employees.put(1005, new Employee(1005, "EE", "E126491@qq.com", 0, new Department(105, "后勤部"))); } private static Integer initId = 1006; //增加员工 public void save(Employee employee) { if (employee.getId() == null) { employee.setId(initId++); } employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId())); employees.put(employee.getId(), employee); } //查询全部员工信息 public Collection<Employee> getAll() { return employees.values(); } //根据id查询员工信息 public Employee getEmployeeById(Integer id) { return employees.get(id); } //删除员工 public void delete(Integer id) { employees.remove(id); } } package com.bianyiit.dao; import com.bianyiit.pojo.Department; import org.springframework.stereotype.Repository; import java.util.Collection; import java.util.HashMap; import java.util.Map; //部门dao @Repository public class DepartmentDao { //模拟数据库 private static Map<Integer, Department> departments = null; static { departments = new HashMap<Integer, Department>(); //创建一个功能数据表 departments.put(101, new Department(101, "教学部")); departments.put(102, new Department(102, "市场部")); departments.put(103, new Department(103, "教研部")); departments.put(104, new Department(104, "运营部")); departments.put(105, new Department(105, "后勤部")); } //获取所有部门信息 public Collection<Department> getDepartments() { //获取map所有的values对象 return departments.values(); } //通过id得到部门 public Department getDepartment(Integer id) { return departments.get(id); } }

    5.编写SpringBoot启动类

    package com.bianyiit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringbootWebApplication { public static void main(String[] args) { SpringApplication.run(SpringbootWebApplication.class,args); } }

    6.在LoginUserController编写登录和登出功能

    package com.bianyiit.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpSession; @Controller @RequestMapping("/user") public class LoginUserController { @RequestMapping("/login") public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model, HttpSession session){ //判断用户名和密码是否正确 if(username.equals("admin")&&password.equals("123456")){ //如果正确,将用户信息保存在session里面 session.setAttribute("loginuser",username); return "redirect:/index.html"; }else{ //登录失败 model.addAttribute("msg", "用户名或者密码错误"); return "/login"; } } @RequestMapping("/loginout") public String userLogin(HttpSession session) { session.invalidate(); return "redirect:/login"; } }

    7.添加视图映射

    package com.bianyiit.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MyMvcConfig implements WebMvcConfigurer { /** * 进行视图跳转 * @param registry */ @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/login.html").setViewName("login"); registry.addViewController("/login").setViewName("login"); registry.addViewController("/index.html").setViewName("dashboard"); } }

    以上代码存在的问题: http://localhost:8080/index.html 可以绕过登录直接访问主页dashboard.html

    8.解决方案:配置和注册拦截器

    配置拦截器

    package com.bianyiit.config; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LoginHandleInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); String loginuser = (String) session.getAttribute("loginuser"); if(loginuser==null){ //未登录 request.setAttribute("msg", "没有权限,请先登录"); request.getRequestDispatcher("/login").forward(request,response); return false; }else{ //登录成功 return true; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } }

    在MyMvcConfig配置类中注册拦截器

    package com.bianyiit.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MyMvcConfig implements WebMvcConfigurer { /** * 进行视图跳转 * @param registry */ @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/login.html").setViewName("login"); registry.addViewController("/login").setViewName("login"); registry.addViewController("/index.html").setViewName("dashboard"); } @Override public void addInterceptors(InterceptorRegistry registry) { //添加拦截器 registry.addInterceptor(new LoginHandleInterceptor()).addPathPatterns("/**").excludePathPatterns("/login.html","/","/login","/user/login","/user/loginout","/css/**","/js/**","/img/**"); } }

    9.标签国际化操作(登录界面中英文切换)

    前端界面

    后端界面

    package com.bianyiit.config; import org.springframework.web.servlet.LocaleResolver; import org.thymeleaf.util.StringUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale; public class MylocaleResolver implements LocaleResolver { @Override public Locale resolveLocale(HttpServletRequest httpServletRequest) { //获取前端传来的参数 String l = httpServletRequest.getParameter("l"); Locale locale = Locale.getDefault(); //如果没有就是默认 //如果请求携带了国际化的参数 if (!StringUtils.isEmpty(l)) { String[] split = l.split("_"); locale = new Locale(split[0], split[1]); } return locale; } @Override public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) { } }

    注册MylocaleResolver

    package com.bianyiit.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MyMvcConfig implements WebMvcConfigurer { /** * 进行视图跳转 * @param registry */ @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("login"); registry.addViewController("/login.html").setViewName("login"); registry.addViewController("/login").setViewName("login"); registry.addViewController("/index.html").setViewName("dashboard"); } @Override public void addInterceptors(InterceptorRegistry registry) { //添加拦截器 registry.addInterceptor(new LoginHandleInterceptor()).addPathPatterns("/**").excludePathPatterns ("/login.html","/","/login","/user/login","/user/loginout","/css/**","/js/**","/img/**"); } @Bean public LocaleResolver localeResolver() { return new MylocaleResolver(); } }

    10.查询员工,新增员工,修改员工,删除员工

    package com.bianyiit.controller; import com.bianyiit.dao.DepartmentDao; import com.bianyiit.dao.EmployeeDao; import com.bianyiit.pojo.Department; import com.bianyiit.pojo.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import java.util.Collection; @Controller public class EmployeeController { @Autowired EmployeeDao employeeDao; @Autowired DepartmentDao departmentDao; //查询所有员工 @GetMapping("/emps") public String emps(Model model){ Collection<Employee> employees = employeeDao.getAll(); model.addAttribute("emps",employees); return "/emp/list"; } //点击添加新员工,跳转至add.html @GetMapping("/emp") public String emp(Model model){ Collection<Department> departments = departmentDao.getDepartments(); model.addAttribute("departments",departments); return "/emp/add"; } //填写完毕之后确认添加新员工 @PostMapping("/emp") public String emp(Employee employee){ employeeDao.save(employee); return "redirect:/emps"; } //修改员工信息 @GetMapping("/emp/{id}") public String emp(@PathVariable("id") Integer id,Model model){ Employee employee = employeeDao.getEmployeeById(id); Collection<Department> departments = departmentDao.getDepartments(); model.addAttribute("emp",employee); model.addAttribute("departments",departments); return "/emp/update"; } //修改完员工信息之后点击确定 @PostMapping("/updateEmp") public String updateEmp(Employee employee){ employeeDao.save(employee); return "redirect:/emps"; } //删除员工信息 @GetMapping("/delemp/{id}") public String delemp(@PathVariable("id") Integer id){ employeeDao.delete(id); return "redirect:/emps"; } }

    11.测试

    二、springboot异常处理

    BasicErrorController:处理默认/error请求 DefaultErrorViewResolver:响应页面;去哪个页面是由DefaultErrorViewResolver解析得到的

    1.在模板引擎的情况下 处理错误请求 通过源代码可知,当出现错误的情况下,都会去templates的error文件夹下面去寻找错误页面 错误处理之后,在视图显示错误信息 2.定义错误视图响应

    有模板引擎的情况下;error/状态码; 【将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的 error文件夹下】,发生此状态码的错误就会来到对应的页面;我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态 码.html);页面能获取的信息; timestamp:时间戳 status:状态码 error:错误提示 exception:异常对象 message:异常消息 errors:JSR303数据校验的错误都在这里 定义4xx.html或者5xx.html页面。在页面输出一些错误处理信息

    三、配置嵌入式Servlet容器

    SpringBoot默认使用Tomcat作为嵌入式的Servlet容器; 1.如何定制和修改Servlet容器的相关配置

    server.port=8081 server.servlet.context-path=/crud server.tomcat.uri-encoding=UTF-8 //通用的Servlet容器设置 server.xxx //Tomcat的设置 server.tomcat.xxx

    2.注册Web三大组件 由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件。

    注册三大组件用以下方式: ServletRegistrationBean 注册Servlet组件 FilterRegistrationBean 注册Filter组件 ServletListenerRegistrationBean 注册监听器组件

    (1)注册Servlet

    1.编写一个Servlet

    @WebServlet("/myServlet") public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Servlet执行了...."); } }

    2.在配置类里面注册Servlet组件

    //注册Servlet组件 @Bean public ServletRegistrationBean registerServlet(){ ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet"); return registrationBean; }
    (2)注册过滤器

    1.定义过滤器类

    public class MyFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { System.out.println("Filter执行了....."); filterChain.doFilter(request,response); } }

    2.注册过滤器组件

    //注册Filter组件 @Bean public FilterRegistrationBean filterRegistrationBean(){ FilterRegistrationBean filterBean = new FilterRegistrationBean(); filterBean.setFilter(new MyFilter()); filterBean.setUrlPatterns(Arrays.asList("/myServlet")); return filterBean; }
    (3)注册监听器

    1.定义监听器(监听ServContext对象的创建和销毁)

    public class MyListener implements ServletContextListener { //监听SerlvetContext对象的创建 @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("ServletContext对象创建了....."); } //监听SerlvetContext对象的销毁 @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("ServletContext对象销毁了....."); } }

    2.注册监听器

    //注册Listener组件 @Bean public ServletListenerRegistrationBean servletListenerRegistrationBean(){ ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener()); return registrationBean; }

    注意:正常退出才可以看出ServletContext对象销毁的效果 3.springboot中使用其他的Servlet容器 只需要在springboot的pom.xml中引入相关容器的依赖即可

    Jetty容器

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency>

    Undertow容器

    <dependency> <artifactId>spring-boot-starter-undertow</artifactId> <groupId>org.springframework.boot</groupId> </dependency>

    四、springboot整合jdbc

    使用脚手架快速创建一个springboot项目,注意我们需要使用jdbc进行数据持久层操作,所以需要勾选jdbc和mysql数据库的启动器。 在pom.xml中,添加的依赖如下:

    <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.5.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies>

    在application.yml文件中配置

    spring: datasource: username: root password: 123 url: jdbc:mysql://127.0.0.1:3306/ssm?serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver #如果报红将pom.xml里面的mysql依赖的scope runtime注释掉即可

    测试

    package com.bianyiit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class); } } package com.bianyiit; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; @RunWith(SpringRunner.class) @SpringBootTest(classes = {App.class}) public class SpringbootJdbcApplicationTests { @Autowired DataSource dataSource; @Test public void contextLoads() { try { Connection connection = dataSource.getConnection(); System.out.println(connection); } catch (SQLException e) { e.printStackTrace(); } } }

    获取的连接对象:

    HikariProxyConnection@1758876146 wrapping com.mysql.cj.jdbc.ConnectionImpl@3ad4a7d6

    测试连接对象是否可用(使用java代码创建数据表) springboot支持在类路径下面放置sql脚本文件,那么在springboot项目启动的时候,会加载这些脚本文件的。

    需求: 在springboot项目启动的时候,自动执行建表语句department.sql 1.在类路径下面,也就是resources目录下面放置department.sql脚本文件 2.在application.yml文件中配置

    spring: datasource: username: root password: 123 url: jdbc:mysql://192.168.2.215:3306/springboot_mysql driver-class-name: com.mysql.jdbc.Driver schema: - classpath:department.sql initialization-mode: always # springboot项目加载的时候,自动执行这些脚本文件

    springboot还自动配置了JdbcTemplate用来操作数据库 需求:将test数据表中的数据查询出来。

    @RestController public class DepartmentController { @Autowired JdbcTemplate jdbcTemplate; @ResponseBody @RequestMapping("/query") public Map<String, Object> test(){ List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT * FROM test"); return list.get(0); } }

    五、springboot整合druid数据源

    导入druid数据源依赖

    <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.5.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <!--引入Druid数据源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency> </dependencies>

    Application.yml配置文件

    spring: datasource: username: root password: 123 url: jdbc:mysql://127.0.0.1:3306/ssm?serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver #如果报红将pom.xml里面的mysql依赖的scope runtime注释掉即可 type: com.alibaba.druid.pool.DruidDataSource #指定数据源类型

    测试

    package com.bianyiit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class); } } package com.bianyiit; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; @RunWith(SpringRunner.class) @SpringBootTest(classes = {App.class}) public class SpringbootJdbcApplicationTests { @Autowired DataSource dataSource; @Test public void contextLoads() { try { Connection connection = dataSource.getConnection(); System.out.println(dataSource.getClass()); System.out.println(connection); } catch (SQLException e) { e.printStackTrace(); } } }

    测试结果:

    (1)druid数据源的相关配置

    引入log4j依赖

    <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.5.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <!--引入Druid数据源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency> <!-- springboot-log4j --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j</artifactId> <version>1.3.8.RELEASE</version> </dependency> </dependencies>

    在application.yml配置文件中添加配置信息(红色部分)

    spring: datasource: username: root password: 123 url: jdbc:mysql://127.0.0.1:3306/ssm?serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver #如果报红将pom.xml里面的mysql依赖的scope runtime注释掉即可 type: com.alibaba.druid.pool.DruidDataSource #指定数据源类型 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,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

    通过配置类将配置信息与数据源进行绑定

    @Configuration public class DruidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druid(){ return new DruidDataSource(); } }
    (2)配置数据源监控

    配置数据源监控的步骤: 1.配置一个管理后台的Servlet。

    //配置Druid的监控 //1、配置一个管理后台的Servlet @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); Map<String,String> initParams = new HashMap<>(); initParams.put("loginUsername","admin"); initParams.put("loginPassword","123456"); initParams.put("allow","");//默认就是允许所有访问 initParams.put("deny","192.168.15.21"); bean.setInitParameters(initParams); return bean; }

    2.配置一个web监控的filter。

    //2、配置一个web监控的filter @Bean public FilterRegistrationBean webStatFilter(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); Map<String,String> initParams = new HashMap<>(); initParams.put("exclusions","*.js,*.css,/druid/*"); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*")); return bean; }

    3.测试

    package com.bianyiit.config; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; import java.util.Arrays; import java.util.HashMap; import java.util.Map; @Configuration public class DruidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druid(){ return new DruidDataSource(); } //配置Druid的监控 //1、配置一个管理后台的Servlet @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); Map<String,String> initParams = new HashMap<>(); initParams.put("loginUsername","admin"); initParams.put("loginPassword","123456"); initParams.put("allow","");//默认就是允许所有访问 initParams.put("deny","192.168.15.21"); bean.setInitParameters(initParams); return bean; } //2、配置一个web监控的filter @Bean public FilterRegistrationBean webStatFilter(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); Map<String,String> initParams = new HashMap<>(); initParams.put("exclusions","*.js,*.css,/druid/*"); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*")); return bean; } } package com.bianyiit.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; @RestController public class DruidController { @Autowired DataSource dataSource; @RequestMapping("/findAll") public void findAll() throws SQLException { Connection connection = dataSource.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement("select * from account"); preparedStatement.execute(); } } package com.bianyiit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class); } }

    先访问一次http://localhost:8080/findAll 然后进入Druid的监控器查看本次执行的sql语句

    六、springboot整合mybatis

    使用脚手架创建springboot项目的时候需要勾选以下信息: 引入log4j和druid数据源依赖

    <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.5.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <!--引入Druid数据源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency> <!-- springboot-log4j --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j</artifactId> <version>1.3.8.RELEASE</version> </dependency> <dependency> <groupId>cn.org.faster</groupId> <artifactId>spring-boot-starter-mybatis</artifactId> <version>1.3.2.RELEASE</version> </dependency> </dependencies>

    在application.yml文件中配置druid数据源的信息

    spring: datasource: username: root password: 123 url: jdbc:mysql://127.0.0.1:3306/ssm?serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver #如果报红将pom.xml里面的mysql依赖的scope runtime注释掉即可 type: com.alibaba.druid.pool.DruidDataSource #指定数据源类型 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,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

    创建配置类,绑定数据源属性,并设置监控

    package com.bianyiit.config; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; import java.util.Arrays; import java.util.HashMap; import java.util.Map; @Configuration public class DruidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druid(){ return new DruidDataSource(); } //配置Druid的监控 //1、配置一个管理后台的Servlet @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); Map<String,String> initParams = new HashMap<>(); initParams.put("loginUsername","admin"); initParams.put("loginPassword","123456"); initParams.put("allow","");//默认就是允许所有访问 initParams.put("deny","192.168.15.21"); bean.setInitParameters(initParams); return bean; } //2、配置一个web监控的filter @Bean public FilterRegistrationBean webStatFilter(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); Map<String,String> initParams = new HashMap<>(); initParams.put("exclusions","*.js,*.css,/druid/*"); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*")); return bean; } }

    创建实体类 Account

    package com.bianyiit.pojo; import lombok.Data; @Data public class Account { private Integer id; private String name; private Double money; }

    整合mybatis——定义接口 使用@Mapper注解修饰

    package com.bianyiit.dao; import com.bianyiit.pojo.Account; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import java.util.List; @Mapper @Repository public interface DruidDao { @Select("select * from account") List<Account> findAll(); }

    定义controller

    package com.bianyiit.controller; import com.bianyiit.dao.DruidDao; import com.bianyiit.pojo.Account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; @RestController public class DruidController { @Autowired DruidDao druidDao; @RequestMapping("/findAll") public void findAll(){ List<Account> list = druidDao.findAll(); System.out.println(list); } }

    查询的测试: http://localhost:8080/findAll2

    注意:如果接口很多的话,在每个接口上面使用@Mapper会很麻烦,使用MapperScan批量扫描所有的dao接口。

    @MapperScan(value = "com.oracle.dao") @SpringBootApplication public class SpringBoot06DataMybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringBoot06DataMybatisApplication.class, args); } }
    Processed: 0.013, SQL: 9