欢迎进入西安甲骨文培训机构 乘车路线| 关于我们| 设为首页| 加入收藏
logo 服务热线
1 2 3 3

新闻动态

联系我们

咨询报名电话:
029-85568080,029-85427081
传真:029-85568080
地址:陕西省西安市长安南路355号华银大厦(西北政法大学老校区对面西安银行南侧)

优秀学员

技术中心 当前位置:首页 > 新闻动态 > 技术中心

Struts2多个方法的访问

点击: 时间:2013-12-14
Struts1提供了DispatchAction,从而允许一个Action内包含多个请求处理方法。Struts2也提供了类似的功能。处理方式主要有以下三种方式:
1.1. 动态方法调用:
DMI:Dynamic Method Invocation 动态方法调用。
动态方法调用是指:表单元素的action不直接等于某个Action的名字,而是以如下形式来指定对应的动作名:
则用户的请求将提交到名为”userOpt”的Action实例,Action实例将调用名为”login”方法来处理请求。同时login方法的签名也是跟execute()一样,即为public String login() throws Exception。
注意:要使用动态方法调用,必须设置Struts2允许动态方法调用,通过设置struts.enable.DynamicMethodInvocation常量来完成,该常量属性的默认值是true。
1.1.1. 示例:
修改用户登录验证示例,多增加一个注册用户功能。
1. 修改Action类:
package org.qiujy.web.struts2.action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
publicclass LoginAction extends ActionSupport{
private String userName;
private String password;
private String msg; //结果信息属性
public String getMsg() {
returnmsg;
}
publicvoid setMsg(String msg) {
this.msg = msg;
}
public String getUserName() {
returnuserName;
}
publicvoid setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
returnpassword;
}
publicvoid setPassword(String password) {
this.password = password;
}
public String login() throws Exception{
if("test".equals(this.userName) && "test".equals(this.password)){
msg = "登录成功,欢迎" + this.userName;
//获取ActionContext实例,通过它来访问Servlet API
ActionContext context = ActionContext.getContext();
//看session中是否已经存放了用户名,如果存放了:说明已经登录了;
//否则说明是第一次登录成功
if(null != context.getSession().get("uName")){
msg = this.userName + ":你已经登录过了!!!";
}else{
context.getSession().put("uName", this.userName);
}
returnthis.SUCCESS;
}else{
msg = "登录失败,用户名或密码错";
returnthis.ERROR;
}
}
public String regist() throws Exception{
//将用户名,密码添加到数据库中
//...
msg = "注册成功。";
returnthis.SUCCESS;
}
}
2. struts.xml文件:没有什么变化,跟以前一样配置
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
/success.jsp
/error.jsp
3. 页面:
index.jsp