Structs2 Action使用
Action中获取HttpServletResponse ,HttpServletRequest,HttpSession等Servlet相关变量有两种方式;
1、非Ioc方式
要获得上述对象,关键Struts 2.0中com.opensymphony.xwork2.ActionContext类。我们可以通过它的静态方法getContext()获取当前Action的上下文对象。 另外,org.apache.struts2.ServletActionContext作为辅助类(Helper Class),可以帮助您快捷地获得这几个对象。
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session = request.getSession();
2、Ioc 方式
只要Action类实现SessionAware, ServletRequestAware, ServletResponseAware这几个接口,相应的变量会自动注入
调用action的方法
我们知道,当客户端请求一个action时,会生成一个Action 对应的变量,并执行execute方法,但这是需要跟据配置来确定的
<
action
name
="HelloWorld"
class
="tutorial.HelloWorld"
>
< result > /HelloWorld.jsp </ result >
</ action >
要想改变默认执行的方法,需要在action节点加上要调用的方法名,如:
< result > /HelloWorld.jsp </ result >
</ action >
<
action
name
="AliasHelloWorld"
class
="tutorial.HelloWorld"
method
="aliasAction"
>
< result > /HelloWorld.jsp </ result >
</ action >
< result > /HelloWorld.jsp </ result >
</ action >
如果要实现类似于Structs1.x那样的DispatchAction方式的调用,配置例子如下:
<
action
name
="login!*"
method
="{1}"
class
="one.LoginAction"
>
< result name ="success" type ="dispatcher" >
< param name ="location" > /main.jsp </ param >
</ result >
< result name ="input" > /login.jsp </ result >
< result name ="loginfail" type ="dispatcher" >
< param name ="location" > /login.jsp </ param >
</ result >
</ action >
如上配置,如果只调用login.action,会执行默认方法execute()。
< result name ="success" type ="dispatcher" >
< param name ="location" > /main.jsp </ param >
</ result >
< result name ="input" > /login.jsp </ result >
< result name ="loginfail" type ="dispatcher" >
< param name ="location" > /login.jsp </ param >
</ result >
</ action >
Structs 2文件上传例子
package
one;
import java.io.File;
import java.text. * ;
import java.util. * ;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport implements ServletContextAware{
private File doc;
private String docContentType;
private String docFileName;
private ServletContext context;
public String execute() throws Exception{
String target = context.getRealPath( " /upload " );
String file = generateFileName(docFileName);
File dfile = new File(target,file);
FileUtils.copyFile(doc,dfile);
return this .SUCCESS;
}
private String generateFileName(String fileName) {
DateFormat format = new SimpleDateFormat( " yyMMddHHmmss " );
String formatDate = format.format( new Date());
int random = new Random().nextInt( 10000 );
int position = fileName.lastIndexOf( " . " );
String extension = fileName.substring(position);
return formatDate + random + extension;
}
public void setServletContext(ServletContext context) {
// TODO Auto-generated method stub
this .context = context;
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this .context = context;
}
public File getDoc() {
return doc;
}
public void setDoc(File doc) {
this .doc = doc;
}
public String getDocContentType() {
return docContentType;
}
public void setDocContentType(String docContentType) {
this .docContentType = docContentType;
}
public String getDocFileName() {
return docFileName;
}
public void setDocFileName(String docFileName) {
this .docFileName = docFileName;
}
}
import java.io.File;
import java.text. * ;
import java.util. * ;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport implements ServletContextAware{
private File doc;
private String docContentType;
private String docFileName;
private ServletContext context;
public String execute() throws Exception{
String target = context.getRealPath( " /upload " );
String file = generateFileName(docFileName);
File dfile = new File(target,file);
FileUtils.copyFile(doc,dfile);
return this .SUCCESS;
}
private String generateFileName(String fileName) {
DateFormat format = new SimpleDateFormat( " yyMMddHHmmss " );
String formatDate = format.format( new Date());
int random = new Random().nextInt( 10000 );
int position = fileName.lastIndexOf( " . " );
String extension = fileName.substring(position);
return formatDate + random + extension;
}
public void setServletContext(ServletContext context) {
// TODO Auto-generated method stub
this .context = context;
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this .context = context;
}
public File getDoc() {
return doc;
}
public void setDoc(File doc) {
this .doc = doc;
}
public String getDocContentType() {
return docContentType;
}
public void setDocContentType(String docContentType) {
this .docContentType = docContentType;
}
public String getDocFileName() {
return docFileName;
}
public void setDocFileName(String docFileName) {
this .docFileName = docFileName;
}
}
1:在action中定义的变量,在jsp页面中显示用:<s:property value="变量名" />
2:在页面中实现自动增加的序号用iterator的statuts的index属性 eg:
<s:iterator value="#request.inOutAccountList" id="data" status="listStat">
<s:property value="#listStat.index+1"/>
</s:iterator>
3:在action类中取得request和session对象的方法
Map session = ActionContext.getContext().getSession();
HttpServletRequest request = ServletActionContext.getRequest ();
设置它们的值的方法
session.put("operation", "add");
request.setAttribute("name", name);
页面中取得它们的值:
<s:property value="#session.operation"/>
<s:property value="#request.name"/>
4:页面中奇偶行样式不一样的控制方法:
<tr class="<s:if test='#listStat.odd == true '>tableStyle-tr1</s:if><s:else>tableStyle-tr2</s:else>" >
5:单选框和复选框的使用方法
1):可以设置默认选中值,注意list的值的设置,通过这种方式使key和value不一样,这种方法比较常用(checkboxlist or radio)
<s:radio name="uncarInsPolicy.policyStateCode"
list="#{'5':'通过' , '2':'不通过'}"
listKey="key"
listValue="value"
value='5'
/>
2):这里的key和value的值是一样的(checkboxlist or radio)
<s:checkboxlist
list="{'Red', 'Blue', 'Green'}"
name="favoriteColor"/>
6:struts2 中的标签会生成类似由<tr><td></td></tr>构成的字串(具体什么标签生成什么,可以查看生成后的页面的源代码)如果不限制这些多余代码的生成,页面将变得无法控制,所以一般我们是不希望它生成多余的代码的,具体的设置方法如果,在struts.xml中统一配置
<constant name="struts.ui.theme" value="simple"/>加上该句即可
也可以通过在页面中将tag的theme属性设为"simple"取消其默认的表格布局
不过最好是:自定义一个theme,并将其设为默认应用到整个站点,如此一来就可以得到统一的站点风格
7:jsp页面中格式化日期的方法
<s:date name="unCarInsModificationInfo.createTime" format="yyyy-MM-dd" nice="false"/>这样就可以将日期格式化为yyyy-MM-dd的形式
8:默认情况下,当请求action发生时,Struts运行时(Runtime)根据struts.xml里的Action映射集(Mapping),实例化action对应的类,并调用其execute方法。当然,我们可以通过以下两种方法改变这种默认调用
1)在classes/sturts.xml中新建Action,并指明其调用的方法
比如想调用action类中的
public String aliasAction() {
message ="自定义Action调用方法";
return SUCCESS;
}
则在classes/sturts.xml中加入下面代码:
<action name="AliasHelloWorld" class="tutorial.HelloWorld" method="aliasAction">
<result>/HelloWorld.jsp</result>
</action>
既可用action名调用该方法了
2)(比较常用)
访问Action时,在Action名后加上“!xxx”(xxx为方法名)。
9:Struts 2.0有两个配置文件,struts.xml和struts.properties都是放在WEB-INF/classes/下。
struts.xml用于应用程序相关的配置
struts.properties用于Struts 2.0的运行时(Runtime)的配置
10:在action类中取得web下某一文件夹物理路径(绝对路径)的方法
filePath = ServletActionContext.getServletContext().getRealPath("/upLoadFiles")
11:要想返回的页面不是一个直接JSP页面而是要先通过返回action中的方法读取相应的数据再返回到jsp页面,有两种方法
1)在struts.xml中这么设置
<result name="list" type="redirect-action">sysmanage/UserBaseInfoAction!findUserBaseInfo.action</result>
2)在action中返回时直接调用这个方法即可
return findList();
12:设置checkboxlist中默认值的方法
<s:checkboxlist name="skills1"
="Skills 1"
list="{ 'Java', '.Net', 'RoR', 'PHP' }"
value="{ 'Java', '.Net' }" />
<s:checkboxlist name="skills2"
label="Skills 2"
list="#{ 1:'Java', 2: '.Net', 3: 'RoR', 4: 'PHP' }"
listKey="key"
listValue="value"
value="{ 1, 2, 3 }"/>
13:二级级连下拉框
<s:set name="foobar"
value="#{'Java': {'Spring', 'Hibernate', 'Struts 2'}, '.Net': {'Linq', ' ASP.NET 2.0'}, 'Database': {'Oracle', 'SQL Server', 'DB2', 'MySQL'}}" />
<s:doubleselect list="#foobar.keySet()"
doubleName="technology"
doubleList="#foobar[top]"
label="Technology" />