標籤:struts開發步驟 配置
說來慚愧,這一個簡單的struts折騰了好久,差不多花了三天多的時間才解決。下面我總結一下開發的步驟:(本人用的是MyEclipse);
1.建立一個Exercise3的web Project項目
2.配置web.xml檔案
添加如下代碼:
<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>/*</url-pattern></filter-mapping>
3.加入類庫
將如的jar包放在WEB-INF/lib下
4.建立一個類
代碼如下:
package cn.wwh.www.struts;/** *類的作用: * *@author 一葉扁舟 *@version 1.0 *@建立時間: 2014-8-11 下午08:44:26 */public class FirstAction {public String <span style="color:#ff0000;">firtstMethod</span>(){System.out.println("hello word ,this my first Struts!");return "hello";}}
5.在WebRoot下建立一個views/hello/welcome.jsp檔案
welcome.jsp的代碼如下:
<pre name="code" class="html"><%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%><%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>My JSP 'welcome.jsp' starting page</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> Hello Word ! welcome to Struts !This is my first Struts. </body></html>
6.在src下建一個struts.xml檔案
代碼如下:
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""http://struts.apache.org/dtds/struts-2.3.dtd"><struts><package name="default" namespace="/<span style="color:#3333ff;">test</span>" extends="struts-default"><action name="<span style="color:#3333ff;">hello</span>" class="cn.wwh.www.struts.FirstAction"method="<span style="color:#ff0000;">firtstMethod</span>"><result name="hello" type="redirect"><param name="location">/views/hello/welcome.jsp</param></result></action></package></struts>
7.在tomcat中部署一下
在瀏覽器中輸入:http://localhost:8080/Exercise3/test/hello.action
由於在設定檔中採用的是redirect(重新導向)的方式,所以地址欄會發生改變
結果圖:
特別要注意(一直出錯的原因):
1.jar包不能重複匯入,否則出現jar衝突,本人由於有各種版本的jar包,所以在啟動tomcat的時候發生了該異常。
2.在瀏覽器中輸入的訪問地址出現了錯誤,這個地址組合是與struts.xml檔案中namespace和action name 有關
一般訪問方式:
http://ip:port/contextPath/namespace/actionName[.action]