教你如何優(yōu)雅的實現(xiàn)接口登錄限制

在項目開發(fā)時,大部分操作時都是基于用戶登錄狀態(tài)下的。攔截器是最經(jīng)常使用的方式,這里我結(jié)合了自定義注解。https://github.com/XMUTLZY/login-check-demo

項目結(jié)構

項目結(jié)構.png

Demo主要用Springboot搭建

  • vo包:定義了一個用戶實體類
  • annotation包:存放自定義的注解
  • config包:配置類,主要用于初始化攔截器
  • controller包:一些操作,比如登錄校驗、訪問主頁
  • interceptor包:定義攔截器

具體實現(xiàn)

自定義注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by lin on 2020/04/10
 */
@Target(ElementType.METHOD) //標記在方法上
@Retention(RetentionPolicy.RUNTIME) //生命周期(運行時有效)
public @interface LoginRequired {
}

這里主要用到2個元注解,其中@Target和@Retention有多個枚舉型可以設置,具體看源碼。

攔截器
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import redis.clients.jedis.Jedis;
import sch.jake.logincheckdemo.web.annotation.LoginRequired;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Created by lin on 2020/04/10
 * @Tip: 登錄校驗攔截器
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {  //判斷處理請求的handler類型
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();  //獲取處理請求的方法
        if (method.getAnnotation(LoginRequired.class) != null) {    //判斷該方法上是否有自定義的注解
            Jedis jedis = new Jedis("127.0.0.1", 6379);
            String userJsonStr = jedis.get("USER_INFO");
            if (!StringUtils.hasText(userJsonStr)) {    //判斷緩存中是否有用戶數(shù)據(jù)
                return false;
            }
        }
        return true;
    }
}

簡單來說就是,攔截器攔截請求,當注解標記在該請求方法上時,查詢緩存中是否有用戶信息。

配置類
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import sch.jake.logincheckdemo.web.interceptor.LoginInterceptor;

/**
 * Created by lin on 2020/04/10
 * @Tip: 配置類,用于初始化攔截器
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor());
    }

    @Bean
    public LoginInterceptor loginInterceptor() {
        return new LoginInterceptor();
    }
}

這里就是初始化攔截器,并注冊到配置中。

Controller
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import sch.jake.logincheckdemo.vo.User;
import sch.jake.logincheckdemo.web.annotation.LoginRequired;

/**
 * Created by lin on 2020/04/10
 */
@Controller
public class TestController {

    //登錄校驗(成功時在緩存中存放用戶信息)
    @PostMapping("/verify")
    @ResponseBody
    public String verify(@RequestBody User user) {
        if ("Jake.lin".equals(user.getUserName()) && "test123".equals(user.getPassword())) {
            Jedis jedis = new Jedis("127.0.0.1", 6379);
            String userJsonStr = JSONObject.toJSONString(user);
            jedis.set("USER_INFO", userJsonStr);
            return "success";
        }
        return "failure";
    }

    //進入主頁
    @GetMapping("/index")
    @LoginRequired
    public String index() {
        return "index.html";
    }
}

這里主要定義了兩個方法。
(1)當用戶調(diào)用/verify接口時,如果用戶密碼輸入正確,將用戶信息序列化之后存入Redis緩存中。
(2)自定義注解標記在index()方法,表示當訪問該方法時,會對登錄狀態(tài)進行校驗(因為之前已經(jīng)定義過攔截器對方法上是否存在自定義注解進行判斷)

總結(jié)

這樣當用戶請求的操作需要登錄狀態(tài)時,只需要在對應請求的方法上添加注解即可。這里我使用的是Redis替代了session的功能,意思一樣

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容