1、首先在web.xml中配置监听器ContextLoaderListener,当服务器启动的时候加载,beans.xml在src下,就写classpath:beans.xml。源码如下
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
2、然后顺着去看beans.xml里面的配置(这是spring)的核心配置文件
以c3p0的连接池对象为例,如下方式配置
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/shop" />
<property name="user" value="root" />
<property name="password" value="root" />
</bean>
其中id属性是自己起的名字,class是所要生成对象的类的全路径。property是其中的成员变量,若要注入已经在beans.xml中配置好的对象,可将value换成ref,对应在配置文件中起的id名。例如
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:hibernate.cfg.xml" /> <!-- 加载hibernate配置文件 -->
</bean>
3、这里sessionFactory对象加载了hibernate.cfg.xml这个hibernate的核心配置文件,接下来我们去看这个配置文件。
注意,该核心配置文件的名字固定,只能叫这个,不同于spring的配置文件。
其中配置了一些关于数据库连接的配置,基本上已经被spring整合,所以不用再配置。
需要注意的是其中会引入POJO类的映射文件,比如:
<mapping resource="cn/sqy/shop/model/Category.hbm.xml" />
为了规范起见,往往都讲映射文件和pojo类放在同一个包下,且按照*.hbm.xml的格式命名。
4、接下来去看看映射文件格式
<class name="cn.sqy.shop.model.Category" table="category" >
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="native" />
</id>
<property name="type" type="java.lang.String">
<column name="type" length="20" />
</property>
<property name="hot" type="java.lang.Boolean">
<column name="hot" />
</property>
</class>
首先必须指定一个id作为主键,native表示自增策略,出主键外的字段都用property标签,若不给colum设置name属性,默认是和property中的name属性一样的。
5、之后再来看看struts2的配置,它的配置文件名字也固定,必须为struts.xml,放在SRC下。
其中配置格式如下
<struts>
<package name="shop" extends="struts-default">
<action name="category_*" class="categroyAction" method="{1}">
<result name="index">/index.jsp</result>
</action>
</package>
</struts>
这里*是占位符,{1}指向这占位符,例如超链接为shop/category_update,点击此链接,会自动调用,categoryAction类中的update方法,注意这里的class没有写全路径,因为categoryAction已经在spring配置过了,只需要写在spring中的id名即可。result标签则用来重定向或者转发,若该方法返回值为index,则转发到index.jsp。
还有最容易忘记的一点,需要在web.xml中为struts2配置过滤器:
<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>*.action</url-pattern>
</filter-mapping>
这里url设置为*.action,作用就是所有以.action结尾的超链接,都会被struts2管理。