欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

两篇文章总结Springboot的基础知识---------加深印象------快速回顾--------下(篇)

程序员文章站 2022-05-04 20:13:06
...


前言

接着上一篇Springboot总结一下基础知识点。

两篇文章总结Springboot的基础知识---------加深印象------快速回顾--------上(篇)


十六、与数据交互-mybatis(注解版)

首先,通过mybatis与数据库有三层,以后写就固定写三层,企业里边也是也三层的。

  1. mapper-数据持久层;
  2. service-业务处理层;
  3. controller–控制层;

步骤很简单,分五步:

(1)引入依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>

(2.)第二步:写mapper数据持久层,新建一个接口DeptMapper,把要实现与数据库交互的功能代码写上。前提已经新建,Dept这个类,
两篇文章总结Springboot的基础知识---------加深印象------快速回顾--------下(篇)
Mapper包下:

@Mapper //(1)表示这是一个数据持久层
public interface DeptMapper {

    //(2)写sql进行数据交互
    @Select("select * from department")
    public List<Dept> getDeptList();

    @Select("select * from department where id = #{id}")
    public Dept getDeptInfo(int id);

    //useGeneratedKeys = true,keyProperty = "id" 
    //useGeneratedKeys设置为 true 时,表示如果插入的表id以自增列为主键,则允许 JDBC 支持自动生成主键,并可将自动生成的主键id返回
    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int addDept(Dept dept);

    @Update("update department set departmentName = #{departmentName} where id = #{id}")
    public int updateDept(Dept dept);

    @Delete("delete from department where id = #{id}")
    public int deleteDept(int id);
}

(3)第三步:写service层。

public interface DeptService {
    public List<Dept> getDeptList();

    public Dept getDeptInfo(int id);

    public Dept addDept(String departmentName);

    public int updateDept(Dept dept);

    public int deleteDept(int id);
}

(4.)写service的实现类

@Service //(1)表示这是一个业务处理层
public class DeptServiceImpl implements DeptService {
// 新建一个类实现之前写的DeptService 接口,实现接口后必须实现接口中相应的方法。
    //(2)注入对应的mapper
    @Resource// 导入资源。
    private DeptMapper deptMapper; // 这里引入的接口。

    //(3)实现接口
    @Override
    public List<Dept> getDeptList() {
        return deptMapper.getDeptList();
    }

    @Override
    public Dept getDeptInfo(int id) {
        return deptMapper.getDeptInfo(id);
    }

    @Override
    public Dept addDept(String departmentName) {
        Dept dept = new Dept();
        dept.setDepartmentName(departmentName);
        deptMapper.addDept(dept);
        return dept;
    }

    @Override
    public int updateDept(Dept dept) {
        return deptMapper.updateDept(dept);
    }

    @Override
    public int deleteDept(int id) {
        return deptMapper.deleteDept(id);
    }
}

(5.)写controller层代码:

@RestController//(1)表示这是一个控制层
public class DeptMybatisController {
	//(2)注入业务层
    @Resource
    private DeptService deptService;
		
    @RequestMapping("getDeptList") // 浏览器请求的接口地址
    public List<Dept> getDeptList(){
        return deptService.getDeptList();
    }

    @RequestMapping("getDeptInfo")
    public Dept getDeptInfo(@RequestParam("id")int id){
        return deptService.getDeptInfo(id);
    }

    @RequestMapping("addDept")
    public Dept addDept(@RequestParam("departmentName")String departmentName){
        return deptService.addDept(departmentName);
    }

    @RequestMapping("updateDept")
    public int updateDept(Dept dept){
        return deptService.updateDept(dept);
    }

    @RequestMapping("deleteDept")
    public int deleteDept(@RequestParam("id")int id){
        return deptService.deleteDept(id);
    }
}

controller接受前台传值的方式有三种:

  • getMapping ---》@RequestParam(“id”) int id
  • postMapping --》@RequestBody Dept dept--请求方式:http://127.0.0.1:8081/updateDept?departmentNam=苏州吴中分部&id=3
@RequestMapping("getDeptInfo/{id}")
public Dept getDeptInfo(@PathVariable("id") int id){
    return deptService.getDeptInfo(id);
}

请求方式:http://127.0.0.1:8081/getDeptInfo/1

十七、idea与数据交互-mybatis(配置文件版)

同理写三层:

  • mapper 数据持久层
  • service 业务处理层
  • controller 控制层

步骤
(1)引入依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
 <dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <scope>runtime</scope>
 </dependency>

(2.)创建对应的mapper的接口。

@Mapper
public interface DeptMapper {

    public List<Dept> getDeptList(Dept dept);

    public Dept getDeptInfo(int id);

    public int addDept(Dept dept);

    public int updateDept(Dept dept);

    public int deleteDept(int id);
}

(3.)创建mybatis的配置类和对应的mapper的xml文件mybatis-config.xml.

<?xml version="1.0" encoding="UTF-8" ?>
        <!DOCTYPE configuration
                PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>

DeptMapper.xml文件之后要做的:

  1. 修改namespace为对应的mapper接口。
  2. 编写crud的sql语句。

注意:id和接口的方法名相同。

  • parameterType --》入参数据类型 方法形参。
  • resultType --》返回数据类型 方法的返回类型。
<?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.neusoft.mybatis001.mapper.DeptMapper">

    <sql id="baseSql">
        id,departmentName
    </sql>

    <select id="getDeptList" parameterType="com.neusoft.mybatis001.entity.Dept" resultType="com.neusoft.mybatis001.entity.Dept">
        select <include refid="baseSql"/> from department
        where 1=1
        <if test="id!=null and id!=0"> <!--当id不为空或为不等0的时候,这个条件才生效 除了and/or-->
            and id = #{id}
        </if>
        <if test="departmentName!=null and departmentName!=null">
            and departmentName = #{departmentName}
        </if>
    </select>

    <select id="getDeptInfo" parameterType="java.lang.Integer" resultType="com.neusoft.mybatis001.entity.Dept">
        select <include refid="baseSql"/> from department
        where id = #{id}
    </select>

    <!--${id} -》12     #{id}-》'12'-->
    <insert id="addDept" parameterType="com.neusoft.mybatis001.entity.Dept" useGeneratedKeys="true" keyProperty="id">
        insert into department(departmentName) values(#{departmentName})
    </insert>

    <update id="updateDept" parameterType="com.neusoft.mybatis001.entity.Dept">
        update department set departmentName = #{departmentName} where id = #{id}
    </update>

    <delete id="deleteDept" parameterType="java.lang.Integer">
        delete from department where id = #{id}
    </delete>

</mapper>

3.如果要在控制台打印sql,开启驼峰式自动转化。

<?xml version="1.0" encoding="UTF-8" ?>
        <!DOCTYPE configuration
                PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/><!--控制台打印sql-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--开启驼峰式自动转化 如:is_delete->isDelete -->
    </settings>
</configuration>

(4.))配置文件中定义mybatis-config.xml和mapper的扫描路径.

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

(5.)写service接口。

public interface DeptService {
    public List<Dept> getDeptList();

    public Dept getDeptInfo(int id);

    public Dept addDept(String departmentName);

    public int updateDept(Dept dept);

    public int deleteDept(int id);
}

(6.)写service的实现类

@Service //(1)表示这是一个业务处理层
public class DeptServiceImpl implements DeptService {

    //(2)注入对应的mapper
    @Resource
    private DeptMapper deptMapper;

    //(3)实现接口
    @Override
    public List<Dept> getDeptList() {
        return deptMapper.getDeptList();
    }

    @Override
    public Dept getDeptInfo(int id) {
        return deptMapper.getDeptInfo(id);
    }

    @Override
    public Dept addDept(String departmentName) {
        Dept dept = new Dept();
        dept.setDepartmentName(departmentName);
        deptMapper.addDept(dept);
        return dept;
    }

    @Override
    public int updateDept(Dept dept) {
        return deptMapper.updateDept(dept);
    }

    @Override
    public int deleteDept(int id) {
        return deptMapper.deleteDept(id);
    }
}

(7.)写controller.

@RestController//(1)表示这是一个控制层
public class DeptMybatisController {
	//(2)注入业务层
    @Resource
    private DeptService deptService;
		
    @RequestMapping("getDeptList")
    public List<Dept> getDeptList(){
        return deptService.getDeptList();
    }

    @RequestMapping("getDeptInfo")
    public Dept getDeptInfo(@RequestParam("id")int id){
        return deptService.getDeptInfo(id);
    }

    @RequestMapping("addDept")
    public Dept addDept(@RequestParam("departmentName")String departmentName){
        return deptService.addDept(departmentName);
    }

    @RequestMapping("updateDept")
    public int updateDept(Dept dept){
        return deptService.updateDept(dept);
    }

    @RequestMapping("deleteDept")
    public int deleteDept(@RequestParam("id")int id){
        return deptService.deleteDept(id);
    }
}

这里Teacher推荐的一种方法:
企业中使用逻辑删除,不使用物理删除。

实现:DeptMapper.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">
<mapper namespace="com.neusoft.mybatis001.mapper.DeptMapper">

    <sql id="baseSql">
        id,departmentName,is_delete
    </sql>

    <select id="getDeptList" parameterType="com.neusoft.mybatis001.entity.Dept" resultType="com.neusoft.mybatis001.entity.Dept">
        select <include refid="baseSql"/> from department
        where is_delete = 0
        <if test="id!=null and id!=0">
            and id = #{id}
        </if>
        <if test="departmentName!=null and departmentName!=null">
            and departmentName = #{departmentName}
        </if>
    </select>

    <select id="getDeptInfo" parameterType="java.lang.Integer" resultType="com.neusoft.mybatis001.entity.Dept">
        select <include refid="baseSql"/> from department
        where is_delete = 0 and id = #{id}
    </select>

    <!--${id} -》12     #{id}-》'12'-->
    <insert id="addDept" parameterType="com.neusoft.mybatis001.entity.Dept" useGeneratedKeys="true" keyProperty="id">
        insert into department(departmentName) values(#{departmentName})
    </insert>

    <update id="updateDept" parameterType="com.neusoft.mybatis001.entity.Dept">
        update department set departmentName = #{departmentName} where id = #{id}
    </update>

    <!--<delete id="deleteDept" parameterType="java.lang.Integer">
        delete from department where id = #{id}
    </delete>-->

    <update id="deleteDept" parameterType="java.lang.Integer">
        update department set is_delete = 1 where id = #{id}
    </update>
</mapper>

十八、开启分页

分四步:

  1. 加入相关依赖:
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.10</version>
</dependency>
  1. 在yml中配置对应分页的数据是哪个。
pagehelper:
  helper-dialect: mysql #表名我这个分页是mysql的数据库
  1. 改进我们查询list方法。
@Data
public class Dept {
    private Integer id;
    private String departmentName;
    private Integer pageNo;//第几页
    private Integer pageNum;//每页有多少个
}
  1. 控制层写:
@Override
public PageInfo<Dept> getDeptList(Dept dept) {
    //1.开启分页 ,传两个参数 
    PageHelper.startPage(dept.getPageNo(),dept.getPageNum());
    //2.正常查询我们的list接口
    List<Dept> list = deptMapper.getDeptList(dept);
    //3.将我们的list查询结果放到PageInfo进行处理
    PageInfo<Dept> pageInfo = new PageInfo<>(list);
    return pageInfo;
}

十九、切换自定义连接池druid

分四步:

  1. 加依赖:
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.1</version>
</dependency>

(2.)切换来源:

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource

(3.)加入一些自定义属性:

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai   #数据库路径
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    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,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

(4.)写配置文件使其生效。

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return new DruidDataSource();
    }
}

二十、springboot集成redis

  1. 加依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 在yml文件写关于redis的配置。
spring:	
    redis:
      host: 192.168.XXX.128 # redis服务器地址
      port: 6379            # redis服务端口号
      database: 0          # 指定redis服务中使用哪个服务器
      password:
  1. 写工具类或测试:
@SpringBootTest
class Jdbc10ApplicationTests {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Test
    public void testRedis(){
        //String
        //设置值
        stringRedisTemplate.opsForValue().set("k1","v1");
        //取值
        System.out.println(stringRedisTemplate.opsForValue().get("k1"));
        //在对应key后面拼接指定值
        stringRedisTemplate.opsForValue().append("k1",",hello!");
        System.out.println(stringRedisTemplate.opsForValue().get("k1"));
        stringRedisTemplate.opsForValue().set("k2","11");
        //指定key加上1或者指定值
        stringRedisTemplate.opsForValue().increment("k2");
        stringRedisTemplate.opsForValue().increment("k2",5);
        stringRedisTemplate.opsForValue().increment("k2",0.5);
        System.out.println(stringRedisTemplate.opsForValue().get("k2"));
        //指定key值不存在可以设置,当存在就设置失败
        stringRedisTemplate.opsForValue().setIfAbsent("k3","22");
        System.out.println(stringRedisTemplate.opsForValue().get("k3"));
        stringRedisTemplate.delete("k3");
        System.out.println(stringRedisTemplate.opsForValue().get("k3"));

        //list
        stringRedisTemplate.delete("list001");
        stringRedisTemplate.delete("list002");
        //左插入一个元素
        stringRedisTemplate.opsForList().leftPush("list001","a");
        //在a左插入一个元素
        stringRedisTemplate.opsForList().leftPush("list001","a","b");
        System.out.println(stringRedisTemplate.opsForList().range("list001",0,-1));
        //从左插入多个
        stringRedisTemplate.opsForList().leftPushAll("list001","c","d","e");
        System.out.println(stringRedisTemplate.opsForList().range("list001",0,-1));
        List<String> list = new ArrayList<>();
        list.add("f");
        list.add("h");
        stringRedisTemplate.opsForList().leftPushAll("list001",list);
        stringRedisTemplate.opsForList().leftPop("list001");
        System.out.println(stringRedisTemplate.opsForList().range("list001",0,-1));
        //获取指定下标的元素
        System.out.println(stringRedisTemplate.opsForList().index("list001",2));
        //左出栈,当指定key为空时,等待10秒,只要10秒这个key有值了,立马左出一个,然后结束
        //当key有值时,直接左出一个,然后结束
        //stringRedisTemplate.opsForList().leftPop("list002",10, TimeUnit.SECONDS);
        stringRedisTemplate.opsForList().rightPush("list001","h");
        System.out.println(stringRedisTemplate.opsForList().range("list001",0,-1));
        System.out.println(stringRedisTemplate.opsForList().range("list002",0,-1));
        //list001右边出一个放到list002左边
        stringRedisTemplate.opsForList().rightPopAndLeftPush("list001","list002");
        System.out.println(stringRedisTemplate.opsForList().range("list002",0,-1));

        //取list001的0~2下标的元素给list001
        stringRedisTemplate.opsForList().trim("list001",0,2);
        System.out.println(stringRedisTemplate.opsForList().range("list001",0,-1));

        //hash
        //设置指定key的属性
        stringRedisTemplate.opsForHash().put("user","id","001");
        //查看指定key的指定属性
        System.out.println(stringRedisTemplate.opsForHash().get("user","id"));
        Map<String,String> map = new HashMap<>();
        map.put("age","12");
        map.put("email","@163.com");
        stringRedisTemplate.opsForHash().putAll("user",map);
        //删除指定key值下得一个或者多个属性
        //stringRedisTemplate.opsForHash().delete("user","id","age");
        //查看指定key值得所有属性对
        System.out.println(stringRedisTemplate.opsForHash().entries("user"));
        //查看所有得key值下所有得属性名
        System.out.println(stringRedisTemplate.opsForHash().keys("user"));
        //查看所有得key值下所有得属性值
        System.out.println(stringRedisTemplate.opsForHash().values("user"));
        //给key值下指定得属性加上指定得整数/浮点数
        stringRedisTemplate.opsForHash().increment("user","age",3);
        stringRedisTemplate.opsForHash().increment("user","age",0.5);
        //当key下属性存在时,插入失败,不存在时插入成功
        stringRedisTemplate.opsForHash().putIfAbsent("user","age","13");
        stringRedisTemplate.opsForHash().putIfAbsent("user","host","10.1.152.1");
        System.out.println(stringRedisTemplate.opsForHash().entries("user"));

        //set
        stringRedisTemplate.opsForSet().add("set001","1","2","3","4","5");
        //查看所有元素
        System.out.println( stringRedisTemplate.opsForSet().members("set001"));
        //查询set001下有没有6这个元素
        System.out.println( stringRedisTemplate.opsForSet().isMember("set001","6"));
        //随机返回set001里面得一个或者多个,randomMembers方法可能会重复,distinctRandomMembers不重复
        System.out.println(stringRedisTemplate.opsForSet().randomMember("set001"));
        System.out.println(stringRedisTemplate.opsForSet().randomMembers("set001",3));
        System.out.println(stringRedisTemplate.opsForSet().distinctRandomMembers("set001",3));
        System.out.println( stringRedisTemplate.opsForSet().members("set001"));

        stringRedisTemplate.opsForSet().add("set002","1","2","3","a","b");
        //set001在set002中不存在得值,差集
        System.out.println(stringRedisTemplate.opsForSet().difference("set001","set002"));
        System.out.println(stringRedisTemplate.opsForSet().union("set001","set002"));
        System.out.println(stringRedisTemplate.opsForSet().intersect("set001","set002"));
        //set001在set002中不存在得值放到set003中,返回值差集得个数
        System.out.println(stringRedisTemplate.opsForSet().differenceAndStore("set001","set002","set003"));
        System.out.println( stringRedisTemplate.opsForSet().members("set003"));

        //zset
        stringRedisTemplate.opsForZSet().add("zset001","a",100);
        stringRedisTemplate.opsForZSet().add("zset001","c",90);
        stringRedisTemplate.opsForZSet().add("zset001","b",70);
        stringRedisTemplate.opsForZSet().add("zset001","d",80);
        System.out.println( stringRedisTemplate.opsForZSet().range("zset001",0,-1));
        System.out.println( stringRedisTemplate.opsForZSet().rangeByScore("zset001",70,90));

    }

二十一、实现redis的session共享

分四步:

  1. 加依赖
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>

2.编写配置类:

@EnableCaching //开启缓存
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600)//session过期时间(秒) //开启redis得httpsession共享
@Configuration
public class RedisSessionConfig {

}

两篇文章总结Springboot的基础知识---------加深印象------快速回顾--------下(篇)
3.控制层写一个接口实现共享

@RestController
public class TestSessionController {

    @RequestMapping("set")
    public Map<String,Object> set(String id, String name, HttpSession session){
        session.setAttribute(id,name);//设置session值
        Map<String,Object> result = new HashMap<>();
        result.put(id,name);
        result.put("sessionId",session.getId());//取出sessionId
        return result;
    }

    @RequestMapping("get")
    public Map<String,Object> get(String id, HttpSession session){
        Map<String,Object> result = new HashMap<>();
        result.put("name",session.getAttribute(id));//根据key获取session值
        result.put("sessionId",session.getId());//取出sessionId
        return result;
    }
}

4.启动两个服务,测试,一个端口号8081,一个8082

用8081登录:

http://localhost:8081/set?id=001&name=xywang
http://localhost:8081/get?id=001
http://localhost:8082/get?id=001

二十二、封装返回对象

@Data
@Accessors(chain = true)//可以链式操作
public class Result {
    private Integer code; //0成功 1异常
    private String msg;
    private Object data;
}

两篇文章总结Springboot的基础知识---------加深印象------快速回顾--------下(篇)

控制层代码:

两篇文章总结Springboot的基础知识---------加深印象------快速回顾--------下(篇)

@Resource
private SysUserService sysUserService;

@Resource
private StringRedisTemplate stringRedisTemplate;

@RequestMapping("login")
public Result login(SysUser sysUser, HttpSession session){
    SysUser user = sysUserService.getSysUsersForLogin(sysUser);
    if(user==null){
        return new Result().setCode(1).setMsg("登录名或者密码错误!");
    }
    session.setAttribute("user",user.getId());
    stringRedisTemplate.opsForHash().put("user:"+user.getId(),"name",user.getUserName());
    stringRedisTemplate.opsForHash().put("user:"+user.getId(),"phone",user.getPhone());
    stringRedisTemplate.opsForHash().put("user:"+user.getId(),"email",user.getEmail());
    user.setSessionId(session.getId());
    return new Result().setCode(0).setMsg("登录成功").setData(user);
}

二十三、开启登录拦截

1.编写拦截处理器类AccessHandler。

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AccessHandler implements HandlerInterceptor {
    @Override
    //这个方法是在访问接口之前执行的,我们只需要在这里写验证登陆状态的业务逻辑,就可以在用户调用指定接口之前验证登陆状态了
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //每一个项目对于登陆的实现逻辑都有所区别,我这里使用最简单的Session提取User来验证登陆。
        HttpSession session = request.getSession();
        //这里的User是登陆时放入session的
        String user = String.valueOf(session.getAttribute("user"));
        //如果session中没有user,表示没登陆
        if (session.getAttribute("user") == null){
            //这个方法返回false表示忽略当前请求,如果一个用户调用了需要登陆才能使用的接口,如果他没有登陆这里会直接忽略掉
            //当然你可以利用response给用户返回一些提示信息,告诉他没登陆
            response401(response);
            return false;
        }else {
            return true;    //如果session里有user,表示该用户已经登陆,放行,用户即可继续调用自己需要的接口
        }
    }

    private void response401(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            response.getWriter().print("用户未登录!");
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2.定义拦截规则

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AccessHandler())
                .addPathPatterns("/**")         //添加需要进行拦截的链接
                .excludePathPatterns("/login");       //排除不需要拦截的链接,多个链接直接用逗号隔开
        System.out.println("===========   拦截器注册完毕   ===========");
    }
}

二十四、日志

1.使用

//创建日志对象
Logger logger = LoggerFactory.getLogger(Jdbc10ApplicationTests.class);

    @Test
    public void testLogger(){
        //trace < debug < info < warn <error
        //springboot得默认级别 从info开始  ,--》root级别
        logger.trace("这是一个轨迹");
        logger.debug("这是debug");
        logger.info("这是{},测试{}","info信息","test");
        logger.warn("这是警告级别");
        logger.error("error");
    }

2.设置打印级别

logging:
  level.com.neusoft: trace

logging:
      lever、需要扫描的包:trace
3.设置输出日志外部文件。

logging:
  level.com.neusoft: trace
  file:
    path: D:/test2.log  //设置外部日志文件得路径 ,文件名默认时spring.log不可修改
    name: D:/test.log   //设置外部日志文件得路径和名称
   //当path和name同时存在时,name覆盖path
   //当都不指定具体路径时,都是默认在项目得根目录下产生

4.设置日志输出格式:

1.修改输出格式

# 在控制台输出的日志的格式

logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50}- %msg%n

# 指定文件中日志输出的格式

logging.pattern.file=%d{yyyy-MM-dd} [%thread] = %-5level + %logger{50} %msg%n

2.关键字

%d表示日期时间,

%thread表示线程名,

%‐5level:级别从左显示5个字符宽度

%logger{50} 表示logger名字最长50个字符,否则按照句点分割。

%msg:日志消息,

%n是换行符

标准的格式:%d{yyyy‐MM‐dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} ‐ %msg%n

logging:
  level.com.neusoft: trace
  file:
    #path: D:/test2.log
    name: D:/test.log
  pattern:
    console: '%d{yyyy‐MM‐dd HH:mm}--[%thread] %-5level // %logger{50} ++ %msg%n'
    file:  '%d{yyyy‐MM‐dd HH:mm}--[%thread] %-5level // %logger{50} ++ %msg%n'

二十五、集成调试工具swagger2

1)加依赖

 <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>

(2)配置类

 import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @Configuration
    @EnableSwagger2  //(1)开启调试
    public class Swagger2 {
        //swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    //(2)为当前包路径
                 .apis(RequestHandlerSelectors.basePackage("com.neusoft"))
                    .paths(PathSelectors.any())
                    .build();
        }
        //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    //(3)页面标题
                    .title("这是标题Spring Boot 测试使用 Swagger2 构建RESTful API")
                    //(4)创建人
                    .contact(new Contact("xywang", "http://www.baidu.com", "aaa@qq.com"))
                    //(5)版本号
                    .version("1.0")
                    //(6)描述
                    .description("这是API 描述")
                    .build();
        }
    }

(3)要是有中文提示,加@Api和@ApiOperation

 @RestController
    @Api(description = "登录接口")
    public class LoginController {
    
        @Resource
        private SysUserService sysUserService;
    
        @Resource
        private StringRedisTemplate stringRedisTemplate;
    
        @GetMapping("login")
        @ApiOperation("登录")
        public Result login(SysUser sysUser, HttpSession session){
            SysUser user = sysUserService.getSysUsersForLogin(sysUser);
            if(user==null){
                return new Result().setCode(1).setMsg("登录名或者密码错误!");
            }
            session.setAttribute("user",user.getId());
            stringRedisTemplate.opsForHash().put("user:"+user.getId(),"name",user.getUserName());
            stringRedisTemplate.opsForHash().put("user:"+user.getId(),"phone",user.getPhone());
            stringRedisTemplate.opsForHash().put("user:"+user.getId(),"email",user.getEmail());
            user.setSessionId(session.getId());
            return new Result().setCode(0).setMsg("登录成功").setData(user);
        }
    }
    

请求:
(1)get --》 获取某个详情,下载

(2)post --》分页 ,查询list

(3)put --》修改

(4)delete --》 删除

分的不详细:

(1)get --》 获取某个详情,下载

(2)post --》分页 ,查询list,修改,删除


写在最后

如果本文对你有帮助的话,给我点歌赞再走吧。

胜利者往往是从坚持最后五分钟的时间中得来成功。——牛顿