1. 程式人生 > >Spring+Struts專案裡配置Servlet

Spring+Struts專案裡配置Servlet

1.現象:

報錯:

There is no Action mapped for namespace [/weixin] and action name [WeixinServlet] associated with context path [/app]

2.報錯時程式碼:

/**
 * 核心請求處理類
 * 
 */
public class WeixinServlet extends HttpServlet {
	
	private Logger log = LoggerFactory.getLogger(WeixinServlet.class);
	
	/**
	 * 確認請求來自微信伺服器
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 微信加密簽名
		String signature = request.getParameter("signature");
		// 時間戳
		String timestamp = request.getParameter("timestamp");
		// 隨機數
		String nonce = request.getParameter("nonce");
		// 隨機字串
		String echostr = request.getParameter("echostr");
		//公眾帳號ID
		String waccountId = request.getParameter("id");
		
		out.close();
		out = null;
	}

	/**
	 * 處理微信伺服器發來的訊息
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	
	}

}

web.xml

<!-- struts配置 begin -->
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>com.util.ExtendStrutsFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
<servlet>
        <servlet-name>WeixinServlet</servlet-name>
        <servlet-class>com.weixin.action.WeixinServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>WeixinServlet</servlet-name>
        <url-pattern>/weixin/WeixinCoreServlet</url-pattern>
    </servlet-mapping>

3.解決方案

方案一、修改servlet的配置檔案的<url-pattern> ,struts2的filter中<url-pattern>不變

方案二、修改struts2的filter中<url-pattern>,servlet中的<url-pattern>不變

出於最小影響原則,選擇方案一,使新加的servlet隻影響區域性不影響全域性。

修改後的web.xml

<!-- struts配置 begin -->
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>com.util.ExtendStrutsFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
<servlet>
        <servlet-name>WeixinServlet</servlet-name>
        <servlet-class>com.weixin.action.WeixinServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>WeixinServlet</servlet-name>
        <url-pattern>/weixin/WeixinCoreServlet.servlet</url-pattern>
    </servlet-mapping>

即:

在servlet-mapping標籤中的url-pattern中的路徑後面追加.servlet,使之能準確定位到Servlet類

然後瀏覽器訪問url也做相應的改變:

參考: