今天学习了Struts2 的配置,记录一下。
实验条件:Myeclipse2014/struts2.3.4/windows
实验过程:
一、下载Struts2所需要的最少的jar包(下载jar)
由于是一个简单的配置,那么使用所需的最少支持jar包就可以了,这些所需的最少jar包在apache官网下载struts-2.3.4后,解压,在struts-2.3.4/apps/struts-blank/WEB-INF/lib下找到。
二、使用Myeclipse创建一个web工程
三、将下载解压得到的jar导入工程对应目录(/WEB-INF/lib)下。
四、配置web.xml
我的web.xml源码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts Blank</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,
1、filter-name 名字随便取,但上下两个需保持一致
2、filter-class 过滤器类,在struts2-core-2.3.4.jar中可找到
3、url-pattern 过滤的路径,‘/*’表示对所有的路径都过滤
通过对filter的配置,则意为已将此项目交给struts2来管理了
五、配置struts,xml
在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>
<!-- 常量名字来自 struts2-core-2.3.4 org.apache.struts2 static detault.properties-->
<!-- 改变访问后缀名的常量 ,可选择,多选项逗号隔开 -->
<constant name="struts.action.extension" value="action,do,,"></constant>
<!-- 配置开发者模式 ,配置文件更新了,不需要重启服务器, 实时更新-->
<constant name="struts.devMode" value="true"></constant>
<!-- 配置路径映射,namespace是访问的路劲,如/aa,那么浏览器访问的时候应是/aa/index -->
<package name="default" namespace="/" extends="struts-default">
<!-- 属性
name:访问时的名字
class:对应的类 可不写,默认为xwork2 的 ActionSupport
method:可不写,执行的方法,默认为execute
-->
<action name="index" >
<result>/index.jsp</result>
</action>
</package>
</struts>
这里做个补充。我们为了快熟开发,常常使用ALT+"/"的快捷键组合得到提示信息。但是在断网的情况下是不可以得出的,根据struts.xml中
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
可以看到,它是从网络http://struts.apache.org/dtds/struts-2.3.dtd中获取的数据。
解决办法:Windows--Preferences---输入xml---xml Catalog--Add--file System--选择路径struts-2.3.4\src\core\src\main\resources\struts-2.3.dtd(这个要是在官网中下载的all版本有源码的才行)-- key type选择urI--key填写http://struts.apache.org/dtds/struts-2.3.dtd。这样即使在断网的情况下也可以使用快捷键提示了。
六、测试将项目部署在tomcat上,在浏览器上访问http://localhost:8080/demoname/index或http://localhost:8080/demoname/index.action或http://localhost:8080/demoname/index.do都可以访问到index.jsp,可以看到浏览器的地址没有发生改变,应该是采用的请求转发的方式执行的跳转。