When your Action class needs to access the HTTP session object implement the SessionAware interface and override the setSession method.
ps: 实现 SessionAware 的 setSession 方法得到 session,但是这里的session是Map型的,struts2框架会做Map 和HttpSession之间的转换。
public void setSession(Map<String, Object) session) { userSession = session ; }
Be sure to also implement the ParameterNameAware interface and override the acceptableParameterName method to mitigate a potential security vulnerability .
PS: 为了确保使用session的安全性,我们最好再实现ParameterNameAware接口的acceptableParameterName方法,具体如下 。 当参数的名字里包含session,request该方法会返回false,告诉struts2 framework 忽略这些参数。
public boolean acceptableParameterName(String parameterName) { boolean allowedParameterName = true ; if ( parameterName.contains("session") || parameterName.contains("request") ) { allowedParameterName = false ; } return allowedParameterName; }
If you have multiple actions that implement SessionAware then consider modifying the params interceptor's excludeParams value as part of your Struts 2 package setup。
PS: 如果你包里许多的action里实现SessionAware 可以如下做统一做安全保证配置,就可以不用再去实现ParameterNameAware 接口的acceptableParameterName 方法了。
<package name="basicstruts2" extends="struts-default"> <interceptors> <interceptor-stack name="appDefault"> <interceptor-ref name="defaultStack"> <param name="params.excludeParams">dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,parameters\...*</param> </interceptor-ref> </interceptor-stack> </interceptors> <default-interceptor-ref name="appDefault" />