步骤1:添加必须的jar包(刚学习时只需加入5个jar包,但是随着struts2吧不断发展,开发struts2项目所需的jar包有所增加)
(1)common-fileupload-xxx.jar
(2)common-io-xxx.jar
(3)common-logging-xxx.jar
(4)ognl-xxx.jar
(5)struts2-core-xxx.jar
(6)xwork-core-xxx.jar
(7)freemarker-xxx.jar
(8)javassist-xxx.jar
(9)common-lang3-xxx.jar
注:xxx表示版本号
步骤2:在web.xml中添加过滤器
<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>
步骤3:以登录功能为例:
接下来我们回到login.jsp界面进行编辑。一般<form>表单包含用户名username和密码password,如:
<form action="login.action" method="post">
username:<input type="text" name="username"/></br>
password:<input type="password" name="password"/></br>
<input type="submit" value="提交"/>
</form>
步骤4:在src目录下建struts.xml,配置属性:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="struts2" extends="struts-default">
<action name="login" class="action.LoginAction">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
步骤5:编写登录对应的action:LoginAction.java,该类继承ActionSupport
(1)LoginAction.java首先需要封装属性,并提供相对应的set和get方法
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRepassword() {
return repassword;
}
(2)重写ActionSupport的execute()方法
@Override
public String execute() throws Exception {
System.out.println(this.username + " " + this.password );
return SUCCESS;
}
此时execute只是检验了是否将数据从前台页面传递过来
至此,一个简单的struts项目就编写完成了,可以进行部署运行了。