1.加载Struts 2类库
<dependencies>
<!-- Struts 2 核心包-->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.4.1</version>
</dependency>
<!-- Struts 2 构建基础-->
<dependency>
<groupId>org.apache.struts.xwork</groupId>
<artifactId>xwork-core</artifactId>
<version>2.3.4.1</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
2.配置wbe.xml文件
<web-app>
<display-name>Archetype Created Web Application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3.开发视图层页面
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>Struts</title>
</head>
<body>
<h2>第一个Strusts 2案例</h2>
<s:property value="message"></s:property>
<form action="helloWorld" method="post">
用户名:<input name="uname" /><s:fielderror fieldName="uname"></s:fielderror>
密码: <input type="password" name="upwd"/><s:fielderror fieldName="pwd" ></s:fielderror>
<input type="submit" value="提交">
</form>
</body>
</html>
4.开发控制层页面Action
public class HelloWorldAction extends ActionSupport implements Action {
private String uname;
private String upwd;
private String message;
//唯一的执行方法
public String execute() throws Exception {
if (this.getUname().equals("1")&&this.getUpwd().equals("1")){
this.setMessage("Hello!"+this.getUname());
return "success";
}else{
return "input";
}
}
//服务器端数据校验
public void validate(){
if (this.getUname().length()==0){
addFieldError("uname","用户名不能为空");
}
if (this.getUpwd().length()==0){
addFieldError("pwd","密码不能为空");
}
}
public String getUpwd() {
return upwd;
}
public void setUpwd(String upwd) {
this.upwd = upwd;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
5.配置Struts.xml
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="helloWorld" class="HelloWorldAction">
<result name="success">/First.jsp</result>
<result name="input">/First.jsp</result>
</action>
</package>
</struts>
6.部署、运行项目
- 直接运行
- 正确输入用户名,密码