使用idea工具,maven來構建struts2項目,給大家詳細截圖講解下,主要是針對新接觸struts2的同學。
大概的步驟如下:
- 新建項目
- 配置pom.xml文件需要的依賴
- 配置web.xml文件
- 添加並配置struts.xml文件
- 添加並編寫需要用的jsp文件
- 配置Tomcat
- 啟動運行
- 報錯及原因分析和解決方案
1.新建項目
1.1.選Maven,勾選Create from archetype,然后選中如下圖的那條。
1.2.輸入GroupId和ArtifactId,這兩個可以按自己意願隨意輸,無需跟下圖完全一致。
1.3.直接選擇下一步Next
1.4.直接完成Finish
1.5.右下角選擇Enable Auto_import,maven會自動加載pom中的依賴jar
1.6.項目新建成功的結構如下圖
2.配置pom.xml文件的struts2依賴
2.1.在pom.xml的dependencies中添加如下依賴
<dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.5.18</version> </dependency>
2.2.效果截圖如下
2.3.添加后,會自動加載,效果如下
3.配置web.xml文件,引入struts核心功能——配置過濾器
3.1.向web.xml中添加filter和filter-mapping節點信息
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <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>/*</url-pattern> </filter-mapping>
4.接下來添加struts.xml文件,並配置
4.1.新建struts.xml文件
4.2.向文件中添加內容,action命名為success,直接指向success.jsp
<?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="basicstruts" extends="struts-default"> <action name="success"> <result>success.jsp</result> </action> </package> </struts>
5.添加success.jsp文件
5.1.添加success.jsp文件
5.2.添加title和body信息如下
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Success</title> </head> <body> <h2>Success</h2> </body> </html>
6.配置tomcat
6.1.從這進入配置頁面
6.2.點擊加號,然后選擇tomcat server,選擇后面的local
6.3.選擇第二個Deployment選項卡,點擊右邊的加號,選擇Artifact
6.4.選擇如下圖的帶exploded的,並確定ok
6.5.回到上級頁面,將Application context改為/,然后apply並ok
7.啟動運行
7.1.點擊右上角的綠色右三角或者下方的run選項卡里的右三角
8.遇到問題和解決方案
8.1.報錯,如下圖
There is no Action mapped for namespace [/] and action name [success] associated with context path [].
8.2.解決方案:這是因為沒法關聯到struts.xml,需要操作如下步驟,可以使用ctrl+alt+shift+s,啟動該界面,如下圖依次操作
8.3可以看到已經有了該關聯文件
8.4.再次運行,輸入localhost:8080/success,就直接轉到了success.jsp頁面
源碼git地址:https://github.com/meersburg/simplestruts2.git