今天学习配置了struts2,总结一下:
(1)从官网下载struts2的包我的版本是2.5.116网址如下: (https://struts.apache.org/download.cgi#struts2516),我下载的是struts2.5.16.min.zip,然后解压
(2)在eclipse下创建一个动态web项目不妨叫做test3,然后把刚解压的bin目录下的所有的jars包放到Webcontent-WEB_INF目录下,并且在WEB-INF 文件夹下面创建web.xml 在java Resource的src目录下创建struts2.xml
(3)创建login.jsp,代码如下:这里需要注意的是action的写法
<%@ 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="login.action" method="post">
请输入账号:<input name="account" type="text"/><br>
请输入密码:<input name="password" type="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
(4)创建loginsucess.jsp和loginFail.jsp,就是简单表示登陆成功登陆失败的跳转功能界面
(5)创建服务端java程序主要代码如下:
package teststruts2;
public class LoginAction {
private String account;
private String password;
public LoginAction() {
// TODO Auto-generated constructor stub
}
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 execute() {
if(account.equals(password)) {
return "success";
}
return "fail";
}
}
6.配置web.xml文件:代码如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>test3</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts-prepare</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareFilter</filter-class>
</filter>
<filter>
<filter-name>struts-execute</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts-prepare</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts-execute</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
7、配置struts2.xml文件:代码如下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="struts2" extends="struts-default">
<action name="login" class="test3.LoginAction">
<result name="success">/loginSuccess.jsp</result>
<result name="fail">/loginFail.jsp</result>
</action>
</package>
</struts>
这里需要注意的是<action name="login">这个标签login可以随便取,但是必须要和login.jsp文件里面的action保持一致
比如说name="jk"则login.jsp里面的action里面应该为jk.action,还有一个注意的地方就是在login.jsp里面的action还可以写成/test3/login.action ,test3表示项目名