ThreadLocal工具类
ThreadLocal工具类
ThreadLocalUtil.java
public class ThreadLocalUtil {static final ThreadLocal THREAD_LOCAL = new ThreadLocal();public static <T> T get() {return (T) THREAD_LOCAL.get();}public static void set(Object value) {THREAD_LOCAL.set(value);}public static void remove() {THREAD_LOCAL.remove();}
}
ThreadLocal应用
配合拦截器使用
LoginInterceptor.java
import java.util.Map;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;import com.itheima.utils.JwtUtil;
import com.itheima.utils.ThreadLocalUtil;@Component
public class LoginInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {String token = request.getHeader("Authorization");ThreadLocalUtil.set(token);try {Map<String, Object> claims = JwtUtil.parseToken(token);return true;} catch (Exception e) {response.setStatus(401);return false;}}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {ThreadLocalUtil.remove();}
}
拦截器注意注册
WebConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import com.itheima.interceptors.LoginInterceptor;@Configuration
public class WebConfig implements WebMvcConfigurer {@AutowiredLoginInterceptor loginInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login", "/user/register");}
}
业务类内调用(比如controller层)
......@GetMapping("/userInfo")public Result<User> userInfo() {Map<String, Object> map = ThreadLocalUtil.get();String username = (String) map.get("username");User user = userService.findByUsername(username);return Result.suc(user);}
......