struts2框架第一个实例
(1)新建web项目,在项目中添加struts2的核心类库。
commons-logging-1.0.4.jar
freemarker-2.3.13.jar
ognl-2.6.11.jar
struts2-core-2.1.6.jar
xwork-2.1.2
commons-fileupload-1.2.1
其中如果缺少commens-fileupload-1.2.1这个jar包,tomcat在启动时就会报错Exception starting filter struts2
Unable to load configuration.
(2)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>Struts</display-name> <filter> <filter-name>**</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>**</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> </web-app>
其中<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>该类是在 struts2-core-2.1.6.jar中
(3)新建login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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=ISO-8859-1"> <title>login.jsp</title> </head> <body> <form action="login.action" method="post"> userName:<input type="text" name="userName"><br> password:<input type="password" name="password"><br> <input type="submit" value="submit"> </form> </body> </html>
(4)新建loginSuccess.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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=ISO-8859-1"> <title>loginSuccess</title> </head> <body> userName:${requestScope.userName}<br> password:${requestScope.password} </body> </html>
(5)新建Action
public class LoginAction { 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 execute() throws Exception{ return "success"; } }
struts2中的action与struts1中的action完全不同,是一个普通的pojo。
由属性,属性的set,get方法,及execute()方法组成。而execute() 方法的返回值和名称是固定的。
(6)在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="login" extends="struts-default"> <action name="login" class="login.LoginAction"> <result name="success" >/loginSuccess.jsp</result> </action> </package> </struts>