springboot+vue 先後端分離項目實戰二 項目登陸攔截

這幾天把項目基本的框架搭建好了,開始設置登陸攔截器
直接上代碼,須要兩個類 LoginInterceptor ,WebConfig (名字是我的起的)
LoginInterceptor 繼承HandlerInterceptorhtml

package com.face.server.interceptor;
import com.face.server.constant.FaceConstant;
import com.face.server.dto.UserDO;
import com.face.server.utils.LoginContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        UserDO user = (UserDO) session.getAttribute(FaceConstant.USER_DO_KEY);
        if(user==null) {
            String userName = null;
            String password = null;
            String url = request.getContextPath()+"/api/login/login/"+userName+"/"+password;
            response.sendRedirect(url);//攔截後跳轉的方法
            System.out.println("已成功攔截並轉發跳轉"+url);
            return false;
        }
        LoginContext.putSessionVisitor(user);
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

WebConfig 繼承WebMvcConfigurationSupport前端

package com.face.server.interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 須要攔截的路徑
        String[] addPathPatterns = {
                "/**"
        };
        //不須要攔截的路徑
        String[] excludePathPatterns = {
                "/api/login/**",
                "/doc.html/**",
                "/swagger-resources/**",
                "/swagger-ui.html/**",
                "/v2/api-docs/**",
                "/webjars/**",
                "/error/**"
        };

        //addPathPatterns()添加攔截路徑
        //excludePathPatterns() 添加不攔截的路徑
        //添加註冊登陸攔截器
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePathPatterns);
    }
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("doc.html","/v2/api-docs/","/swagger-ui.html","/webjars/**","/error/**")
                .addResourceLocations("classpath:/META-INF/resources/");
    }
}

這樣除了登陸/api/login,swagger 接口外,其餘接口都走了登陸攔截,若是沒有登陸會會返回401,vue前端進行判斷
例如:前端main主頁面調用 獲取用戶權限的接口,固然這些接口的返回值判斷能夠單獨抽出來,寫成公共方法,之後再實現vue

export default {
  data () {
    const item = {
      date: '',
      name: '',
      address: ''
    }
    return {
      tableData: Array(20).fill(item),
      menuDate: ''
    }
  },
  created () {
    this.convert()
  },
  methods: {
    convert: function () {
      this.$axios.get('/menu/user').then(res => {
        let { code } = res.data
        if (code === 200) {
          console.log(res.data)
          console.log(code)
          console.log(res.data.data[0].menuName)
          this.menuDate = res.data.data
        } else if (code === 401) {
          window.location.href = '/login'
        }
      })
    }
  }
}
</script>

springboot+vue 先後端分離項目實戰一 項目的搭建
java