Struts2 学习经验之谈

    以前一直用Spring MVC做web项目的开发,虽然知道还存在一个用的比较多的web开发框架就是Struts2. 觉得去试一试,整蛊了一天终于做了一个小例子。给我的感觉就是这个框架问题太多,如果没有人指导的话,太麻烦了了,不过这也是一个学习的过程嘛,或许只有自己亲自动手体验一下,经历一些错误你才能够真正懂得这个框架到底是怎么样运行的。一下是我在这个学习的过程中总结的一些经验,记录下来以便日后借鉴。

1. 首先要从Struts2 官网上下载最新的jar包,(当然里面有很多包,我们可能只需要其中的一部分)这里最简单的例子用来以下9个。有点多,但是我发现只有这些包都加进去才可以正常运行,所以说这个框架有点麻烦。

2. 这个jar包一定要放在你所建立工程项目的lib文件夹下,然后再从构建路径将包导入进去。这么做的原因是,如果你把你的项目部署在一个tomcat服务器的时候不会因为确认包而报错。

3. 关于服务器(在Eclipse中),我建议在建立server的时候(file->new -> server 让后一直进行下去),建好以后在控制台窗口处,点击Servers 然后就可以看到建好的服务器了,然后双击该服务器,将server locations改选为第二个(Use Tomcat installation),Deloy path选为 webapps。这样我们运行的项目就会出现在tomcat 所在的webapps 文件夹下。

4. 新建工程要选web3.0以下,因为在3.0以后没有了web.xml 文件。以下是一个例子,仅供参考。

要特别注意        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>。在近期版本都用这个,

<?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>

5.  struts.xml 要新建这样一个文件,文件名一定要对,不能随意命名。同时,该文件只能位于src目录下,而且不能是子目录下。这样编译后该文件才可以被拷贝到classes文件下,才能正常运行。以下是一个例子。

<?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>
<!-- <constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />-->
<package name="" namespace="/" extends="struts-default">
 <action name="hello" class="com.Hello">
  <result name="success">success.html</result>
  <result name="error">error.html</result>
 </action>

</package>
</struts>

这里的action name的值 就是在对应jsp 或者html文件中 action的值,当然也可以给值加一个".action"的后缀(默认是加的,所以可以不加)。action class的值一定要类名加上包名。

6. 对于工程打成 .war 包,当部署在tomcat服务器时,服务器会自动解压该包进行部署,只要我们部署完毕就可以依据URL访问。

 


你可能感兴趣的:(Struts2 学习经验之谈)