创建第一个Action
创建第一个Action
1.
普通的java类 编写public String execute(){}方法
实现Action接口 重写execute()方法
继承ActionSupport类 重写execute()方法
2、案例:
创建Struts2的Action输出"hello Struts"
实现思路:
继承ActionSupport类 实现execute()方法
修改struts.xml的<action>添加class属性
3.struts.xml
<struts>
<!-- ynamicMethodInvocation动态方法 -->
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<!--struts.devMod开发模式 -->
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="hello" method="execute" class="">
<!-- 默认success返回 -->
<result name="success">hello.jsp</result>
</action>
<!-- 自己创建的execute -->
<action name="hello_javabean" class="cn.bdqn.web.action.HelloAction">
<result>hello.jsp</result>
</action>
<!-- 通过接口实现execute -->
<action name="hello_iterface" class="cn.bdqn.web.action.Hello2Action">
<result>hello.jsp</result>
</action>
<!-- 通过继承实现execute <result name="success">hello.jsp</result> 默认是success 如果想改返回值就改name-->
<action name="hello_extends" class="cn.bdqn.web.action.Hello2Action">
<result name="success">hello.jsp</result>
</action>
<action name="login" class="cn.bdqn.web.action.LoginAction">
<result name="fail">loginSuccess.jsp</result>
<result name="success">loginSuccess.jsp</result>
</action>
</struts>
4.Hello2Action.java
import com.opensymphony.xwork2.Action;
public class Hello2Action implements Action {
@Override
public String execute() throws Exception {
return "success";
}
}
访问http://localhost:8080/qnfang/hello_iterface
5.Hello3Action.java
public class Hello3Action extends ActionSupport{
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return super.execute();
}
}
6LoginAction.java(一个登录的jsp页面提交struts配置的login)
package cn.bdqn.web.action;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private String loginName;
private String passwd;
// 必须得有set/get因为struts会通过反射去赋值
@Override
public String execute() throws Exception {
System.out.println(loginName + "" + passwd);
if ("admin".equals(loginName)) {
return SUCCESS;
} else {
return "fail";
}
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}