在struts2中如何定义全局session
时间: 2024-05-01 10:19:45 浏览: 112
在Struts2中,可以通过实现`org.apache.struts2.dispatcher.SessionMap`接口,创建一个自定义的session类,并在struts.xml文件中定义全局的session。
例如,我们可以创建一个名为`MySession`的session类,如下所示:
```
public class MySession implements SessionMap<String,Object> {
private Map<String, Object> session;
@Override
public void clear() {
session.clear();
}
@Override
public boolean containsKey(Object arg0) {
return session.containsKey(arg0);
}
@Override
public boolean containsValue(Object arg0) {
return session.containsValue(arg0);
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
return session.entrySet();
}
@Override
public Object get(Object arg0) {
return session.get(arg0);
}
@Override
public boolean isEmpty() {
return session.isEmpty();
}
@Override
public Set<String> keySet() {
return session.keySet();
}
@Override
public Object put(String arg0, Object arg1) {
return session.put(arg0, arg1);
}
@Override
public void putAll(Map<? extends String, ? extends Object> arg0) {
session.putAll(arg0);
}
@Override
public Object remove(Object arg0) {
return session.remove(arg0);
}
@Override
public int size() {
return session.size();
}
@Override
public Collection<Object> values() {
return session.values();
}
@Override
public void invalidate() {
session.clear();
}
@Override
public boolean isNew() {
return false;
}
@Override
public void setMaxInactiveInterval(int interval) {
// do nothing
}
@Override
public int getMaxInactiveInterval() {
return 0;
}
@Override
public long getCreationTime() {
return 0;
}
@Override
public String getId() {
return null;
}
@Override
public long getLastAccessedTime() {
return 0;
}
@Override
public void removeValue(String key) {
session.remove(key);
}
@Override
public void setAttribute(String key, Object value) {
session.put(key, value);
}
@Override
public void putValue(String key, Object value) {
session.put(key, value);
}
@Override
public void removeAttribute(String key) {
session.remove(key);
}
@Override
public Object getAttribute(String key) {
return session.get(key);
}
@Override
public Enumeration<String> getAttributeNames() {
return Collections.enumeration(session.keySet());
}
@Override
public String[] getValueNames() {
return session.keySet().toArray(new String[0]);
}
public void setSession(Map<String, Object> session) {
this.session = session;
}
}
```
然后在`struts.xml`文件中配置全局的session:
```
<constant name="struts.objectFactory" value="org.apache.struts2.spring.StrutsSpringObjectFactory" />
<constant name="struts.objectFactory.spring.autoWire.alwaysRespect" value="true" />
<constant name="struts.objectFactory.spring.useClassCache" value="true" />
<session-factory class="com.example.MySession">
<property name="session">
<map>
<entry key="key1">
<value>value1</value>
</entry>
<entry key="key2">
<value>value2</value>
</entry>
</map>
</property>
</session-factory>
```
这样就可以在整个应用程序中使用`MySession`类作为全局session了。
阅读全文