Struts2中Session的使用
在Struts2里,如果需要在Action中使用session,可以通過下面兩種方式得到 ??
1.通過ActionContext class中的方法getSession得到 ??
2.Action實(shí)現(xiàn)org.apache.struts2.interceptor.SessionAware接口的方式來對session進(jìn)行操作 ??
下面先看一個(gè)采用第一種方式,在action中得到session的例子 ??
package s2.ex.action;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class SessionTestAction extends ActionSupport {
? ? public String execute() {
? ? ? ? ActionContext actionContext = ActionContext.getContext();
? ? ? ? Map session = actionContext.getSession();
? ? ? ? session.put("USER_NAME", "Test User");
? ? ? ? return SUCCESS;
? ? }
} ??
在這個(gè)例子中,通過ActionContext得到session,并往session里放置一個(gè)key為USER_NAME,值為Test User的內(nèi)容。
下面是一個(gè)實(shí)現(xiàn)org.apache.struts2.interceptor.SessionAware接口來對session操作的例子 ??
package s2.ex.action;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport; ?
public class SessionTest1Action extends ActionSupport implements SessionAware {
? ? private Map session;
? ? public void setSession(Map session) {
? ? ? ? this.session = session;
? ? }
? ? public String execute() {
? ? ? ? this.session.put("USER_NAME", "Test User 1");
? ? ? ? return SUCCESS;
? ? }
} ??
在這個(gè)例子中實(shí)現(xiàn)了接口SessionAware中的setSession方法。
上面兩種方式都可以得到session,能實(shí)現(xiàn)的功能都是一樣的。
這里推薦通過第二種方式來使用session,原因是便于做單體測試,用第二種方式,只需要構(gòu)造一個(gè)Map就可以對action class進(jìn)行單體測試了。
在一個(gè)項(xiàng)目中可能會有很多action都需要用到session,如果每個(gè)action都來實(shí)現(xiàn)org.apache.struts2.interceptor.SessionAware這個(gè)接口,可能會顯得比較麻煩,所以建議作一個(gè)抽象的BaseAction類來實(shí)現(xiàn)org.apache.struts2.interceptor.SessionAware接口,以后所有的action只要繼承這個(gè)BaseAction就可以了。
下面是一個(gè)如何在JSP中使用session的例子。 ??
<%@ page contentType="text/html; charset=UTF-8" %>
<%@page pageEncoding="utf-8" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Session Test</title>
</head>
<body>
? ? <h1><s:property value="#session.USER_NAME"/></h1>
</body>
</html> ?
? ? 一般在項(xiàng)目中往往會往session里放置一個(gè)Object,必如說user,user里有個(gè)boolean admin和String userName,如果user里存在isAdmin的方法,在jsp中可以通過<s:if test="#session.user.admin">來判斷用戶有沒有管理權(quán)限,通過<s:property value="#session.user.userName">或者來取得用戶名。Struts2中Session的使用好東西!!!
url來源 :http://blog.sina.com.cn/s/blog_5f7865cc0100dfff.html
轉(zhuǎn)載于:https://blog.51cto.com/3515030/1590014
總結(jié)
以上是生活随笔為你收集整理的Struts2中Session的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WEB IM
- 下一篇: Atom飞行手册翻译: 3.4 文本处理