Struts2请求方式有七种,主要介绍转发和重定向,其它有兴趣可以自行去了解。
转发和重定向又分为转发、重定向到jsp、和到action
下面就直接给出他们的配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="result" namespace="/" extends="struts-default">
<!-- 转发到jsp -->
<action name="Demo1Action" class="struts2.result.Demo1Action" method="execute">
<result name="success" type="dispatcher">/hello.jsp</result>
</action>
<!-- 重定向到jsp -->
<action name="Demo2Action" class="struts2.result.Demo2Action" method="execute">
<result name="success" type="redirect">/hello.jsp</result>
</action>
<!-- 转发到Action -->
<action name="Demo3Action" class="struts2.result.Demo3Action" method="execute">
<result name="success" type="chain">
<!-- action的名字 -->
<param name="actionName">Demo1Action</param>
<!-- action的命名空间 -->
<param name="namespace">/</param>
</result>
</action>
<!-- 重定向到Action -->
<action name="Demo4Action" class="struts2.result.Demo4Action" method="execute">
<result name="success" type="redirectAction">
<param name="actionName">Demo1Action</param>
<param name="namespace">/</param>
</result>
</action>
</package>
</struts>
下面再介绍一下重定向的时候携带参数的问题(直接给出代码)
package test;
import com.opensymphony.xwork2.ActionSupport;
public class DemoAction extends ActionSupport{
//必须要有get / set方法
private String name;
private Integer age;
@Override
public String execute() throws Exception {
//模仿从数据库取数据
name = "tom";
age = 18;
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
package test;
public class Demo1Action {
public String execute(){
return "success";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="hello" namespace="/" extends="struts-default">
<action name="DemoAction" class="test.DemoAction" method="execute">
<result name="success" type="redirectAction">
<param name="actionName">Demo1Action</param>
<param name="namespace">/</param>
<!--
如果添加的参数struts“看不懂”,就会作为参数附加重定向的路径后面
如果参数是动态的,可以使用${}包裹ognl表达式,动态取值
<param name="age">${age}</param>
-->
<param name="name">${name}</param>
<param name="age">${age}</param>
</result>
</action>
<action name="Demo1Action" class="test.Demo1Action" method="execute">
<result name="success" type="dispatcher">/hello.jsp</result>
</action>
</package>
</struts>