1、前端
import axios from 'axios'
axios.defaults.withCredentials = true
2、后台
package com.jbossjf.bootproject.common.OriginConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.RegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Arrays;
/**
* @Author : JCccc
* @CreateTime : 2019/10/25
* @Description : 拦截器配置总部
* 普及:Tomcat(Filter->Servlet->Interceptor->Controller)
**/
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
//解决跨域问题
@Override
public void addCorsMappings(CorsRegistry registry) {
System.out.println("我是MyWebConfig跨域");
registry.addMapping("/API/**").allowedOrigins("*")
.allowCredentials(true);
}
// @Bean
// public RegistrationBean myFilter(){
// LoginFilter loginFilter = new LoginFilter();
// FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(loginFilter);
// filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
// return filterRegistrationBean;
// }
}
package com.jbossjf.bootproject.common.WebSecurity;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class SessionConfiguration extends WebMvcConfigurerAdapter {
//注册session监听器;
@Bean
public ServletListenerRegistrationBean<SessionListener> servletListenerRegistrationBean() {
ServletListenerRegistrationBean<SessionListener> slrBean = new ServletListenerRegistrationBean<SessionListener>();
slrBean.setListener(new SessionListener());
return slrBean;
}
}
package com.jbossjf.bootproject.common.WebSecurity;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
public class MySessionContext {
private static MySessionContext context;
private Map<String, HttpSession> map;
private MySessionContext() {
map = new HashMap<>();
}
public static MySessionContext getSessionContext() {
if(context == null) {
context = new MySessionContext();
}
return context;
}
//添加
public synchronized void addSession(HttpSession session) {
if(session!= null) {
map.put(session.getId(), session);
}
}
//获取
public synchronized HttpSession getSession(String sessionId) {
if(sessionId == null) {
return null;
}
return map.get(sessionId);
}
//删除
public synchronized void delSession(HttpSession session) {
if(session!= null) {
map.remove(session.getId());
}
}
//获取map的个数
public synchronized String getSize() {
int size = map.size();
return String.valueOf(size);
}
}
package com.jbossjf.bootproject.common.WebSecurity;
import com.jbossjf.bootproject.model.UserInfo;
import com.jbossjf.bootproject.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
@Component()
public class SessionListener implements HttpSessionListener {
@Autowired
UserInfoService userInfoService;
@PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
public void init() {
serverIOT = this;
// serverIOT.userInfoService = this.userInfoService;
// 初使化时将已静态化的easybandDateService实例化
}
public static SessionListener serverIOT;
private MySessionContext context = MySessionContext.getSessionContext();
@Override
public void sessionCreated(HttpSessionEvent e) {
// e.getSession().setMaxInactiveInterval(5); //5秒调用sessionDestroyed
//context.addSession(e.getSession());
}
@Override
public void sessionDestroyed(HttpSessionEvent e) {
try {
context.delSession(e.getSession());
}catch (Exception ex){}
// System.out.println("移除了sessionid是"+e.getSession().getId()); 删除map中的key value
try {
UserInfo tempUser = (UserInfo) e.getSession().getAttribute("USER_INFO");
if (tempUser != null) {
//获取service
// UserInfoService genericService =(UserInfoService) getObjectFromApplication(e.getSession().getServletContext(),"userInfoRepository");
//获取用户的sessionId和用户在线状态
// UserInfo tempUser1 = serverIOT.userInfoService.GetBean(tempUser.getId());
//如果用户在线且sessionId和e.getSession().getId()相同说明下线,不是更替。
//则修改用户的在线状态和session设置null。
if (tempUser.getOnlinestatus().equals("TRUE") && tempUser.getSessionid().contains(e.getSession().getId())) {
if(tempUser.getSessionid().contains(","+e.getSession().getId()))
{
String temp_session = tempUser.getSessionid().replace(","+e.getSession().getId(),"");
tempUser.setSessionid(temp_session);
}
if(tempUser.getSessionid().contains(e.getSession().getId()))
{
String temp_session = tempUser.getSessionid().replace(e.getSession().getId(),"");
tempUser.setSessionid(temp_session);
}
tempUser.setOnlinestatus("FLASE");
// tempUser.setSessionid(null);
serverIOT.userInfoService.UpdateBean(tempUser);
//如果直接关闭浏览器的话可以直接杀死session 不用写 会直接杀死session的
// e.getSession().invalidate();
// System.out.println("session杀死了");
}
}
}catch (Exception ex)
{
System.out.print(ex.getMessage());
}
}
private Object getObjectFromApplication(ServletContext servletContext, String beanName){
//通过WebApplicationContextUtils 得到Spring容器的实例。
ApplicationContext application= WebApplicationContextUtils.getWebApplicationContext(servletContext);
//返回Bean的实例。
return application.getBean(beanName);
}
}
@ResponseBody
@RequestMapping(value = "/API/LoginUserInfo", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public Map<String, Object> LoginUserInfo(@RequestBody JSONObject jsonParam) {
Map<String, Object> map = new HashMap<>();
try {
String phone = jsonParam.getString("phone");
String password = jsonParam.getString("password");
if (phone == null && phone.equals("")) {
map.put("status", "fail");
return map;
}
if (password == null && password.equals("")) {
map.put("status", "fail");
return map;
}
// Session ses = new Session();
List<UserInfo> userInfoList = userService.findByNamePhonePassword(phone, password);
if (userInfoList.size() > 0) {
if (userInfoList.get(0).getRole().getName().equals("管理员")) {
map.put("token", "admin");
} else {
map.put("token", "editor");
}
HttpSession session = request.getSession();
UserInfo tempuser = userInfoList.get(0);
// if((tempuser.getOnlinestatus() != null && tempuser.getOnlinestatus().equals("TRUE")) && tempuser.getSessionid() != null) {
// HttpSession oldSession = context.getSession(tempuser.getSessionid());
// if(oldSession != null){
// oldSession.invalidate();
// context.delSession(oldSession);
// }
// }
System.out.print(session.getId()+"------------"+tempuser.getSessionid()+"/r/n");
// System.out.print("Context_Get"+context.getSession(session.getId()).getId()); context.getSession(tempuser.getSessionid())!=null)
if ((tempuser.getOnlinestatus() != null && tempuser.getOnlinestatus().equals("TRUE")) && (tempuser.getSessionid() != null
&& tempuser.getSessionid().contains(session.getId()))
) {
// String[] session_array = userInfoList.get(0).getSessionid().split(",");
map.put("token", session.getId());
map.put("status", "success");
return map;
} else {
if (tempuser.getSessionid() == null || tempuser.getSessionid().isEmpty()) {
tempuser.setOnlinestatus("TRUE");
tempuser.setSessionid(session.getId());
//修改用户对象的状态和sessionid置为空
userService.UpdateBean(tempuser);
session.setAttribute("USER_INFO", tempuser);
context.addSession(session);
map.put("token", tempuser.getId());
map.put("status", "success");
return map;
}
if (tempuser.getSessionid() != null && !tempuser.getSessionid().isEmpty()) {
String[] session_array = tempuser.getSessionid().split(",");
if (session_array.length >= 5) {
map.put("status", "fail");
return map;
} else {
String temp_session = "";
for (int i = 0; i < session_array.length; i++) {
if (i == 0) {
temp_session = session_array[i];
} else {
temp_session = temp_session + "," + session_array[i];
}
}
temp_session = temp_session + "," + session.getId();
tempuser.setOnlinestatus("TRUE");
tempuser.setSessionid(temp_session);
//修改用户对象的状态和sessionid置为空
userService.UpdateBean(tempuser);
session.setAttribute("USER_INFO", tempuser);
context.addSession(session);
map.put("token", tempuser.getId());
map.put("status", "success");
return map;
}
}
}
}
} catch (Exception e) {
logger.info(e.getStackTrace().toString());
}
map.put("status", "fail");
return map;
}