后端:
1,写一个验证token的拦截器
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ffyc.news.model.CommonData;
import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;public class AdminTokenInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String adminToken= request.getHeader("adminToken");boolean ans=JWTUtil.verify(adminToken);if(!ans){PrintWriter printWriter=response.getWriter();CommonData commonData=new CommonData(402,"Token验证失效,请重新登录!");String json=new ObjectMapper().writeValueAsString(commonData);printWriter.write(json);printWriter.close();}return ans;}
}
2,配置拦截器
import com.ffyc.news.util.AdminTokenInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {InterceptorRegistration interceptorRegistration=registry.addInterceptor(new AdminTokenInterceptor());interceptorRegistration.addPathPatterns("/admin/**");interceptorRegistration.excludePathPatterns("/admin/login/login");}// @Override
// public void addResourceHandlers(ResourceHandlerRegistry registry) {
//
// }
}
前端:
1,axios响应拦截
//axios 请求拦截 每次向后端发送
axios.interceptors.request.use(config => {//为请求头对象,添加 Token 验证的 token 字段config.headers.adminToken = window.sessionStorage.getItem('adminToken');return config;
})
axios.interceptors.response.use((resp) => { //正常响应拦截if (resp.data.code == 500) {ElementUI.Message({message: resp.data.message,type: "error"})}if (resp.data.code == 402) {ElementUI.Message({message: resp.data.message,type: "error"})router.replace("/login");}return resp;
});