JSP 页面中 jsessioinid 出现在css和js路径中的怪现象

用 Spring mvc  开发一个小应用, 用传统的方法配置好了所有的东西, 但在运行时发现样式,js并没有找到,页面并不是真正想要的页面,打开生成的 HTML 页面查看代码居然发现在 js, css 的路径中出现了jsessionid. 真是怪事, 但最终还是能解决.

1. 简单的 页面
程序代码 程序代码

<html>
  <head>
  <title>Welcome!</title>

  <c:url var="assets" value="/resources/abc" />
  <link href="${assets}/css/style.min.css" rel="stylesheet">

  <script src="<c:url value="/resources/js/jquery.1.10.2.min.js" />">
  </script>

  </head>
  ...
</html>


2. Spring mvc 对资源文件的请求, 在 spring-servlet.xml 中配置
程序代码 程序代码

<mvc:resources mapping="/resources/**" location="/resources/" />


3. 生成的 HTML 页面, 居然带了 jsessonid
程序代码 程序代码

<html>
  <head>
  <title>Welcome!</title>

  <link href="/resources/simpliq;jsessionid=2957A...5C8DA/css/style.min.css"
    rel="stylesheet">

  <script src="/resources/js/jquery.1.10.2.min.js;jsessionid=2957A...5C8DA">
  </script>
  </head>
  ...
</html>


这显然不是我们想要的结果,但如何决绝呢,其实方法也很简单, 有两种方法:
1. 在jsp页面中关掉session : <%@page session="true"%>
2. 采用 ${pageContext.request.contextPath} ,代替 jstl c:url
程序代码 程序代码

<html>
  <head>
  <title>Welcome!</title>

  <link href="${pageContext.request.contextPath}/resources/css/style.min.css"
    rel="stylesheet">

  <script src="${pageContext.request.contextPath}/resources/js/jquery.1.10.2.min.js" />">
  </script>

  </head>
  ...
</html>


产生这种问题的原因: 来源于 stackoverflow:
程序代码 程序代码

SESSIONID cookie is created/sent when session is created. Session is created when your code calls request.getSession() or request.getSession(true) for the first time. If you just want get session, but not create it if it doesn't exists, use request.getSession(false) -- this will return you a session or null. In this case, new session is not created, and JSESSIONID cookie is not sent. (This also means that session isn't necessarily created on first request... you and your code is in control when the session is created)

Sessions are per-context:

SRV.7.3 Session Scope

HttpSession objects must be scoped at the application (or servlet context) level. The underlying mechanism, such as the cookie used to establish the session, can be the same for different contexts, but the object referenced, including the attributes in that object, must never be shared between contexts by the container.

(Servlet 2.4 specification)

Update: Every call to JSP page implicitly creates new session if there is no session yet. This can be turned off by session='false' page directive, in which case session variable is not available on JSP page at all.


除非申明,文章均为一号门原创,转载请注明本文地址,谢谢!
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: session
相关日志:
评论: 0 | 引用: 0 | 查看次数: -
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.