首先我們來看一個簡單的調用:
1、在web.xml中配置攔截器StrutsPrepareAndExecuteFilter。StrutsPrepareAndExecuteFilter實現了filter接口,在執行action之前,利用filter做一些操作。
~~~
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
~~~
2、提供Struts2的配置文件struts.xml
~~~
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="Struts2_006" extends="struts-default" >
<action name="user" class="com.struts2.UserAction">
<result>/add_success.jsp</result>
</action>
</package>
</struts>
~~~
注:<result>標簽的默認值是success,此處省略。
3、頁面顯示部分。
index.jsp頁面,轉向到action中,調用action中的方法。
~~~
<body>
<a href="user.action">調用</a>
</body>
~~~
調用完后,跳轉到成功頁面,并顯示message中的消息。
~~~
<body>
?我的操作:${message} <br>
</body>
~~~
? ? ? ?4、編寫Action類 UserAction。
~~~
public class UserAction extends ActionSupport{
//消息字符串,用來顯示調用結果
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
/***
* execute方法
*/
public String execute() throws Exception{
message="執行execute方法";
return SUCCESS;
}
}
~~~
注意:這里我們讓UserAction繼承自ActionSupport類,從源碼中可以看到ActionSupport類實現了Action接口。在ActionSupport類中也處理了execute()方法,但他并沒有做什么操作,只是返回SUCCESS。因而,如果我們在UserAction中不寫execute方法,也不會報錯。
~~~
public class ActionSupport implements Action, Validateable, ValidationAware, TextProvider, LocaleProvider, Serializable {
protected static Logger LOG = LoggerFactory.getLogger(ActionSupport.class);
private final ValidationAwareSupport validationAware = new ValidationAwareSupport();
private transient TextProvider textProvider;
private Container container;
/**
* A default implementation that does nothing an returns "success".
* <p/>
* Subclasses should override this method to provide their business logic.
* <p/>
* See also {@link com.opensymphony.xwork2.Action#execute()}.
*
* @return returns {@link #SUCCESS}
* @throws Exception can be thrown by subclasses.
*/
public String execute() throws Exception {
return SUCCESS;
}
}
~~~

如果在UserAction中不寫execute方法,message中沒有值。

這篇博客介紹了Struts2的簡單的方法調用,下篇博客將繼續介紹,當action中有多個方法時,應該如何實現調用。