创建项目
file - - ->新建Dynamic Web Project(如果没找到这三个单词也可以直接在other里面搜索即可)- - >next…- - >finish即可
我的项目结构如下:
导入所需jar包
可以去这里下载:http://download.youkuaiyun.com/download/qq_36748278/9981431 ,然后复制到项目的WEB-INF下的lib文件夹中即可
配置web.xml文件
加上这一段代码:
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
编写你的项目代码
我这里举个小例子:实现登录功能。
1、在WebContent目录下创建一个login.jsp页面。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="mylogin_login" method="post">
<table>
<tr>
<td>account:</td>
<td><input type="text" name="account"></td>
</tr>
<tr>
<td>password:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="login"></td>
</tr>
</table>
</form>
</body>
</html>
2、在src下创建我的LoginAction文件,用来编写登录时候的验证。
package org.danni.web.action;
public class LoginAction{
private String account;
private String password;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String login(){
//如果账号是lili,密码是123456就可以去index页面
if("lili".equals(account) && "123456".equals(password)){
return "loginSuccess";
}
//否则继续回到login页面
return "login";
}
}
3、在src目录下创建struts文件进行配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="Login" namespace="/" extends="struts-default">
<action name="mylogin_*" class="org.danni.web.action.LoginAction" method="{1}">
<result name="loginSuccess">/index.jsp</result>
<result name="login">login.jsp</result>
<allowed-methods>login</allowed-methods>
</action>
</package>
</struts>
package标签: name属性可以自己定义,没有要求。
action标签: name属性是你为自己的action定义的别名,class属性配置你编写的LoginAction的路径,包括包名。这里的name我采用占位符的形式,用占位符来指明你调用的是哪个方法。具体用法这里先不讲,后期我会更新。
result标签:也就是你的LoginAction中方法返回的字符串。进行匹配要进行那个操作。