跨域获取sessionId

sessionId所属的站点暴露接口(本机域localhost):

@GetMapping(value = "/mySessionId")
public void mySessionId(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String requestedSessionId = request.getRequestedSessionId();
    response.addHeader("content-type","text/javascript");
    try(PrintWriter writer = response.getWriter()) {
        writer.write("var mySessionId = '"+requestedSessionId+"';");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

其它任意站点访问该接口( 菜鸟教程所在域www.runoob.com):

  • 关键 JSONP 跨域特性

  • 使用JQuery的getScript函数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.getScript("http://localhost:8080/mySessionId",function(){alert(mySessionId)});
    });
});
</script>
</head>
<body>

<button>使用 Ajax 来获取JavaScript脚本并执行</button>

</body>
</html>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。