@GetMapping("/set-cookie")
// HttpServletResponse - Tomcat自动初始化的响应对象
public BaseResponse<Void> setCookie(HttpServletResponse response) {
Cookie cookie = new Cookie("key", "value");
cookie.setMaxAge(7 * 24 * 60 * 60);
cookie.setPath("/");
cookie.setHttpOnly(true);
response.addCookie(cookie);
return ResultUtils.success(null);
}
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://xxx.xx:5173", "http://xxx.xx:3000")
.allowedCredentials(true)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.maxAge(604800)
}
}
@Getter
public enum ErrorCode {
SUCCESS(0, "ok", "")
PARAMS_ERROR(40000, "参数错误", "")
PARAMS_NULL(40001, "参数为空", "")
NOT_LOGIN(40100, "未登录", "")
NOT_AUTH(40101, "未授权", "")
SYSTEM_ERROR(50000, "系统内部异常", "")
private final int code;
private final String message;
private final String description;
ErrorCode(int code, String message, String description) {
this.code = code;
this.message = message;
this.description = description;
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BaseResponse<T> implements Serializable {
private int code;
private T data;
private String message;
private String description;
public BaseResponse(int code, T data, String message) {
this(code, data, message, "");
}
public BaseResponse(int code, T data) {
this(code, data, "", "");
}
public BaseResponse(ErrorCode errorCode) {
this(errorCode.getCode(), null, errorCode.getMessage(), errorCode.getDescription());
}
}
public class ResultUtils {
public static <T> BaseResponse<T> success(T data) {
return new BaseResponse<>(0, data, "ok");
}
public static BaseResponse error(ErrorCode errorCode) {
return new BaseResponse(errorCode);
}
public static BaseResponse error(int code, String message, String description) {
return new BaseResponse(code, null, message, description);
}
}
@Getter
public class BusinessException extends RuntimeException {
private final int code;
private final String description;
public BusinessException(ErrorCode errorCode) {
super(errorCode.getMessage());
this.code = errorCode.getCode();
this.description = errorCode.getDescription();
}
public BusinessException(ErrorCode errorCode, String description) {
super(errorCode.getMessage());
this.code = errorCode.getCode():
this.description = description;
}
}
@Slf4j
@RestControllerAdvice // 全局统一异常拦截器
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public BaseResponse businessExceptionHandler(BusinessException e) {
log.error("businessException:" + e.getMessage(), e);
return ResultUtils.error(e.getCode(), e.getMessage(), e.getDescription());
}
@ExceptionHandler(RuntimeException.class)
public BaseResponse runtimeExceptionHandler(RuntimeException e) {
log.error("runtimeException", e);
return ResultUtils.error(ErrorCode.SYSTEM_ERROR, e.getMessage(), "")
}
}
@Data
public class DTO {
@NotBlank(message="name不能为空")
@Size(min=2, max=20, message="name长度需要在2-20之间")
private String name;
@Pattern(regexp="^[0-9a-zA-Z]{0, 30}$", message="密码格式不正确")
private String confirmPassword;
@Email(message="邮箱格式不正确")
private String email;
@Min(value=0, message="不能小于0")
@Max(value=100, message="不能大于100")
private Integer age;
}
@RestController
@RequestMapping("/group")
@RequiredArgsConstructor
public class XxxController {
private final XxxService xxxService;
@PostMapping("/{id}")
public BaseResponse<VO> xxx(
@PathVariable Long id,
@RequestParam(required=false) String name,
@RequestBody @Valid DTO dto,
HttpServletRequest request
) {
Object uid = request.getAttribute("uid");
VO vo = new VO();
return ResultUtils.success(VO);
}
}
@Component
public class JwtUtils {
@Value("${jwt.secret}")
private String secretKey;
@Value("#{ ${jwt.expire-hours} * 3600L * 1000 }") // SpEL:小时转毫秒
private long expireMs;
// claims:存放用户信息的 Map
public String generateToken(Map<String, Object> claims) {
return Jwts.builder()
.addClaims(claims)
.setExpiration(new Date(System.currentTimeMillis() + expireMs))
.signWith(SignatureAlgorithm.HS256, secretKey)
.compact();
}
public Claims parseToken(String token) {
if (token == null || token.isBlank()) {
throw new IllegalArgumentException("token不能为空");
}
try {
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody();
} catch (ExpiredJwtException e) {
throw new RuntimeException("token已过期");
} catch (SignatureException e) {
throw new RuntimeException("token签名非法,数据被篡改");
} catch (MalformedJwtException e) {
throw new RuntimeException("token格式错误");
} catch (Exception e) {
throw new RuntimeException("token解析失败");
}
}
}
@Slf4j
@WebFilter(urlPatterns = "/*", filterName = "jwtFilter")
public class JwtFilter implements Filter {
private static final List<String> WHITE_LIST = Arrays.asList(
"/api/login", "/api/register"
);
@Autowired
private JwtUtils jwtUtils;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String uri = request.getRequestURI();
// 白名单放行
if (WHITE_LIST.contains(uri)) {
filterChain.doFilter(request, response);
return;
}
String token = request.getHeader("token");
if (token == null || token.isBlank()) {
send401(response, "token不能为空");
return;
}
try {
Claims claims = jwtUtils.parseToken(token);
request.setAttribute("uid", claims.get("uid")); // 把用户 id 传给后续 Controller
filterChain.doFilter(request, response);
} catch (RuntimeException e) {
log.error("token校验失败: {}", e.getMessage());
send401(response, e.getMessage());
}
}
private void send401(HttpServletResponse response, String message) throws IOException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json;charset=UTF-8");
BaseResponse<?> failRes = ResultUtils.error(ErrorCode.NOT_LOGIN);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(response.getWriter(), failRes);
}
}
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object userId = SessionUtil.get("userId");
if (userId == null) {
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("{\"code\":401,\"msg\":\"请先登录\"}");
return false;
}
return true;
}
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/auth/login"); // 放行登录接口
}
}
public class SessionUtil {
public static HttpSession getSession() {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = sra.getRequest();
return request.getSession(true); // true: 没有则自动创建; false: 没有则返回 null
}
public static void set(String key, Object value) {
getSession().setAttribute(key, value);
}
public static Object get(String key) {
return getSession().getAttribute(key);
}
public static <T> T get(String key, Class<T> clazz) { // Long userId = SessionUtil.get("userId", Long.class);
return clazz.cast(get(key));
}
public static void remove(String key) {
getSession().removeAttribute(key);
}
public static void logout() {
HttpSession session = getSession(false);
if (session != null) session.invalidate();
}
}