在Struts2中提供了更为简单的参数请求与接收方法,可以直接在Action中定义属性;Struts2通过反射机制将参数反射到属性的set方法上实现参数的传递;
GET方式传送参数
<struts> <constant name="struts.118n.encoding" value="UTF-8"></constant> <constant name="struts.action.extension" value="do"></constant> <package name="helloPackage" namespace="/hello" extends="struts-default"> <action name="hello_*" class="com.actions.HelloAction" method="{1}"> <result name="message">/WEB-INF/message.jsp</result> </action> </package> </struts>
public class HelloAction { private Integer id; private String name; public HelloAction(){} public String sayHello(){ return "message"; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
message页面:
<body> id=${id } <br> name=${name } </body>
请求路径:http://localhost:9000/Struts3/hello/hello_sayHello.do?id=888&name=tom
POST方式传递参数
<form action="http://localhost:9000/Struts3/hello/hello_sayHello.do" method="post"> <table> <tr> <td>id:</td> <td><input type="text" name="id" /> </td> </tr> <tr> <td>name:</td> <td><input type="text" name="name" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="提交"/></td> </tr> </table> </form>
Action 代码同上;
复合方式传递参数
可能要传递的参数是一个对象,Struts2同样也支持自定义实体的进行参数传递;
<form action="http://localhost:9000/Struts3/hello/hello_sayHello.do" method="post"> <table> <tr> <td>id:</td> <td><input type="text" name="hello.id" /> </td> </tr> <tr> <td>name:</td> <td><input type="text" name="hello.name" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="提交"/></td> </tr> </table> </form>
实体:
public class HelloEntity { // 使用复合方式传递参数,必须添加实体的无参构造函数 public HelloEntity(){ } private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }action:
public class HelloAction { private HelloEntity hello; public HelloAction(){} public String sayHello(){ return "message"; } public HelloEntity getHello() { return hello; } public void setHello(HelloEntity hello) { this.hello = hello; } }
message.jsp:
<body> id=${hello.id } <br> name=${hello.name } </body>