SpringBoot+Vue前后台分离使用session存储用户状态

迷人闹G
迷人闹G
擅长邻域:Java,HTML,MySQL,Linux,SpringBoot,SpringCloud,Vue,Layui,小程序

分类: Java 标签: SpringBoot Vue

2021-05-07 09:01:04 2000浏览

SpringBoot+Vue前后台分离使用session存储用户状态 昨天遇到了一个问题 就是前后端分离的项目 不用redis怎么实现登录用户状态管理
因为前后端分离的话 普通情况下是拿不到htpSession这个对象的 不像JSP一样
先配置后台跨域
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
.allowCredentials(true).maxAge(6000);
}
}
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "CorsFilter ")
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;

HttpServletRequest reqs = (HttpServletRequest) req;

// response.setHeader("Access-Control-Allow-Origin",reqs.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}

@Override
public void init(FilterConfig filterConfig) {}

@Override
public void destroy() {}

}
写一个拦截器 用于拦截没有登录的用户请求(判断session中有没有user)
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.mfc.entity.EtAdmin;


public class LoginInterceptor implements HandlerInterceptor {

// 执行Handler方法之前执行
// 用于身份认证、身份授权
// 比如身份认证,如果认证通过表示当前用户没有登陆,需要此方法拦截不再向下执行
//验证用户权限

@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("---"+request.getSession().getAttribute("user"));
if(null == request.getSession().getAttribute("user")){
return false;
}
return true;

}

// 进入Handler方法之后,返回modelAndView之前执行
// 应用场景从modelAndView出发:将公用的模型数据(比如菜单导航)在这里
// 传到视图,也可以在这里统一指定视图
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {

}

// 执行Handler完成执行此方法
// 应用场景:统一异常处理,统一日志处理
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
然后把这个拦截器注册(addPathPattern是添加过滤路径 excludePathPatterns是排除过滤路径 也就是说/user下面的请求 只有login可以不走拦截器 其他的都会走)
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.mfc.Interceptor.LoginInterceptor;


@Configuration
public class WebappAdapter implements WebMvcConfigurer{

/**
* 注册拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/user/**")
.excludePathPatterns("/user/login");
}

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> arg0) {
// TODO Auto-generated method stub

}

@Override
public void addCorsMappings(CorsRegistry arg0) {
// TODO Auto-generated method stub

}

@Override
public void addFormatters(FormatterRegistry arg0) {
// TODO Auto-generated method stub

}

@Override
public void addResourceHandlers(ResourceHandlerRegistry arg0) {
// TODO Auto-generated method stub

}

@Override
public void addReturnValueHandlers(
List<HandlerMethodReturnValueHandler> arg0) {
// TODO Auto-generated method stub

}

@Override
public void addViewControllers(ViewControllerRegistry arg0) {
// TODO Auto-generated method stub

}

@Override
public void configureAsyncSupport(AsyncSupportConfigurer arg0) {
// TODO Auto-generated method stub

}

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer arg0) {
// TODO Auto-generated method stub

}

@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer arg0) {
// TODO Auto-generated method stub

}

@Override
public void configureHandlerExceptionResolvers(
List<HandlerExceptionResolver> arg0) {
// TODO Auto-generated method stub

}

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> arg0) {
// TODO Auto-generated method stub

}

@Override
public void configurePathMatch(PathMatchConfigurer arg0) {
// TODO Auto-generated method stub

}

@Override
public void configureViewResolvers(ViewResolverRegistry arg0) {
// TODO Auto-generated method stub

}

@Override
public void extendHandlerExceptionResolvers(
List<HandlerExceptionResolver> arg0) {
// TODO Auto-generated method stub

}

@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> arg0) {
// TODO Auto-generated method stub

}

@Override
public MessageCodesResolver getMessageCodesResolver() {
// TODO Auto-generated method stub
return null;
}

@Override
public Validator getValidator() {
// TODO Auto-generated method stub
return null;
}

}
VUE中需要简单配置一下axios(后面可以吧axios封装起来 我这项目比较小 就暂时没有封装)
在main.js中配置并引用axios(当请求后台被拦截的话 就跳转到登录页面)
import VueAxios from 'vue-axios'
import axios from 'axios'

Vue.use(VueAxios, axios)
axios.defaults.baseURL = 'http://localhost:8099'
axios.defaults.withCredentials=true;//请求发送cookie
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
console.log('in interceptor, request config: ', config);
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
console.log('in interceptor, response: ', response);
if(!response.data.success){
console.log('errCode:', response.data.errCode, 'errMsg:', response.data.errMsg);
let code = response.data.errCode;
console.log("reposne ",response)
if('login02'==code){ //登录session失效
//window.location.href = '/';
console.log('before to login, current route path:', router.currentRoute.path);
router.push({path:'/login'});
}
}
return response;
}, function (error) {
// 对响应错误做点什么
console.log('in interceptor, error: ', error);
router.push({path:'/login'});
return Promise.reject(error);
});
登录的话就写了一个简易的请求
const loading = this.$loading({
lock: true,
text: "登录中",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.7)",
});
that.axios.get("/user/login?stu_no="+this.username+"&upass="+this.password).then(res=>{
console.log(res)
if(res.data.status == 0){
this.$message(res.data.msg)
loading.close();
}else{
loading.close();
sessionStorage.setItem("userId",res.data.stu.id)
sessionStorage.setItem("realname",res.data.stu.realname)
that.$router.replace("Home");
}
后台处理登录(登录成功后session中储存用户信息)

好博客就要一起分享哦!分享海报

此处可发布评论

评论(0展开评论

暂无评论,快来写一下吧

展开评论

您可能感兴趣的博客

客服QQ 1913284695