Blueherb In solitude, where we are least alone 王佳鑫

前后端分离,session登录实例,jquery版本必须大于1.5,否则withCredentials不起作用

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"><head>
<meta charset="UTF-8"><title>Title</title><script type="text/javascript"src="http://code.jquery.com/jquery-2.1.4.min.js"></script><script>
` function checkForm() { $.ajax({type :"POST",
url :"http://localhost:18087/DictEvent/login",
dataType :"json",
contentType:"application/json;charset=utf-8",
data : JSON.stringify({username:1}),
xhrFields: {withCredentials: true},
crossDomain: true,
success :function(test) {

                console.log(test);
                alert("登录成功")
                $(window).attr('location', './index.html');
            },
        });
    }

function checkForm1() {

        $.ajax({
            type :"POST",
            url :"http://localhost:18087/DictEvent/getOrder",
            dataType :"json",
            async:true,
            xhrFields: {
                withCredentials: true
				
            },
            crossDomain: true,
            data : {username:1},
            success :function(test) {
                console.log(test);
				
            },error: function (XMLHttpRequest, textStatus, errorThrown) {
                // 状态码
                console.log(XMLHttpRequest.response);
                alert(XMLHttpRequest.response)
                console.log(textStatus);
                $(window).attr('location', './login.html');
            }
        });
    }

</script>
</head>
<body>
<div id="change_margin_1">
<input class="user" type="text" name="user" placeholder="请输入用户名" >
</div>
<p id="remind_1"></p>
<div id="change_margin_2">
<input class="password" type="password" name="password" placeholder="请输入密码" >
</div>
<div><input type="submit" value="注册" onclick="checkForm()"></div>
<div><input type="submit" value="查看订单" onclick="checkForm1()"></div>
</body>
</html>

跨域Filter
@Component
public class CORSFilter implements Filter {

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
    HttpServletRequest request1 = servletRequestAttributes.getRequest();
    String Session = request1.getHeader("users");
    System.out.println("Session: " +Session);

    String origin = "*";
    if(req.getHeader("Origin")!=null){
        origin = req.getHeader("Origin");
    }

    // 允许http://www.xxx.com域(自行设置,这里只做示例)发起跨域请求
    res.setHeader("Access-Control-Allow-Origin", origin);
    // 允许跨域请求包含content-type
    res.setHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN,Access-Token,X-Requested-With,token,x-auth-token");

// res.setHeader("Access-Control-Allow-Origin", request2.getHeader("Origin"));
// 设置允许跨域请求的方法
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT,OPTIONS");
// 设置允许Cookie
res.setHeader("Access-Control-Allow-Credentials", "true");

    // 设置允许跨域请求的方法
    res.setHeader("Access-Control-Max-Age", "3600");

    res.setContentType("application/json");
    res.setCharacterEncoding("utf-8");
    if (req.getMethod().equals("OPTIONS")) {
        res.setStatus(HttpServletResponse.SC_OK);
    }
    else
    {
        chain.doFilter(request, response);
    }

}

@Override
public void destroy() {
}

@Override
public void init(FilterConfig filterConfig) throws ServletException {
}

}

session拦截器
public class MyLoginInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {

    //首页路径以及登录放行
    if ("/index".equals(arg0.getRequestURI()) || "/login".equals(arg0.getRequestURI())) {
        return true;}
    //重定向------前台实现
    HttpSession session = arg0.getSession();
    arg0.getServletContext().log("sessionID: " + session.getId());
    Object object = session.getAttribute("users");
    if (null == object) {
        arg1.getWriter().write("Please Login In");
        return false;}
    return true;
}

}

界面拦截器
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
//全局跨域配置
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") //添加映射路径
.allowedOrigins("") //放行哪些原始域
.allowedMethods("
") //放行哪些原始域(请求方式) //"GET","POST", "PUT", "DELETE", "OPTIONS"
.allowedHeaders("*") //放行哪些原始域(头部信息)
.allowCredentials(true) //是否发送Cookie信息
// .exposedHeaders("access-control-allow-headers",
// "access-control-allow-methods",
// "access-control-allow-origin",
// "access-control-max-age",
// "X-Frame-Options") //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
.maxAge(1800);
}

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

}

posted @ 2021-07-27 10:16  阿呆学习之路  阅读(200)  评论(0编辑  收藏  举报