在最初配置struts中會遇到There is no Action mapped for namespace / and action name類似的問題,很多情況是我們粗心大意導致的,以下為總結的解決方法:
1.struts.xml文件配置錯誤,這是其中一個很大的原因
DTD的問題在此不再贅述,網上相關的帖子很多,在這里出現的問題主要是適用版本2.0的問題,注意區分2.0和2.1,建議都用2.0
其次就是編碼格式的問題,如果遇到中文亂碼,記得加
<constant name="struts.i18n.encoding" value="GBK"></constant>
還有就是存放位置的問題,struts.xml存放於src目錄下(注意MyEclipse和Eclipse的不同)
大多數問題處在package中,
extends的作用主要用於繼承struts-default或者其它的package,根據自己的情況更改,建議不要漏掉;
namespace不要拼寫錯誤,因為在項目中會分單獨每個模塊,建議在平時的練習中最好在namespace中寫成/模塊名,好區分,若平時練習可以寫/,在訪問的時候直接寫
<%=request.getContextPath()%>/index.action
在package中還有比較容易忽視的地方是action中<result>/r1.jsp</result>會比較容易漏掉“/”,在訪問action中提示The requested resource is not available. 多半是因為漏加/仔細一點
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.i18n.encoding" value="GBK"></constant> <package name="actions" namespace="/actions" extends="struts-default"> <action name="index"> <result>/r1.jsp</result> </action> </package> </struts>
2.index.jsp中容易出現的問題
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <% String context=request.getContextPath(); System.out.println(context); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>Insert title here</title> </head> <body> <a href="<%=context%>/actions/index.action">點擊</a> </body> </html>
這里出現的問題主要是在jsp的存放位置,注意區分Eclipse和MyEclipse,我是用的是EclipseEE,jsp的存放位置WebContent,與WEB-INF在同一級,這也是訪問不到的重要原因之一
建議在訪問的時候最好加上.action
3.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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Struts</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>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
這里最好是復制以上filter的,不要更改內容,問題可能會出現在<welcome-file-list>,因為最初生成的web.xml文件中有一個index.html和index.htm,根據自己的情況進行選擇
以上是經驗之談,希望能幫助到大家~~