我的Struts2之旅
几次想使用Struts2框架,都以失败告终,甚至按着别人的简单教程来做,也没有走通!哎真是搞不懂怎么这么难。这我下定决心,一定要把它弄懂!
之前曾经按照 http://www.blogjava.net/max/category/16130.html 的指导做了几次,但总没有成功,我就一步一步的来,把每个错误信息都搞清楚。
1. Eclipse 新建动态Web项目,为与MyEclipse 一致,内容目录名改为 WebRoot
2. 在 Web.xml 中添加 Struts2 监听器配置,
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
报错,当然还没引入 jar 包呢!
3. 在 lib 中添加 struts2-core-2.1.8.1.jar, 一个一个的来!
4. 报错
严重: Exception starting filter struts2
java.lang.NoClassDefFoundError: Lcom/opensymphony/xwork2/util/logging/Logger;
5. lib 中添加 xwork-core-2.1.6.jar
报错
严重: Dispatcher initialization failed
Unable to load configuration. - bean - jar:file:/D:/workspace/SiteWeaver/SiteWeaver_2010-06-05/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Struts2_HelloWorld1/WEB-INF/lib/struts2-core-2.1.8.1.jar!/struts-default.xml:47:178
添加 lib commons-fileupload-1.2.1.jar
OK!
6. 添加 SayHello.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Say Hello</title>
</head>
<body>
<h3>Say "Hello" to: </h3>
<s:form action="HelloWorld">
Name: <s:textfield name="name" />
<s:submit />
</s:form>
</body>
</html>
报错:
严重: Servlet.service() for servlet jsp threw exception
The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag. - [unknown location]
at org.apache.struts2.views.jsp.TagUtils.getStack(TagUtils.java:60)
[原因分析]:访问的页面使用了struts标签,但是没有经过struts的过滤器。
在 web.xml 中加上过滤器拦截模板设置
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
测试OK!