1.拦截器分为request请求拦截器和response响应拦截器
PS:request请求拦截器:发送请求前统一处理,如:设置请求头headers、应用的版本号、终端类型等。
response响应拦截器:有时候我们要根据响应的状态码来进行下一步操作,例如:由于当前的token过期,接口返回401未授权,那我们就要进行重新登录的操作。
2.main.js文件中(先安装axios)
import axios from 'axios'
// 给Vue函数添加一个原型属性$axios指向axios(全局使用axios)
// vue实例中直接用this.$axios就可以执行axios方法
Vue.prototype.$axios=axios
3.http request 请求拦截器
PS:发送请求之前判断是否存在token,除了登录页,其他页面请求头headers都添加token
// http request 请求拦截器
axios.interceptors.request.use(config => {
// 在发送请求之前做些什么
let pathname = location.pathname;
if(localStorage.getItem('token')){
if(pathname != '/' && pathname != '/login'){
config.headers.common['token'] = localStorage.getItem('token');
}
}
return config;
}, error => {
// 对请求错误做些什么
return Promise.reject(error);
});
4.http response 响应拦截器
PS:若返回401,页面跳转到登录页面
// http response 响应拦截器
axios.interceptors.response.use(response => {
return response;
},error => {
if (error.response) {
switch (error.response.status) {
// 返回401,清除token信息并跳转到登录页面
case 401:
localStorage.removeItem('token');
router.replace({
path: '/login'
//登录成功后跳入浏览的当前页面
// query: {redirect: router.currentRoute.fullPath}
})
}
// 返回接口返回的错误信息
return Promise.reject(error.response.data);
}
});
springboot设置拦截器
package com.cignacmb.sms.common.interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
protected void addInterceptors(InterceptorRegistry registry) {
// 多个拦截器组成一个拦截器链
// addPathPatterns 用于添加拦截规则,/**表示拦截所有请求
// excludePathPatterns 用户排除拦截
registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
// .excludePathPatterns("/stuInfo/getAllStuInfoA","/account/register");
super.addInterceptors(registry);
}
}
package com.cignacmb.sms.common.interceptor;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.cignacmb.sms.common.Constants;
@Component
public class LoginInterceptor implements HandlerInterceptor {
private static Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
// TODO Auto-generated method stub
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
//获取请求的URL
String url = request.getRequestURI();
log.info("请求url:" + url);
//URL:除了登陆的请求,其余都拦截
if (url != null && url.contains("/login")) {
return true;
}
//判断是否已登录
if(request.getSession().getAttribute(Constants.USER_SESSION) != null){
return true;
}
response.setContentType("text/html;charset=UTF-8");
ServletOutputStream out = response.getOutputStream();
out.write("未授权访问,请登录账号".getBytes("UTF-8"));
response.setStatus(999);
out.flush();
out.close();
return false;
}
}