1.注册web的filter组件
web开发--如何定义过滤器以及如何把过滤注册到web.xml容器中
public class 类名 implements java.servlet.Filter{
doFilter(){}
}
<filter>
<filter-name></filter-name>
<filter-class></filter-class>
</filter>
<filter-mapping>
<filter-name></filter-name>
<url-paterrn></
</filter-mapping>
springboot中不存在web.xml文件 ---@Configuration
1.1创建一个过滤器类
package com.hmq.springboot.filter;
import javax.servlet.*;
import java.io.IOException;
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//校验是否登录,编码问题
System.out.println("-------过滤器------");
filterChain.doFilter(servletRequest,servletResponse);//放行到下一个过滤器或者到达你的请求地址的controller
}
}
1.2配置类
@Configuration //等价于xml配置文件
public class MyConfig {
@Bean //加载方法上 ,把该方法的返回结果交于springIOC容器来管理
public FilterRegistrationBean<Filter> filterRegistrationBean(){
FilterRegistrationBean<Filter> filterFilterRegistrationBean = new FilterRegistrationBean<>();
filterFilterRegistrationBean.setName("myFilter");
filterFilterRegistrationBean.setFilter(new MyFilter());
filterFilterRegistrationBean.addUrlPatterns("/*");
return filterFilterRegistrationBean;
}
}
2.springboot自动装配原理
2.1 springboot自动包扫描
pringboot默认扫描的包是哪些?
主类所在的包以及子包,一定在主类上的@SpringBootApplication上
人为修改主类的路径,可以在主类上使用@ComponentScan来修改默认的包扫描
2.2 自动装配原理
springboot 有没有注册DispatcherServlet. 为何能找到controller层
<!--注册DispatchServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--如果没有指定参数默认解析WEB-INF/servlerName-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
springboot帮你完成自动装配
protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
} else {
AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);//得到所有的自动装配类
configurations = this.removeDuplicates(configurations);//移除一些重复的自动装配类
Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);//移除一些被排除的自动装配
this.checkExcludedClasses(configurations, exclusions);//移除一些被排除的自动装配
configurations.removeAll(exclusions);//移除一些被排除的自动装配
configurations = this.getConfigurationClassFilter().filter(configurations);//过滤掉没有引用的自动装配
this.fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
}
}
当主函数运行时会加载一个使用@SpringBootApplication注释的类,@SpringbootApplication它是一个复合组件。其中@EnableAutoConfiguration它是开启自动配置的核心注解,该注解也是一个复合组件,其中@Import({AutoConfigurationImportSelector.class}) ,该注解需要导入一个AutoConfigurationImportSelector类,该类会加载你需要的自动装配类,而这些自动装配类会完成响应的自动装配功能。
3.springboot整合第三方框架
3.1springboot整合mybatis
3.1.1依赖
<!--mysql的驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--mybatis启动依赖:DataSourceAutoConfiguration:读取application配置文件中以spring,datasource-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
3.1.2配置文件
#数据源信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#characterEncoding防止添加到数据的数据出现乱码 ---utf-8
spring.datasource.url=jdbc:mysql://localhost:3306/qy165?serverTimezone=Asia/Shanghai&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
#指定mybatis映射文件的路径 classpath编译后的路径
mybatis.mapper-locations=classpath:mapper/*.xml
#控制台打印sql日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
3.1.3创建实体类和dao接口,sql
package com.hmq.springboot01.pojo;
import lombok.Data;
@Data
public class Dept {
private Integer id;
private String name;
private String loc;
}
dao
package com.hmq.springboot01.dao;
import com.hmq.springboot01.pojo.Dept;
import java.util.List;
//@Mapper 代理实现类
public interface DeptDao {
public List<Dept> findAll();
}
mapper包DeptDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namesapce的内容必须和对应的接口路径映射-->
<mapper namespace="com.hmq.springboot01.dao.DeptDao">
<!--查询所有部门信息-->
<select id="findAll" resultType="com.hmq.springboot01.pojo.Dept">
select * from tb_dept
</select>
</mapper>
3.1.4在主启动类上添加注解
3.1.5测试
package com.hmq.springboot01;
import com.hmq.springboot01.dao.DeptDao;
import com.hmq.springboot01.dao.EmpDao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(classes = SpringBoot01Application.class) //springboot提高了单元测试
class SpringBoot01ApplicationTests {
@Autowired
private DeptDao deptDao;//无法注入DeptDao的对象,为什么无法注入【spring容器中没有dao接口的代理实现类】
@Test
void contextLoads() {
deptDao.findAll().stream().forEach(System.out::println);
}
}
3.2springboot整合pageHelper
<!--pageHelper分页驱动-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
</dependency>
测试类中
package com.hmq.springboot01;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hmq.springboot01.dao.DeptDao;
import com.hmq.springboot01.dao.EmpDao;
import com.hmq.springboot01.pojo.Dept;
import com.hmq.springboot01.pojo.Emp;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest(classes = SpringBoot01Application.class) //springboot提高了单元测试
class SpringBoot01ApplicationTests {
@Autowired
private DeptDao deptDao;//无法注入DeptDao的对象,为什么无法注入【spring容器中没有dao接口的代理实现类】
@Autowired
@Test
void contextLoads() {
PageHelper.startPage(1,3);
List<Dept> all = deptDao.findAll();
//把查询的结果封装到PageInfo中
PageInfo<Dept> deptPageInfo = new PageInfo<>(all);
System.out.println("总页数:"+deptPageInfo.getPages());
System.out.println("总条数:"+deptPageInfo.getTotal());
System.out.println("当前页的记录:");
List<Dept> list = deptPageInfo.getList();
list.stream().forEach(System.out::println);
}
}
4.综合案例
4..1修改pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.hmq</groupId>
<artifactId>springboot02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot02</name>
<description>springboot02</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--pageHelper分页驱动-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
4.2properties
#数据源信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#characterEncoding防止添加到数据的数据出现乱码 ---utf-8
spring.datasource.url=jdbc:mysql://localhost:3306/hmq?serverTimezone=Asia/Shanghai&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
#指定mybatis映射文件的路径 classpath编译后的路径
mybatis.mapper-locations=classpath:mapper/*.xml
#控制台打印sql日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
4.3pojo
clazz实体类
package com.hmq.pojo;
import lombok.Data;
@Data
public class Clazz {
private Integer id;
private String name;
}
Student实体类
package com.hmq.pojo;
import lombok.Data;
@Data
public class Stu {
private Integer id;
private String headImg = "https://aaa165.oss-cn-beijing.aliyuncs.com/wz.jpg";
private String name;
private Integer age;
private String sex;
private Integer clazz_id;
private Clazz clazz;
}
4.4dao
package com.hmq.dao;
import com.hmq.pojo.Stu;
import com.hmq.vo.StuVo;
import java.util.List;
public interface StuDao {
//增加员工
public Integer save(Stu stu);
//修改员工
public Integer update(Stu stu);
//删除员工
public Integer delete(Integer id);
//查询员工id
public Stu selectById(Integer id);
//分页条件查询
public List<Stu> selectByCondition(StuVo stuVo);
}
4.5vo
package com.hmq.vo;
import lombok.Data;
@Data
public class StuVo {
private String name;
private String age;
}
4.6mapper
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hmq.dao.StuDao">
<!--添加-->
<insert id="save">
insert into tb_student(headImg,name,age,sex,clazz_id)
values(#{headImg},#{name},#{age},#{sex},#{clazzId})
</insert>
<!--修改-->
<update id="update">
update tb_student set headImg=#{headImg},name=#{name},age=#{age},sex=#{sex},clazz_id=#{clazzId} where id=#{id}
</update>
<!--删除-->
<delete id="delete">
delete from tb_student where id=#{id}
</delete>
<!--查询-->
<resultMap id="myMap" type="com.hmq.pojo.Stu" autoMapping="true">
<id property="id" column="id"/>
<result property="clazzId" column="clazz_id"/>
</resultMap>
<select id="selectById" resultMap="myMap">
select * from tb_student where id=#{id}
</select>
<!--分页-->
<select id="selectByCondition" resultMap="myMap">
select s.*,c.id cid,s.name from tb_student s join tb_clazz c on s.clazz_id=c.id
<where>
<if test="name!=null and name!=''">
s.name like concat("%",#{name},"%")
</if>
<if test="age!=null and age!=''">
age=#{age}
</if>
</where>
</select>
</mapper>
4.7service
package com.hmq.service;
import com.github.pagehelper.PageInfo;
import com.hmq.pojo.Stu;
import com.hmq.vo.StuVo;
import java.util.List;
public interface StuService {
//增加员工
public Integer save(Stu stu);
//修改员工
public Integer update(Stu stu);
//删除员工
public Integer delete(Integer id);
//查询员工id
public Stu selectById(Integer id);
//分页条件查询
public PageInfo<Stu> selectByCondition(Integer current, Integer pageSize, StuVo stuVo);
}
4.8impl
package com.hmq.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hmq.dao.StuDao;
import com.hmq.pojo.Stu;
import com.hmq.service.StuService;
import com.hmq.vo.StuVo;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class StuServiceImpl implements StuService {
@Autowired
private StuDao stuDao;
@Override
public Integer save(Stu stu) {
return stuDao.save(stu);
}
@Override
public Integer update(Stu stu) {
return stuDao.update(stu);
}
@Override
public Integer delete(Integer id) {
return stuDao.delete(id);
}
@Override
public Stu selectById(Integer id) {
return stuDao.selectById(id);
}
@Override
public PageInfo<Stu> selectByCondition(Integer current, Integer pageSize, StuVo stuVo) {
PageHelper.startPage(current,pageSize);
List<Stu> stus = stuDao.selectByCondition(stuVo);
PageInfo<Stu> PageInfo = new PageInfo<>(stus);
return PageInfo;
}
}
4.9controller
package com.hmq.controller;
import com.github.pagehelper.PageInfo;
import com.hmq.pojo.Stu;
import com.hmq.service.StuService;
import com.hmq.vo.Result;
import com.hmq.vo.StuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/stu")
public class StuController {
@Autowired
private StuService stuService;
@PostMapping
public Result save(@RequestBody Stu stu){
Integer save = stuService.save(stu);
return save>0?new Result(200,"添加成功",null):new Result(500,"添加失败",null);
}
@PutMapping //修改操作 postman
public Result update(@RequestBody Stu stu){
Integer update = stuService.update(stu);
return update>0?new Result(200,"修改成功",null):new Result(500,"修改失败",null);
}
@DeleteMapping
public Result delete(Integer id){
Integer delete = stuService.delete(id);
return delete>0?new Result(200,"删除成功",null):new Result(500,"删除失败",null);
}
@GetMapping
public Result get(Integer id){
Stu stu = stuService.selectById(id);
return new Result(200,"查询成功",stu);
}
@PostMapping("/findByCondition") //如果前端传递json对象 那么必须使用post或put提交
public Result findByCondition(Integer current, Integer pageSize, @RequestBody StuVo stuVo){
PageInfo<Stu> PageInfo = stuService.selectByCondition(current, pageSize, stuVo);
return new Result(200,"查询成功",PageInfo);
}
}