1.创建web项目,添加struts2支持的类库,在web.xml中配置struts2过滤器。
2.创建名为UserAction的Action对象,并在其中编写execute()方法,代码如下所示:
package com.wh.Demo;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport {
private String info;
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
@Override
public String execute() throws Exception {
if ("".equals(info)) {
return "error";
} else {
return "success";
}
}
}
3.在源文件夹中创建Struts.xml配置文件,在其中配置UserAction,代码如下:
<?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>
<!-- 动态方法调用 -->
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<package name="default" extends="struts-default" namespace="/user">
<action name="userAction" class="com.wh.Demo.UserAction">
<result name="success">success.jsp</result>
<result name="error">error.jsp</result>
</action>
</package>
</struts>
4.创建index.jsp主页面
<body>
<form id="form1" name="form1" method="post" action="userAction.action">
输入信息:<input type="text" name="info" id="username" />
<input type="submit" name="submit" value="提交">
</form>
</body>
5.创建success.jsp页面
<%@taglib prefix="s" uri="/struts-tags" %>
Successful!!!
<s:property value="info"/>
6.创建error页面
<h1>404找不到页面</h1>