1、搭建 struts2 項目步驟
- 新建Java項目--輸入項目名稱/項目路徑
- 目錄結構如下:將lib文件夾復制到web-inf下(否則發布不到Tomcat)
- 配置web.xml(filter-class中需與導入的Struts2的jar包中的一致,此處刪除了.ng)
- 配置Struts.xml(IDEA創建Struts2項目會自動生成)
- 修改index.jsp
- 運行成功
2、添加頁面
- 編寫 Action 類--HelloAction(在src下創建cn.ht.action.HelloAction類)
package cn.ht.action; /** * @Classname HelloAction * @Description TODO * @Date 2019-8-12 16:12 * @Created by Administrator * Struts2的第一個案例 */ public class HelloAction { // 在Struts2中,所有的業務方法都是public // 返回值都為string類型,所有業務方法都沒有參數 // 方法名可以自定義,默認為execute public String execute(){ System.out.println("hello struts2"); return "success"; } }
注:在 servlet 中,默認執行 service 方法。在 struts2 中,默認執行 execute 方法。
在 servlet 中,service 方法參數時 HttpServletRequest 和 HttpServletResponse,無返回
值。在 struts2 中,方法都是 public 的,並且返回值都是 String 類型,而且方法都是沒
有參數的。
- 配置 action 類--在 struts.xml
<?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="default" namespace="/" extends="struts-default"> <!--配置action 配置url和處理類的方法進行映射 --> <action name="hello" class="cn.ht.action.HelloAction"> <result>/hello.jsp</result> </action> </package> </struts>
- 配置 struts2 的核心控制器 web.xml 文件

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--配置Struts2的前端控制器--> <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>*.action</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
- 訪問:http://localhost:8080/StrutsTest_war_exploded/hello.action
結果: