下载Struts2导入lib中的jar包
工作流程介绍:
- 用户访问.action的路径
- 经过struts的过滤器
- 交给actionmanager然后返回给struts的派发器
- 派发给action代理然后生成一个action实例
- 实例经过拦截器然后生成一个result
- result可能是一个jsp页面 这里以JSP为例子
- 然后再经过一层拦截器筛选result
- 然后将结果返回给用户
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="demo" extends="struts-default" >
<action name="submit" class="action.MoreSubmitAction">
<result name="save" >
/result.jsp
</result>
<result name="print">
/result.jsp
</result>
</action>
</package>
</struts>
默认情况下 struts会调用动作类的execute方法,但是当我们要在一个动作类中处理不同的动作的时候---也就是用户请求不同的动作的时候,执行动作类中的不同的方法,我们可以在<action>标签中使用method方法指定要执行的动作类的方法名,并且为不同的动作起不同的名字
<?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="demo" extends="struts-default" >
<action name="test" class="action.MyAction">
</action>
<action name="my" class="action. MyAction" method="my">
</action>
</package>
</struts>
----------
package action;
import com.opensymphony.xwork2.ActionSupport;
public class MyAction extends ActionSupport
{
public String execute() throws Exception
{
// 处理test动作的代码
}
public String my() throws Exception
{
// 处理my动作的代码
}
}
在默认时,标签的type属性值是“dispatcher”(实际上就是转发,forward)。开发人员可以根据自己的需要指定不同的类型,如redirect、stream等。
全局Result:
<struts>
<package name="demo" extends="struts-default">
<global-results>
<result name="print">/result.jsp</result>
</global-results>
<action name="submit" class="action.MoreSubmitAction">
</action>
<action name="my" class="action.MoreSubmitAction" method="my">
</action>
</package>
</struts>
web.xml文件配置:
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>HelloStruts</display-name>
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>