步驟 1、 新建工程 MyElipse下新建一個叫struts2hello的web工程; 2、 導入Jar包 將struts 2的jar包copy到WEB-INF/lib/目錄下; 或者在工程的.classpath文件中加入: [html] <classpathentry kind="con" path="melibrary.com.genuitec.eclipse.struts2.MYECLIPSE_STRUTS21_CORE"/> 並刷新工程。 3、配置Filter 修改web.xml文件,配置Struts 2的核心Filter; [html] <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*.action</url-pattern> </filter-mapping> 4、配置struts.xml 在src 目錄下增加struts.xml配置文件; [html] <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <include file="struts-default.xml" /> <constant name="struts.i18n.encoding" value="utf-8" /> <package name="default" extends="struts-default"> <global-results> <result name="login">login.jsp</result> <result name="index">index.jsp</result> </global-results> <action name="UserAction" class="com.app.action.UserAction" /> </package> </struts> 5、 實現控制器 [java] package com.app.hello; import com.opensymphony.xwork2.Action; //POJO(Plain Object Java Object 低侵入式) public class UserWorld implements Action{ //獲取頁面上的控件,只需要要在這裡注入對應的屬性,提供setter和getter方法即可。(名稱要完全一樣) private User user;//action類德每個屬性對應於頁面中的某個控件屬性 private UserDAO userDAO = new UserDAO(); // action默認執行方法 public String execute() { if(!userDAO.login(user.getUsername(), user.getPassword())) { ActionContext ac = ActionContext.getContext(); ac.put("msg", "登陸信息有誤"); //request.setAttribute("", ); } else { return "index"; //轉發到邏輯視圖對應的頁面 } return "login"; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } // http://localhost:8080/Struts2HelloWorld/hello!aliasAction.action public String aliasAction() { name = ""; return "success"; } } 6、 修改struts.xml文件 添加Action的映射和邏輯視圖轉向,在<struts></struts>中添加如下內容; [html] <package name="default" extends="struts-default"> <action name="hello" class="com.app.hello.HelloWorld"> <result name="success">/helloworld.jsp</result> </action> </package> 7、 添加JSP視圖層 取名helloworld.jsp [html] <%@ page contentType="text/html; charset=utf-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <%@ page isELIgnored="false" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>Say Hello</title> </head> <body> <h3>Say "Hello" to: </h3> <s:property value="name"/> ${name} <s:form action="hello"> Name: <s:textfield name="user.username" /> <s:submit /> </s:form> </body> </html>