java SSH框架搭建总结

最近学习了java的开源框架Struts2、Hibernate、Spring,为了理清一下自己的思路,更为了给自己加深一下印象,同时也方便刚学的朋友可以有个借鉴,本人初学,说的不对的地方还望各位嘴下留情。大神就不用看了。好了废话不多说,咱们切入正题。

大家都知道在使用java开发企业级系统时,不免要涉及到一些开源的框架,其中比较流行的主要有Struts2、Hibernate、Spring以及其他一些框架,这些框架为我们的开发带来了很大的便利。

一、使用Hibernate

Hibernate主要是用来封装JDBC,使用Hibernate可以使我们的DAO层变得非常简单,但是在使用Hibernate的时候要注意的就是映射文件,以及Hibernate中的几种实体之间的关系,Hibernate帮助我们将关系模型转换成了对象模型,这样以来,我们在使用Hibernate的时候就不需要太多的去关心实体与实体的硬性关系,完全可以利用面向对象的思想来思考问题。

使用Hibernate的好处就暂且不说了,我们来看一下在使用Hibernate的时候需要注意的地方有哪些:

首先我们在使用Hibernate的时候要注意的有两个配置文件(学习框架会涉及到很多配置文件):分别为hibernate.cfg.xml和[object].hbm.xml,前者是Hibernate的主配置文件,后者是Hibernate的映射文件,其中[object]代表的是对应于数据库每个表的实体类,在Hibernate的主配置文件中主要涉及一下几个必备的配置项:

<session-factory>
        <property name="dialect">
            org.hibernate.dialect.Oracle9Dialect
        </property>
        <property name="connection.url">
            jdbc:oracle:thin:@localhost:1521:orcl1
        </property>
        <property name="connection.username">jboa</property>
        <property name="connection.password">jboa123</property>
        <property name="connection.driver_class">
            oracle.jdbc.OracleDriver
        </property>
        <property name="myeclipse.connection.profile">jboa</property>
</session-factory>

1.dialect:代表连接数据库的方言,表示当前使用的是哪种数据库,Hibernate可以根据该方言生成适合当前使用的数据库的sql语句。
2.connection.url:连接数据库的连接字符串,不同数据库的连接字符串不同,该项是Hibernate必备项
3.connection.username:连接数据时是用的用户名。
4.connection.password:连接数据库时的密码。
5.connection.driver_class:连接数据库用的驱动,该项也是Hibernate的必备项。


另外,除了以上要求的必备项之外,我们还可以使用一些配置项来帮助我们在开发过程中实时观察Hibernate的运行状况:
<property name="show_sql">true</property>表示要在控制台输出sql语句。

<property name="format_sql">true</property> 表示要格式化输出sql语句。

<property name="current_session_context_class">thread</property> 表示使用ThreadLocal来管理session使得session和当前线程绑定。

<property name="hbm2ddl.auto">update</property> 该项一般用在领域建模的时候,配置该项后Hibernate可以根据映射文件中配置的实体与数据库表之间的关系,动态生成表结构。

<property name="cache.use_second_level_cache"></property>配置该项是为了使用Hibernate支持的二级缓存机制。

以上是hibernate.cfg.xml中的一些经常要用到的一些配置,那么我们接着看一下Hibernate的映射文件配置的时候一些注意要点。

在配置Hibernate的映射文件时([object].hbm.xml)我们必须先要了解实体与实体之间的关系,并且要清楚Hibernate对于对象模型和关系模型是如何转换的,在Hibernate中各个实体之间的关系可以被分为一下几种:

1.多对一映射(many-to-one)

该关系的映射是hibernate中比较常用的,也是较为简单的一种映射关系,该关系映射是站在many的一方考虑,使用<many-to-one>元素来配置该关系,如下所示:
<many-to-one name="" class="" fetch="select" lazy="true">
其中各个属性的值或含义分别为:
name:实体类中one的一方在many一方的实例属性。
class:one的一方对应的实体类全名,即为包名+实体类名。
fetch:该属性指定了在hibernate抓取数据的方式,默认为select。
lazy:表示hibernate是否开启懒加载,默认情况下为true表示开启懒加载。
注意:如果将fetch的值设置为join的话,那么懒加载将会失效。

2.一对多映射(one-to-many)
该关系映射比较特殊,也是hibernate中较为常用的一种映射关系,该关系映射是站在one的一方考虑,在配置的时候较为复杂,如下所示:

在实体类之间,hibernate是通过集合的形式表示这种映射关系的,hibernate支持的用来表示一对多的集合有:set、List、Map,这三种集合对应的映射文件中的配置各不相同。

(1).使用的是set集合
<set name="" inverse="true">
<key>
<column name=""/>
</key>
<one-to-many class="">
</set>

其中name表示实体类中many的一方在one的一方的实例属性,inverse表示反转,一般情况下one的一方最好设置该属性为true,这样one的一方就会放弃维护依赖关系,将依赖关系交给many的一方去维护,这样效率会更高,column元素的name表示的是对应数据库中字表的外键字段名,one-to-many元素中的class表示的many一方的实体类全名(包名+实体类名)。

(2)使用的是List集合
<list name="" inverse="true">
<list-index ></list-index>
<key>
<column name=""/>
</key>
<one-to-many class="">
</list>
使用list集合的时候,一般是因为要保证hibernate取得的数据的顺序,因为List集合的元素是有序的,那么在使用list元素的时候就要指定<list-index>该元素。

如果不需要保证数据顺序的话,可以使用<bag>元素,该元素与set元素用法一致。

二、使用struts2

struts2是一款全新的MVC框架,它使用核心过滤器来控制用户请求,这样的设计使得控制层更加灵活,并且struts2提供了更加完善的验证框架以及支持国际化,除此之外struts2还提供了一系列标签库,使得java开发变得简单化。

使用struts2需要配置两个文件,一是web.xml另外一个是struts.xml,具体配置情况如下:

struts.xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
    <constant name="struts.i18n.encoding" value="utf-8"/>
    <include file="struts-goodslist.xml"/>
    <include file="struts-customer.xml"/>
    <include file="struts-detail.xml"/>

    <include file="struts-info.xml"/>
    <include file="struts-categorys.xml"/>
    <include file="struts-shopcar.xml"/>
    <include file="struts-order.xml"/>
    <include file="struts-backgoods.xml"/>
    <include file="struts-backuser.xml"/>
    <include file="struts-backsale.xml"/>
    <include file="struts-backorders.xml"/>
<include file="struts-backattr.xml"/>
    <package name="default" namespace="/" extends="struts-default">
        <action name="index" class="indexAction">
            <result name="results">/${results}.jsp</result>
        </action>
        <action name="footer" class="footerAction">
            <result name="res">/${res}.jsp</result>
        </action>
        <action name="header" class="headerAction">
            <result name="re">/${re}.jsp</result>
        </action>
    </package>
</struts>    

<package>元素是struts2中特有的包,其中可以包含有关控制器的一些配置,可以包含多个<action>元素,另外<package>默认要继承于struts-default核心包,action中可以使用OGNL表达式来实现动态结果。

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></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>*.action</url-pattern>
  </filter-mapping>
  <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>*.jsp</url-pattern>
  </filter-mapping>

由上述可知struts2是通过核心的过滤器来拦截用户请求的,它的核心类是StrutsPrepareAndExecuteFilter

在使用struts的时候除了使用它来实现MVC以外,我们还经常用到它的标签库,常用的标签有:

<s:property value=""/>、<s:iterator value=""></s:iterator>、<s:select list="" listKey="" listValue="" headerKey="" headerValue="" key=""></s:select>等

三、使用Spring

在使用Spring的时候,首先我们需要了解Spring可以为我们做什么,Spring提供了IOC(控制反转)以及AOP(面向切面编程)以及Spring MVC等,其中IOC可以降低系统的耦合度,通过IOC机制可以使模块之间的调用由主动变为被动的形式。AOP允许通过分离应用的业务逻辑系统服务(例如审计(auditing)和事务(transaction)管理)进行内聚性的开发。应用对象只实现它们应该做的——完成业务逻辑——仅此而已。它们并不负责(甚至是意识)其它的系统级关注点,例如日志或事务支持。

Spring的核心配置文件为applicationContext.xml,其中包含了Spring利用IOC机制的配置,以及一些其他整合struts2和Hibernate的配置,同时我们还需要配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
    <bean id="defaultLobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler" lazy-init="true" />
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="configLocation"
            value="classpath:hibernate.cfg.xml">
        </property>
        <property name="lobHandler" ref="defaultLobHandler"/>
    </bean>
    <!-- 配置声明式事务管理器 -->
    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    
    <!-- 配置声明式事务 -->
    
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="search*" read-only="true"/>
            <tx:method name="query*" read-only="true"/>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="del*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="do*" propagation="REQUIRED"/>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置事务切面 -->
    <aop:config>
        <aop:pointcut expression="execution(* dao.impl.*.*(..))" id="serviceMethod"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>
    </aop:config>
    
    </beans>

Spring还对JavaMail有了很好的支持,其配置如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <!--定义邮件发送器, 配置发送者信息 -->
    <bean id="sender" class="org.springframework.mail.javamail.JavaMailSenderImpl" autowire="byName">
        <property name="host" value="smtp.126.com"/> <!-- SMTP服务器 -->
        <property name="port" value="25"/> <!-- smtp端口号 -->
        <property name="username" value="*****"/> <!-- 用户名 -->
        <property name="password" value="******"/> <!-- 密码 -->
        <property name="protocol" value="smtp"/> <!--采用smtp协议 -->
        <property name="defaultEncoding" value="utf-8"/> <!-- 默认编码 -->
        <property name="javaMailProperties">
            <props>
                <!-- 设置smtp服务器用户认证 -->
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.timeout">25000</prop>
            </props>
        </property>
    </bean>
    <!-- 注入邮件发送器 -->
    <bean id="mailService1" class="util.MailService" autowire="byName"/>
    </beans>

web.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>    
  <!-- 配置Spring -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml,classpath:applicationContext-*.xml</param-value>
  </context-param>
  <!-- 配置Spring监听器 -->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- 配置openSessionInViewFilter -->
  <filter>
      <filter-name>openSessionInViewFilter</filter-name>
      <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>openSessionInViewFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
   </web-app>

 

 

posted @ 2014-04-22 22:50  OnlyYou0726  阅读(656)  评论(0编辑  收藏  举报