刚学Struts2 时 大家可能遇到过很多问题,这里我讲一下Action 接收参数的三种方法,我曾经在这上面摔过一回。所以要警醒一下自己。。。。。
第一种:Action里声明属性,样例:accountName,password,message,并且要写get(),set() 方法。。
public class MessageAction extends ActionSupport {
// 接受客户端两个文本框的值
private String accountName;
private String password;
// 将服务器端处理结果返回给客户端
private String message;
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Action(value = "messageAction", results = {
@Result(name = "success", type = "dispatcher", location = "/signin.jsp"),
@Result(name = "error", type = "dispatcher", location = "/signin.jsp") })
//上面是注解,就是相当于在struts.xml里配置Action
<!--
<action name="messageAction" class="org.orclwdp.jwt.action.MessageAction" >
<result name="success" type="dispatcher" >/signin.jsp</result>
<result name="error" type="dispatcher">/signin.jsp</result>
</action>
-->
public String execute() {
if ("admin".equals(this.accountName)) {
if ("111111".equals(this.password)) {
message = "登录成功";
return SUCCESS;
} else {
message = "密码错误";
return ERROR;
}
} else {
message = "帐号不存在";
return ERROR;
}
}
}
第二种:声明一个对象,当然这个对象是已经有了的,即accountName,password,message。当然这些需要用到的参数属性是这个对象有的。声明对象要也要写get(),set() 方法。。但在前台页面里form表单中input输入框name属性:
<input class="m-wrap" id="editAccountName" name="userInfo.accountName" type="text" value="" placeholder="请输入用户名" />
public class MessageAction extends ActionSupport {
private UserInfo userInfo = new UserInfo();
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
@Action(value = "messageAction", results = {
@Result(name = "success", type = "dispatcher", location = "/signin.jsp"),
@Result(name = "error", type = "dispatcher", location = "/signin.jsp") })
public String execute() {
if ("admin".equals(userInfo.getAccountName()) {
if ("111111".equals(userInfo.getPassword()) {
message = "登录成功";
return SUCCESS;
} else {
message = "密码错误";
return ERROR;
}
} else {
message = "帐号不存在";
return ERROR;
}
}
}
第三种:实现ModelDriven<UserInfo>接口,UserInfo不需要写get(),set() 方法。实现 ModelDriven<UserInfo>
public class HelloAction extends ActionSupport implements ModelDriven<UserInfo> {
private UserInfo userInfo=new UserInfo();
@Override
public UserInfo getModel() {
return userInfo;
}
..................同上
}