Introduction
Your Struts 2 application may need to access the HTTP session object. Struts 2 provides an interface, SessionAware, that your Action class should implement to obtain a reference to the HTTP session object.
...
Code Block |
---|
| java |
---|
| java |
---|
title | HelloWorldAction.java setSession Method |
---|
|
private Map<String, Object> userSession ;
public void setSession(Map<String, Object) session) {
userSession = session ;
}
|
...
Code Block |
---|
| java |
---|
| java |
---|
title | HelloWorldAction.java increaseHelloCount Method |
---|
|
private void increaseHelloCount() {
Integer helloCount = (Integer) userSession.get(HELLO_COUNT);
if (helloCount == null ) {
helloCount = 1;
} else {
helloCount++;
}
userSession.put(HELLO_COUNT, helloCount);
}
|
...
Struts 2 provides an easy way to get an object stored in the HTTP session from within the view page. In the example application is HelloWorld.jsp with this markup:
Code Block |
---|
| XMLhtmlXML |
---|
| html |
---|
title | HelloWorld.jsp Get helloCount Value From HTTP Session |
---|
|
<p>I've said hello to you <s:property value="#session.helloCount" /> times!</p>
|
...
Code Block |
---|
| java |
---|
| java |
---|
title | HelloWorldAction.java acceptableParameterName Method |
---|
|
public boolean acceptableParameterName(String parameterName) {
boolean allowedParameterName = true ;
if ( parameterName.contains("session") || parameterName.contains("request") ) {
allowedParameterName = false ;
}
return allowedParameterName;
}
|
...
Instead of having each action that implements SessionAware also implement the ParameterNameAware interface you can tell the params interceptor to exclude specific request attributes for all actions in a package. In struts.xml configure the struts-default set of interceptors as follows:
Code Block |
---|
| XMLxmlXML |
---|
| xml |
---|
title | struts.xml configure params interceptor |
---|
|
<package name="basicstruts2" extends="struts-default">
<interceptors>
<interceptor-stack name="appDefault">
<interceptor-ref name="defaultStack">
<param name="exception.logEnabled">true</param>
<param name="exception.logLevel">ERROR</param>
<param name="params.excludeParams">dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,parameters\...*</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="appDefault" />
|
...