在spring mvc中删除url重写中的jsessionid

时间:2011-03-11 18:03:59

标签: java spring session spring-mvc jsessionid

我正在使用spring MVC并且在jsessionid中遇到问题,我发现如果在浏览器中没有启用cookie,则会在URL中注入jsessionid,生成类似的URL:

http://localhost/categories;jsessionid=Bsls4aQFXA5RUDcmZKV5iw?cid=13001

实际上浏览器没有问题,但是当Google抓取我的网站时,Google抓取工具似乎没有Cookie :),他们会将该网站的网址存储在该表单中,而我的网站会显示在搜索结果中,其网址就像那些包含jsessionid。

实际上它运行没有任何问题,但我更喜欢在没有jsessionid的情况下将网址显示在Google搜索结果中。

任何帮助?

5 个答案:

答案 0 :(得分:19)

要点:只要用户不登录或执行POST操作,就不要让您的应用创建会话。请勿致电request.getSession()request.getSession(true)。不要为未登录的用户创建或管理会话范围的bean。确保您使用的框架不会不必要地创建会话,而不是您要这样做。

如果由于应用程序的设计方式或由于所使用的(MVC)框架的限制/错误而确实不可能,那么您最好的选择是将Googlebot请求重定向到没有JSESSIONID标识符。您可以使用Tuckey's URL rewrite filter(例如,Apache HTTPD着名的mod_rewrite的Java变体)。以下是configuration examples page的相关摘录。

  

为来自googlebot的请求隐藏jsessionid。

     
<outbound-rule>
     <name>Strip URL Session ID's</name>
     <note>
         Strip ;jsession=XXX from urls passed through response.encodeURL().
         The characters ? and # are the only things we can use to find out where the jsessionid ends.
         The expression in 'from' below contains three capture groups, the last two being optional.
             1, everything before ;jesessionid
             2, everything after ;jesessionid=XXX starting with a ? (to get the query string) up to #
             3, everything ;jesessionid=XXX and optionally ?XXX starting with a # (to get the target)
         eg,
         from index.jsp;jsessionid=sss?qqq to index.jsp?qqq
         from index.jsp;jsessionid=sss?qqq#ttt to index.jsp?qqq#ttt
         from index.jsp;jsessionid=asdasdasdsadsadasd#dfds - index.jsp#dfds
         from u.jsp;jsessionid=wert.hg - u.jsp
         from /;jsessionid=tyu - /
     </note>
     <condition name="user-agent">googlebot</condition>
     <from>^(.*?)(?:\;jsessionid=[^\?#]*)?(\?[^#]*)?(#.*)?$</from>
     <to>$1$2$3</to>
 </outbound-rule>

答案 1 :(得分:11)

Spring可以配置为不这样做: Why jsessionid is appended to each url?

可以将Web应用程序配置为阻止它: http://randomcoder.org/articles/jsessionid-considered-harmful

答案 2 :(得分:1)

如果您不使用Spring http标签 转到定义Spring过滤器链的applicationFilterChain bean 通常情况下,您将有一个名为httpSessionContextIntegrationFilter的过滤器或非常接近的过滤器,它基于类org.springframework.security.web.context.HttpSessionContextIntegrationFilter或从其继承。
添加属性:

<property name="securityContextRepository" ref="securityContextRepositoryNoJSession"/>

添加bean:

<bean id="securityContextRepositoryNoJSession" class="org.springframework.security.web.context.HttpSessionSecurityContextRepository">
    <property name="disableUrlRewriting" value="true"/>
</bean>


这应该等同于将disable-url-rewriting设置为true

答案 3 :(得分:0)

我会插入一个过滤器,如果它检测到机器人(如googlebot)使用自定义的HttpServletResponse,它会覆盖encodeUrl方法以简单地返回原始URL。如果过滤器没有检测到机器人,它只会让链继续,这应该让url编码等按照默认值继续。

答案 4 :(得分:0)

在您的网址中删除jsessionid的最简单方法是更改​​为登录页面上的标记,其中调用j_spring_security_check

<c:url var="authUrl" value="/static/j_spring_security_check" />
    <form action="${authUrl}" method="post">