Browse Source

feat: session过期时间使用redis过期时间

weijianghai 2 years ago
parent
commit
34b4f118fb

+ 2 - 1
src/main/java/com/nokia/common/R.java

@@ -2,6 +2,7 @@ package com.nokia.common;
 
 import io.swagger.v3.oas.annotations.media.Schema;
 import lombok.Data;
+import org.slf4j.MDC;
 
 /**
  * 返回值的统一包装
@@ -54,7 +55,7 @@ public class R<T> {
         R<T> r = new R<>();
         r.setSuccess(false);
         r.setCode(0);
-        r.setMessage("失败");
+        r.setMessage("失败" + MDC.get("traceId"));
         return r;
     }
 

+ 1 - 2
src/main/java/com/nokia/config/web/ControllerExceptionHandler.java

@@ -3,7 +3,6 @@ package com.nokia.config.web;
 import com.nokia.common.R;
 import com.nokia.common.exception.BizException;
 import lombok.extern.slf4j.Slf4j;
-import org.slf4j.MDC;
 import org.springframework.beans.TypeMismatchException;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
@@ -82,6 +81,6 @@ public class ControllerExceptionHandler
     public ResponseEntity<Object> exceptionHandler(Exception e)
     {
         log.error("╭( ′• o •′ )╭☞ 发生错误了 {}", e.getMessage(), e);
-        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(R.error("失败" + MDC.get("traceId")));
+        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(R.error());
     }
 }

+ 5 - 1
src/main/java/com/nokia/config/web/MyWebMvcConfigurer.java

@@ -1,6 +1,7 @@
 package com.nokia.config.web;
 
 import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
@@ -10,12 +11,15 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
 @Configuration
 public class MyWebMvcConfigurer implements WebMvcConfigurer {
+    @Value("${redis.timeoutSeconds:600}")
+    private Integer timeoutSeconds;
+
     @Override
     public void addInterceptors(InterceptorRegistry registry) {
         // 添加请求日志拦截
         registry.addInterceptor(new RequestLogHandlerInterceptor()).addPathPatterns("/**");
         // 添加web登录拦截
-        registry.addInterceptor(new WebLoginInterceptor()).addPathPatterns("/api/web/**");
+        registry.addInterceptor(new WebLoginInterceptor(timeoutSeconds)).addPathPatterns("/api/web/**");
     }
 
     /**

+ 18 - 4
src/main/java/com/nokia/config/web/WebLoginInterceptor.java

@@ -1,8 +1,9 @@
 package com.nokia.config.web;
 
 import com.alibaba.fastjson2.JSON;
+import com.nokia.common.R;
+import lombok.NoArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
-import org.springframework.http.HttpStatus;
 import org.springframework.web.servlet.HandlerInterceptor;
 
 import javax.servlet.http.HttpServletRequest;
@@ -13,25 +14,38 @@ import javax.servlet.http.HttpSession;
  * web登录拦截
  */
 @Slf4j
+@NoArgsConstructor
 public class WebLoginInterceptor implements HandlerInterceptor {
+    private Integer timeoutSeconds;
+
+    public WebLoginInterceptor(Integer timeoutSeconds) {
+        this.timeoutSeconds = timeoutSeconds;
+    }
+
     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         HttpSession session = request.getSession();
         // 未登录或登录失效返回401
         if (session == null || session.getAttribute("userinfo") == null) {
-            response.setStatus(HttpStatus.UNAUTHORIZED.value());
+            response.setCharacterEncoding("UTF-8");
+            response.setContentType("application/json; charset=utf-8");
+            response.getWriter().write(JSON.toJSONString(R.error().code(401).message("登录失效")));
+            log.warn("登录失效");
             return false;
         }
         // 没有权限返回403
         if (session.getAttribute("role") == null) {
-            response.setStatus(HttpStatus.FORBIDDEN.value());
+            response.setCharacterEncoding("UTF-8");
+            response.setContentType("application/json; charset=utf-8");
+            response.getWriter().write(JSON.toJSONString(R.error().code(403).message("权限不足")));
+            log.warn("权限不足");
             return false;
         }
         log.debug("sessionId: {}, userinfo: {}, role: {}", session.getId(),
                 JSON.toJSONString(session.getAttribute("userinfo")),
                 JSON.toJSONString(session.getAttribute("role")));
         // 延长session过期时间
-        session.setMaxInactiveInterval(600);
+        session.setMaxInactiveInterval(timeoutSeconds);
         return true;
     }
 }

+ 2 - 2
src/main/java/com/nokia/controller/web/WebAreaController.java

@@ -32,10 +32,10 @@ public class WebAreaController {
     }
 
     /**
-     * 查询省和地市树形接口(添加修改用户、操作日志地区选择框)
+     * 查询省和地市树形接口(添加修改用户、登录日志地区选择框)
      *
      */
-    @Operation(summary = "查询省和地市树形接口(添加修改用户、操作日志地区选择框)")
+    @Operation(summary = "查询省和地市树形接口(添加修改用户、登录日志地区选择框)")
     @PostMapping("treeProvinceCity")
     public R<TreeAreaVo> treeProvinceCity(HttpSession session) {
         return areaService.treeProvinceCity(session);