Struts2.3.16.1+Hibernate4.2.4+Spring4.0.2注解整合

来源:互联网 发布:单片机输入的是什么 编辑:程序博客网 时间:2024/06/05 16:29

如果大家对maven比较熟悉的话,建议大家用maven搭建SSH比较理想,因为我发现直接用jar包整合SSH是一件头痛的事,尝会报一些奇怪的错误,所以我借此将我整合的经验跟大家分享一下,希望对大家有所参考作用。

在这里,我建议大家整合框架的时候,一个框架一个框架的整合,整合完一个框架就测试一个框架,这样出错容易查找。

 一.首先单独整合Spring。

1.导入jar包。


2.新建一个Spring配置文件,我这里新建了beans.xml。

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"<span style="white-space:pre"></span>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<span style="white-space:pre"></span>xmlns:aop="http://www.springframework.org/schema/aop"<span style="white-space:pre"></span>xmlns:context="http://www.springframework.org/schema/context"<span style="white-space:pre"></span>xmlns:tx="http://www.springframework.org/schema/tx"<span style="white-space:pre"></span>xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd<span style="white-space:pre"></span>http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd<span style="white-space:pre"></span>http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd<span style="white-space:pre"></span>http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"><span style="white-space:pre"></span><span style="white-space:pre"></span><!-- 自动加载构建bean -->        <context:component-scan base-package="cn.zym" />    </beans>

<context:component-scan base-package="cn.zym" /> ,自动扫描cn.zym包下的组件,实现注解配置数据库访问层(@Repository)、业务层(@Service)、控制层(@Controller),还有注入功能(@Resource)。

3.测试Spring的提供的控制反转和依赖注入功能。

import org.springframework.stereotype.Repository;@Repositorypublic class MyDao {<span style="white-space:pre"></span>public void prin(){<span style="white-space:pre"></span>System.out.println("我是ZYM");<span style="white-space:pre"></span>}}
@Repository ,将数据库访问层的bean交给Spring生成和管理。

import javax.annotation.Resource;import org.springframework.stereotype.Service;import cn.zym.dao.impl.MyDao;@Servicepublic class MyServiceImpl {<span style="white-space:pre"></span>@Resource<span style="white-space:pre"></span>private MyDao myDao;<span style="white-space:pre"></span>public void setMyDao(MyDao myDao) {<span style="white-space:pre"></span>this.myDao = myDao;<span style="white-space:pre"></span>}<span style="white-space:pre"></span><span style="white-space:pre"></span>public void print(){<span style="white-space:pre"></span>myDao.prin();<span style="white-space:pre"></span>}}
@Service ,将业务层的bean交给Spring生成和管理,@Resource 将myDao注入到myServiceImpl组件中。

import org.junit.BeforeClass;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.zym.service.impl.MyServiceImpl;public class MyServiceTest {<span style="white-space:pre"></span>private static ApplicationContext act;<span style="white-space:pre"></span>private static MyServiceImpl myService;<span style="white-space:pre"></span>@BeforeClass<span style="white-space:pre"></span>public static void setUpBeforeClass() throws Exception {<span style="white-space:pre"></span>act = new ClassPathXmlApplicationContext("beans.xml");<span style="white-space:pre"></span>myService = act.getBean(MyServiceImpl.class);<span style="white-space:pre"></span>}<span style="white-space:pre"></span><span style="white-space:pre"></span>@Test<span style="white-space:pre"></span>public void printTest(){<span style="white-space:pre"></span>myService.print();<span style="white-space:pre"></span>}<span style="white-space:pre"></span>}
测试Spring注解整合的是否成功,控制台如果打印出了"我是ZYM",ok,下一步,整合hibernate。

二.整合Hibernate之数据库连接。

1.导入jar包。


2.新建一个db.properties 

jdbc.user=rootjdbc.password=rootjdbc.driverClass=com.mysql.jdbc.Driverjdbc.jdbcUrl=jdbc:mysql://localhost:3306/testjdbc.initPoolSize=5jdbc.maxPoolSize=10

3.在beans.xml添加,数据源连接配置

<span style="white-space:pre"></span><!-- 加载数据库属性配置文件 --><context:property-placeholder location="classpath:db.properties"/><!-- 配置 C3P0 数据源 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="user" value="${jdbc.user}"></property><property name="password" value="${jdbc.password}"></property><property name="driverClass" value="${jdbc.driverClass}"></property><property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property><property name="initialPoolSize" value="${jdbc.initPoolSize}"></property><property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property></bean>
4.测试数据库是否连接成功。

import java.sql.SQLException;import javax.sql.DataSource;import org.junit.BeforeClass;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class MyDataSourceTest {private static ApplicationContext act;@BeforeClasspublic static void setUpBeforeClass() throws Exception {act = new ClassPathXmlApplicationContext("beans.xml");}//测试数据库连接成功与否@Testpublic void testDataSource() throws SQLException{DataSource ds = (DataSource) act.getBean("dataSource");System.out.println(ds.getConnection());}}
如果System.out.println(ds.getConnection());能够在控制台打印出一个Connection对象,就代表连接成功。我的:com.mchange.v2.c3p0.impl.NewProxyConnection@5abf3952

三.整合Hibernate之session工厂和事务管理(transactionManager)。

1.在beans.xml中添加session单例配置和事务管理。

<!-- 配置 SessionFactory --><bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><!-- 配置Hibernate相关属性 --><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop><prop key="hibernate.show_sql">true</prop><prop key="hibernate.format_sql">true</prop><prop key="hibernate.hbm2ddl.auto">update</prop></props></property><!-- 自动扫描注解方式配置实体bean --><property name="packagesToScan" value="cn.zym.model"/></bean><!-- 配置事务管理 --><bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">          <property name="sessionFactory" ref="sessionFactory" />      </bean>        <tx:advice id="txAdvice" transaction-manager="transactionManager">          <!-- 定义事务传播属性 -->          <tx:attributes>              <tx:method name="insert*" propagation="REQUIRED" />              <tx:method name="update*" propagation="REQUIRED" />              <tx:method name="edit*" propagation="REQUIRED" />              <tx:method name="save*" propagation="REQUIRED" />              <tx:method name="add*" propagation="REQUIRED" />              <tx:method name="new*" propagation="REQUIRED" />              <tx:method name="set*" propagation="REQUIRED" />              <tx:method name="remove*" propagation="REQUIRED" />              <tx:method name="delete*" propagation="REQUIRED" />              <tx:method name="change*" propagation="REQUIRED" />              <tx:method name="get*" propagation="REQUIRED" read-only="true" />              <tx:method name="find*" propagation="REQUIRED" read-only="true" />              <tx:method name="load*" propagation="REQUIRED" read-only="true" />              <tx:method name="*" propagation="REQUIRED" read-only="true" />          </tx:attributes>      </tx:advice>          <aop:config>          <aop:pointcut id="serviceOperation"              expression="execution(* cn.zym.service..*.*(..))" />          <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />      </aop:config>
Spring提供管理事务的方式有两种,一种是通过注解方式实现的,一种是xml配置实现,我这边就采用了常用的xml配置,但是黎活明老师倡导使用注解方式,因为注解方式配置会更加的细致。

 <aop:pointcut id="serviceOperation" expression="execution(* cn.zym.service..*.*(..))" />  这段代码就是实现了拦截cn.zym.service包极其子包下的所有事物和方法。

2.注解创建实体bean。

import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import org.hibernate.annotations.GenericGenerator;@Entitypublic class User {private Integer id;private String username;private String password;@Id@GenericGenerator(name = "generator", strategy = "increment")      @GeneratedValue(generator = "generator")      @Column(length=11)public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}@Column(name="username",length=20)public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}@Column(name="password",length=20)public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}
3.实现dao层的bean,摘抄自网上。

import java.io.Serializable;import java.util.List;public interface BaseDAO<T> {/**      * 保存一个对象      *       * @param o      * @return      */      public Serializable save(T o);        /**      * 删除一个对象      *       * @param o      */      public void delete(T o);        /**      * 更新一个对象      *       * @param o      */      public void update(T o);        /**      * 保存或更新对象      *       * @param o      */      public void saveOrUpdate(T o);        /**      * 查询      *       * @param hql      * @return      */      public List<T> find(String hql);        /**      * 查询集合      *       * @param hql      * @param param      * @return      */      public List<T> find(String hql, Object[] param);        /**      * 查询集合      *       * @param hql      * @param param      * @return      */      public List<T> find(String hql, List<Object> param);        /**      * 查询集合(带分页)      *       * @param hql      * @param param      * @param page      *            查询第几页      * @param rows      *            每页显示几条记录      * @return      */      public List<T> find(String hql, Object[] param, Integer page, Integer rows);        /**      * 查询集合(带分页)      *       * @param hql      * @param param      * @param page      * @param rows      * @return      */      public List<T> find(String hql, List<Object> param, Integer page, Integer rows);        /**      * 获得一个对象      *       * @param c      *            对象类型      * @param id      * @return Object      */      public T get(Class<T> c, Serializable id);        /**      * 获得一个对象      *       * @param hql      * @param param      * @return Object      */      public T get(String hql, Object[] param);        /**      * 获得一个对象      *       * @param hql      * @param param      * @return      */      public T get(String hql, List<Object> param);        /**      * select count(*) from 类      *       * @param hql      * @return      */      public Long count(String hql);        /**      * select count(*) from 类      *       * @param hql      * @param param      * @return      */      public Long count(String hql, Object[] param);        /**      * select count(*) from 类      *       * @param hql      * @param param      * @return      */      public Long count(String hql, List<Object> param);        /**      * 执行HQL语句      *       * @param hql      * @return 响应数目      */      public Integer executeHql(String hql);        /**      * 执行HQL语句      *       * @param hql      * @param param      * @return 响应数目      */      public Integer executeHql(String hql, Object[] param);        /**      * 执行HQL语句      *       * @param hql      * @param param      * @return      */      public Integer executeHql(String hql, List<Object> param); }
</pre><pre name="code" class="html">import java.io.Serializable;import java.util.List;import javax.annotation.Resource;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;import org.springframework.transaction.annotation.Transactional;import cn.zym.dao.BaseDAO;@Repository  @SuppressWarnings("all")public class BaseDAOImpl<T> implements BaseDAO<T> {private SessionFactory sessionFactory;        public SessionFactory getSessionFactory() {          return sessionFactory;      }        @Resource     public void setSessionFactory(SessionFactory sessionFactory) {          this.sessionFactory = sessionFactory;      }        private Session getCurrentSession() {          return sessionFactory.getCurrentSession();      }        public Serializable save(T o) {          return this.getCurrentSession().save(o);      }        public void delete(T o) {          this.getCurrentSession().delete(o);      }        public void update(T o) {          this.getCurrentSession().update(o);      }        public void saveOrUpdate(T o) {          this.getCurrentSession().saveOrUpdate(o);      }        public List<T> find(String hql) {          return this.getCurrentSession().createQuery(hql).list();      }        public List<T> find(String hql, Object[] param) {          Query q = this.getCurrentSession().createQuery(hql);          if (param != null && param.length > 0) {              for (int i = 0; i < param.length; i++) {                  q.setParameter(i, param[i]);              }          }          return q.list();      }        public List<T> find(String hql, List<Object> param) {          Query q = this.getCurrentSession().createQuery(hql);          if (param != null && param.size() > 0) {              for (int i = 0; i < param.size(); i++) {                  q.setParameter(i, param.get(i));              }          }          return q.list();      }        public List<T> find(String hql, Object[] param, Integer page, Integer rows) {          if (page == null || page < 1) {              page = 1;          }          if (rows == null || rows < 1) {              rows = 10;          }          Query q = this.getCurrentSession().createQuery(hql);          if (param != null && param.length > 0) {              for (int i = 0; i < param.length; i++) {                  q.setParameter(i, param[i]);              }          }          return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();      }        public List<T> find(String hql, List<Object> param, Integer page, Integer rows) {          if (page == null || page < 1) {              page = 1;          }          if (rows == null || rows < 1) {              rows = 10;          }          Query q = this.getCurrentSession().createQuery(hql);          if (param != null && param.size() > 0) {              for (int i = 0; i < param.size(); i++) {                  q.setParameter(i, param.get(i));              }          }          return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();      }        public T get(Class<T> c, Serializable id) {          return (T) this.getCurrentSession().get(c, id);      }        public T get(String hql, Object[] param) {          List<T> l = this.find(hql, param);          if (l != null && l.size() > 0) {              return l.get(0);          } else {              return null;          }      }        public T get(String hql, List<Object> param) {          List<T> l = this.find(hql, param);          if (l != null && l.size() > 0) {              return l.get(0);          } else {              return null;          }      }        public Long count(String hql) {          return (Long) this.getCurrentSession().createQuery(hql).uniqueResult();      }        public Long count(String hql, Object[] param) {          Query q = this.getCurrentSession().createQuery(hql);          if (param != null && param.length > 0) {              for (int i = 0; i < param.length; i++) {                  q.setParameter(i, param[i]);              }          }          return (Long) q.uniqueResult();      }        public Long count(String hql, List<Object> param) {          Query q = this.getCurrentSession().createQuery(hql);          if (param != null && param.size() > 0) {              for (int i = 0; i < param.size(); i++) {                  q.setParameter(i, param.get(i));              }          }          return (Long) q.uniqueResult();      }        public Integer executeHql(String hql) {          return this.getCurrentSession().createQuery(hql).executeUpdate();      }        public Integer executeHql(String hql, Object[] param) {          Query q = this.getCurrentSession().createQuery(hql);          if (param != null && param.length > 0) {              for (int i = 0; i < param.length; i++) {                  q.setParameter(i, param[i]);              }          }          return q.executeUpdate();      }        public Integer executeHql(String hql, List<Object> param) {          Query q = this.getCurrentSession().createQuery(hql);          if (param != null && param.size() > 0) {              for (int i = 0; i < param.size(); i++) {                  q.setParameter(i, param.get(i));              }          }          return q.executeUpdate();      }  }
4.实现service层的bean。

import cn.zym.model.User;public interface UserService {public abstract User findUserByUserNameAndPassword(String username,String password);public void addUser(User user);}

import javax.annotation.Resource;import org.springframework.stereotype.Service;import cn.zym.dao.BaseDAO;import cn.zym.model.User;import cn.zym.service.UserService;@Service("userService")public class UserServiceImpl implements UserService {@Resource      private BaseDAO<User> baseDAO;@Overridepublic void addUser(User user){baseDAO.save(user);}@Overridepublic User findUserByUserNameAndPassword(String username,String password){return baseDAO.get("from User u where u.username=? and u.password=? ", new String[] {username,password});}}
5.测试UserServiceImpl业务组件。

import org.junit.BeforeClass;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.zym.model.User;import cn.zym.service.UserService;public class UserTest {private static ApplicationContext act;private static UserService us = null;@BeforeClasspublic static void setUpBeforeClass() throws Exception {act = new ClassPathXmlApplicationContext("beans.xml");us = (UserService) act.getBean("userService");}@Testpublic void testsave(){User u = new User();u.setUsername("xm");u.setPassword("123");us.addUser(u);}@Testpublic void testgetUser(){System.out.println(us.findUserByUserNameAndPassword("xm", "123"));}}

四.整合Struts2。

1.添加jar。


2.添加web.xml配置文件。

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="WebApp_ID" version="2.5"><!-- 服务器启动,初始化spring容器 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:beans.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 数据提交中文乱码问题 --><filter><filter-name>encodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 延迟加载带来的问题 --><filter><filter-name>openSessionInViewFilter</filter-name><filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class><init-param><param-name>singleSession</param-name><param-value>true</param-value></init-param></filter> <!-- 添加对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>/*</url-pattern>   </filter-mapping></web-app>
3.添加struts2的配置文件(struts.xml)和添加jsp页面。

<?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>       <!-- 指定Web应用的默认编码集,相当于调用HttpServletRequest的setCharacterEncoding方法 -->    <constant name="struts.i18n.encoding" value="UTF-8"/>    <!-- 该属性指定需要Struts 2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。    如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。 -->    <constant name="struts.action.extension" value="action"/>    <!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 -->    <constant name="struts.serve.static.browserCache" value="false"/>    <!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->    <constant name="struts.configuration.xml.reload" value="true"/>    <!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->    <constant name="struts.devMode" value="true" />     <!-- 默认的视图主题 -->    <constant name="struts.ui.theme" value="simple" />    <!-- action类由spring创建 -->    <constant name="struts.objectFactory" value="spring" />           <package name="s2sh" namespace="/user" extends="struts-default">          <action name="login" method="login" class="cn.zym.action.LoginAction">              <result name="success">/success.jsp</result>              <result name="error">/login.jsp</result>          </action>      </package>        </struts>
login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  <%  String path = request.getContextPath();  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  %>    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  <html>    <head>      <base href="<%=basePath%>">            <title>My JSP 'index.jsp' starting page</title>      <meta http-equiv="pragma" content="no-cache">      <meta http-equiv="cache-control" content="no-cache">      <meta http-equiv="expires" content="0">          <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">      <meta http-equiv="description" content="This is my page">      <!--     <link rel="stylesheet" type="text/css" href="styles.css">     -->    </head>        <body>    <form action="${pageContext.request.contextPath}/user/login.action" method="post">       username:<input type="text" name="username"/> <br/>       password:<input type="password" name="password"/> <br/>      <input type="submit" value="login"/><input type="reset" value="reset"/>    </form>    </body>  </html>  
seccess.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  <%  String path = request.getContextPath();  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  %>    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  <html>    <head>      <base href="<%=basePath%>">            <title>My JSP 'index.jsp' starting page</title>      <meta http-equiv="pragma" content="no-cache">      <meta http-equiv="cache-control" content="no-cache">      <meta http-equiv="expires" content="0">          <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">      <meta http-equiv="description" content="This is my page">      <!--     <link rel="stylesheet" type="text/css" href="styles.css">     -->    </head>        <body>     欢迎您:${username}!    </body>  </html>  
4.实现Action。

import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import org.apache.struts2.ServletActionContext;import org.springframework.stereotype.Controller;import cn.zym.model.User;import cn.zym.service.UserService;import com.opensymphony.xwork2.ActionSupport;@Controllerpublic class LoginAction extends ActionSupport { private static final long serialVersionUID = -9044881430201334544L;@Resource      private UserService userService;private String username;      private String password;        public String login(){                  HttpServletRequest request = ServletActionContext.getRequest();          User user = userService.findUserByUserNameAndPassword(username, password);         if (user != null) {              request.setAttribute("username", username);              return SUCCESS;          } else {              return ERROR;          }                    }         public String getUsername() {          return username;      }      public void setUsername(String username) {          this.username = username;      }      public String getPassword() {          return password;      }      public void setPassword(String password) {          this.password = password;      } }

最后,访问:http://localhost:8888/SSH2/user/login.action 进行测试。

源代码下载链接:点击打开链接




0 0