點擊MyEclipse菜單欄File按鈕,點擊new-->Web Project
輸入Project name之后點擊Finish
項目創建完成。
然后右鍵項目,點擊MyEclipse-->Project Facets-->Install Apache Struts(2.x) Facets
選擇Struts2的版本,然后點擊finish
完成后的項目目錄結構如下圖所示:
創建完之后在src下面可以看到struts.xml
在src下創建action包,然后創建HelloWorldAction.java文件,內容如下:
public class HelloWorldAction extends ActionSupport{ @Override public String execute() throws Exception{ // TODO Auto-generated method stub System.out.println("執行Action"); return "success"; } }
在src下面的struts.xml中加入代碼,效果如下圖所示:
<?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> <package name="default" extends="struts-default"> <action name="helloworld" class="action.HelloWorldAction"> <result name="success">/result.jsp</result> </action> </package> </struts>
在WebRoot路徑下添加result.jsp頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>result.jsp</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> This is result page. <br> </body> </html>
web.xml是自動生成的
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>struts2Test2</display-name> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> </web-app>
將項目部署到tomcat服務器,打開瀏覽器地址欄輸入http://localhost:8080/struts2Demo/helloworld.action即可訪問
推薦學習視頻(struts2入門):http://www.imooc.com/learn/464