知识大全 struts2 session使用
Posted 知
篇首语:知识是心灵的活动。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 struts2 session使用相关的知识,希望对你有一定的参考价值。
在Struts 里 如果需要在Action中使用session 可以通过下面两种方式得到 通过ActionContext class中的方法getSession得到 Action实现 apache struts interceptor SessionAware接口的方式来对session进行操作 下面先看一个采用第一种方式 在action中得到session的例子 package s ex action; import java util Map; import opensymphony xwork ActionContext; import opensymphony xwork 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; 在这个例子中 通过ActionContext得到session 并往session里放置一个key为USER_NAME 值为Test User的内容 下面是一个实现 apache struts interceptor SessionAware接口来对session操作的例子 package s ex action; import java util Map; import apache struts interceptor SessionAware; import opensymphony xwork ActionSupport; public class SessionTest Action 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 ) return SUCCESS; 在这个例子中实现了接口SessionAware中的setSession方法 上面两种方式都可以得到session 能实现的功能都是一样的 这里推荐通过第二种方式来使用session 原因是便于做单体测试 用第二种方式 只需要构造一个Map就可以对action class进行单体测试了 在一个项目中可能会有很多action都需要用到session 如果每个action都来实现 apache struts interceptor SessionAware这个接口 可能会显得比较麻烦 所以建议作一个抽象的 BaseAction类来实现 apache struts interceptor SessionAware接口 以后所有的action只要继承这个BaseAction就可以了 下面是一个如何在JSP中使用session的例子 <%@ page contentType= text/; charset=UTF %> <%@page pageEncoding= utf %> <%@taglib prefix= s uri= /struts tags %> <> <head> <title>Session Test</title> </head> <body> <h ><s:property value= #session USER_NAME /></h > </body> </> 一般在项目中往往会往session里放置一个Object 必如说user user里有个boolean admin和String userName 如果user里存在isAdmin的方法 在jsp中可以通过<s:if test= #session user admin >来判断用户有没有管理权限 通过<s:property value= #session user userName >或者来取得用户名 cha138/Article/program/Java/ky/201311/27858相关参考