简介
大家以前都使用过session存储信息,有的交给容器创建,有的存储到mysql或者redis,这次项目用到了JWT,我们把用户的信息和登录的过期时间都封装到一个token字符串里,客户端每次请求只需要在头信息里携带token即可,话不多说,下面是目录结构.
一.annonation注解
package com.demo.annotation;import java.lang.annotation.*;@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface IgnoreLogin {}
该注解主要作用是过滤掉请求拦截器,使用该注解就不会对该请求进行拦截(权限校验),具体使用下面讲.
package com.demo.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * 登录用户信息 */@Target(ElementType.PARAMETER)@Retention(RetentionPolicy.RUNTIME)public @interface LoginUser {}
该注解作用是SpringMVC参数解析器,类似于RequestBody注解(希望大家了解springmvc的参数解析机制),和我们后面的resolver相关联.
二.bean实体类
package com.demo.bean;public class User { private long userId; private String userName; private String password; 忽略get/set}
我们的用户信息
package com.demo.bean;public class Business { private String str; private int num; 忽略get/set}
我们的业务参数
三.config配置信息
package com.demo.config;import com.demo.interceptor.AuthorizationInterceptor;import com.demo.resolver.UserArgumentResolver;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.web.method.support.HandlerMethodArgumentResolver;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.util.List;/** * MVC配置 */@Configurationpublic class WebMvcConfig implements WebMvcConfigurer { @Autowired private AuthorizationInterceptor authorizationInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authorizationInterceptor).addPathPatterns("/**"); //注入我们自定义的拦截器,拦截所有请求 } @Override public void addArgumentResolvers(List resolvers) { resolvers.add(new UserArgumentResolver()); //注入我们的用户参数解析器 }}
四.controller
package com.demo.controller;import com.demo.annotation.IgnoreLogin;import com.demo.annotation.LoginUser;import com.demo.bean.Business;import com.demo.bean.User;import com.demo.util.JwtUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;@RestControllerpublic class UserController { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private JwtUtils jwtUtils; @PostMapping(value = "/login") @IgnoreLogin public String login() { //在此 我们不做登录检验 假设检验成功 User user = new User(); user.setUserId(9527); user.setUserName("小星星"); return jwtUtils.generateToken(user);//这里只是为了测试只返回token,(请求不含IgnoreLogin注解时需要将token放在头信息里) } @PostMapping("/business") public User business(@RequestBody Business business, @LoginUser User user) {//在业务逻辑可以使用注解将我们的user注入进来 logger.info("用户信息参数id:{},姓名:{}