SSH整合

来源:互联网 发布:2016网络贷款平台排名 编辑:程序博客网 时间:2024/04/27 16:32
<?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:context="http://www.springframework.org/schema/context"       xmlns:aop="http://www.springframework.org/schema/aop"       xmlns:tx="http://www.springframework.org/schema/tx"       xsi:schemaLocation="http://www.springframework.org/schema/beans           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd           http://www.springframework.org/schema/context           http://www.springframework.org/schema/context/spring-context-2.5.xsd           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><!-- 1 属性文件加载 指定spring容器要加载的属性文件 用来连接数据库的  --><bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><!-- 加载位于src目录下的 jdbc.properties --><property name="location">        <value>classpath:/jdbc.properties</value>    </property><!-- 加载位于webapp目录下的文件  <property name="locations"><list><value>/WEB-INF/db/jdbc.properties</value></list></property>--></bean><!-- 2 把类交给spring管理 扫描加注解的方式 包及其子包--><context:component-scan base-package="com.scottwong"/><!-- 3 配置c3p0数据源--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"><property name="driverClass" value="${jdbc.driver}"/><property name="jdbcUrl" value="${jdbc.url}"/><property name="user" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/><!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 --><property name="initialPoolSize" value="1" /><!--连接池中保留的最小连接数。--><property name="minPoolSize" value="1" /><!--连接池中保留的最大连接数。Default: 15 --><property name="maxPoolSize" value="300" /><!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --><property name="maxIdleTime" value="60" /><!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --><property name="acquireIncrement" value="5" /><!--每60秒检查所有连接池中的空闲连接。Default: 0 --><property name="idleConnectionTestPeriod" value="60" /></bean><!-- 4 把SessionFactory交给spring管理 单例 spring和hibernate集成--><bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="annotatedClasses" ref="annotatedClasses"/>   <property name="hibernateProperties"> <value>      hibernate.dialect=org.hibernate.dialect.MySQL5Dialect      hibernate.hbm2ddl.auto=update      hibernate.show_sql=false      hibernate.format_sql=false  </value> </property></bean><!-- 5 指定哪些类是和数据库中的表一一对应的。-->  <beanid="annotatedClasses" class="org.springframework.beans.factory.config.ListFactoryBean">       <property name="sourceList">           <list>               <value>com.scottwong.bean.Employee</value>               <value>com.scottwong.bean.Department</value>        </list>       </property>   </bean>   <!-- 6 配置spring的事物管理器 把hibernate的事务管理交给spring --><bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"/></bean><!-- 7 使用基于注解配置事务 --><tx:annotation-driven transaction-manager="txManager"/></beans>

 以上是 bean.xml  一共是7步 用的是spring annotation

---------------------------------------------------------------------------------------------------------------------------------------------------

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"><!-- 指定spring的配置文件,默认从web根目录寻找配置文件,我们可以通过spring提供的classpath:前缀指定从类路径下寻找 --><context-param>   <param-name>contextConfigLocation</param-name>   <param-value>classpath:beans.xml</param-value></context-param><!-- 对Spring容器进行实例化 --><listener>      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param> <param-name>webAppRootKey</param-name> <param-value>webName.root</param-value> </context-param><!--由Sprng载入的Log4j配置文件位置-->   <context-param>          <param-name>log4jConfigLocation</param-name>          <param-value>classpath:log4j.properties</param-value>   </context-param>     <!--Spring默认刷新Log4j配置文件的间隔,单位为millisecond-->   <context-param>          <param-name>log4jRefreshInterval</param-name>          <param-value>60000</param-value>   </context-param>     <!--Spring log4j Config loader-->   <listener>          <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>   </listener>     <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>


jdbc.properties

jdbc.username=rootjdbc.password=qq123456jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc\:mysql\://127.0.0.1\:3306/ssh2?useUnicode\=true&characterEncoding\=UTF-8&zeroDateTimeBehavior\=convertToNulljdbc.dialect=org.hibernate.dialect.MySQLDialectjdbc.show_sql=true 


 

log4j.properties

### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c:%L - %m%n### direct messages to file hibernate.log ####log4j.appender.file=org.apache.log4j.FileAppender#log4j.appender.file.File=hibernate.log#log4j.appender.file.layout=org.apache.log4j.PatternLayout#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change 'info' to 'debug' ###log4j.rootLogger=info, stdout#log4j.logger.org.hibernate=info#log4j.logger.org.hibernate=debug### log HQL query parser activity#log4j.logger.org.hibernate.hql.ast.AST=debug### log just the SQL#log4j.logger.org.hibernate.SQL=debug### log JDBC bind parameters ####log4j.logger.org.hibernate.type=info#log4j.logger.org.hibernate.type=debug### log schema export/update ####log4j.logger.org.hibernate.tool.hbm2ddl=debug### log HQL parse trees#log4j.logger.org.hibernate.hql=debug### log cache activity ####log4j.logger.org.hibernate.cache=debug### log transaction activity#log4j.logger.org.hibernate.transaction=debug### log JDBC resource acquisition#log4j.logger.org.hibernate.jdbc=debug### enable the following line if you want to track down connection ###### leakages when using DriverManagerConnectionProvider ####log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace



 

package com.scottwong.action;import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Controller;import com.opensymphony.xwork2.ActionSupport;import com.scottwong.bean.Employee;import com.scottwong.service.EmployeeService;import com.scottwong.util.PageBean;@Controllerpublic class EmployeeAction extends ActionSupport {@Resourceprivate EmployeeService employeeService;private int page;    //第几页    private PageBean pageBean;    //包含分布信息的bean        public int getPage() {        return page;    }    public void setPage(int page) {        //若URL中无此参数,会默认为第1页        this.page = page;    }    public PageBean getPageBean() {        return pageBean;    }    public void setPageBean(PageBean pageBean) {        this.pageBean = pageBean;    }private List<Employee> listEmployees;    //用来页面显示private int id;                          //用来接收参数private Employee employee;               //用来页面显示public Employee getEmployee() {return employee;}public void setEmployee(Employee employee) {this.employee = employee;}public int getId() {return id;}public void setId(int id) {this.id = id;}public List<Employee> getListEmployees() {return listEmployees;}public void setListEmployees(List<Employee> listEmployees) {this.listEmployees = listEmployees;}/** * http://localhost:8080/ssh2_1.1/employee/employeeAction!add.action */public String add(){//Employee transientInstance = new Employee("黄家驹",200000,3);//employeeService.save(transientInstance);return "add";}/** * 显示所有的雇员 * http://localhost:8080/ssh2_1.4/employee/employeeAction!list.action */public String list(){this.pageBean = employeeService.queryForPage(10, page);return "list";}/** * 显示一个雇员 * http://localhost:8080/ssh2_1.1/employee/employeeAction!show.action?id=10 */public String show(){employee = employeeService.findById(id);return "show";}/** * 修改雇员信息前收集数据 * @return */public String preUpdate(){employee = employeeService.findById(id);return "preupdate";}/** * 更新数据 * @return */public String update(){employeeService.update(employee);return "update";}}


 

package com.scottwong.service;import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Service;import com.scottwong.bean.Employee;import com.scottwong.dao.EmployeeDao;import com.scottwong.dao.PageDao;import com.scottwong.util.PageBean;@Servicepublic class EmployeeService {@Resourceprivate EmployeeDao employeeDao;@Resourceprivate PageDao pageDao;/**      * 分页查询     * @param currentPage 当前第几页     * @param pageSize    每页大小     * @return 封闭了分页信息(包括记录集list)的Bean     */     public PageBean queryForPage(int pageSize,int page){        final String hql = "from Employee";        //查询语句        int allRow = pageDao.getAllRowCount(hql);    //总记录数        int totalPage = PageBean.countTotalPage(pageSize, allRow);    //总页数        final int offset = PageBean.countOffset(pageSize, page);    //当前页开始记录        final int length = pageSize;    //每页记录数        final int currentPage = PageBean.countCurrentPage(page);        List list = pageDao.queryForPage(hql,offset, length);        //"一页"的记录                //把分页信息保存到Bean中        PageBean pageBean = new PageBean();        pageBean.setPageSize(pageSize);            pageBean.setCurrentPage(currentPage);        pageBean.setAllRow(allRow);        pageBean.setTotalPage(totalPage);        pageBean.setList(list);        pageBean.init();        return pageBean;    }public void save(Employee transientInstance){this.employeeDao.save(transientInstance);}public List<Employee> findAllEmployees(){return this.employeeDao.findAllEmployees();}public Employee findById(int id) {return this.employeeDao.findById(id);}public void update(Employee transientInstance) {this.employeeDao.update(transientInstance);}public List<Employee> findAll(){return this.employeeDao.findAll();}public List<Employee> findByHQL(int id,String name){return this.employeeDao.findByHQL(id,name);}public List<Employee> findEmployeesByemployeeName(final String name){return this.employeeDao.findEmployeesByemployeeName(name);}public List<Employee> findByCriteria(int id, String name) {return this.employeeDao.findByCriteria(id, name);}public List<Employee> findByDongTaiBangDing(int id, String name) {return this.employeeDao.findByDongTaiBangDing(id, name);}}


 

package com.scottwong.dao;import java.sql.SQLException;import java.util.List;import javax.xml.registry.infomodel.User;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.hibernate.Criteria;import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.criterion.DetachedCriteria;import org.hibernate.criterion.Restrictions;import org.springframework.orm.hibernate3.HibernateCallback;import org.springframework.stereotype.Repository;import com.scottwong.bean.Employee;@Repositorypublic class EmployeeDao extends BaseDao {private static final Log log = LogFactory.getLog(EmployeeDao.class);public void save(Employee transientInstance) {log.info("saving Employee instance");try {getHibernateTemplate().save(transientInstance);log.info("save successful");} catch (RuntimeException re) {log.error("save failed", re);throw re;}}public void delete(Employee persistentInstance) {log.debug("deleting Employee instance");try {getHibernateTemplate().delete(persistentInstance);log.info("delete successful");} catch (RuntimeException re) {log.error("delete failed", re);throw re;}}public void update(Employee transientInstance) {log.info("update Employee instance");try {getHibernateTemplate().update(transientInstance);getHibernateTemplate().flush();log.info("update successful");} catch (RuntimeException re) {log.error("update failed", re);throw re;}}@SuppressWarnings("unchecked")public List<Employee> findAllEmployees() {log.info("finding all Employee instances");try {String queryString = "from Employee";return getHibernateTemplate().find(queryString);} catch (RuntimeException re) {log.error("find all failed", re);throw re;}}public Employee findById(int id) {log.info("getting Employee instance with id: " + id);try {Employee instance = (Employee) getHibernateTemplate().get(Employee.class, id);return instance;} catch (RuntimeException re) {log.error("get failed", re);throw re;}}public List findByExample(Employee instance) {log.debug("finding Employee instance by example");try {List results = getHibernateTemplate().findByExample(instance);log.info("find by example successful, result size: "+ results.size());return results;} catch (RuntimeException re) {log.error("find by example failed", re);throw re;}}public List findByProperty(String propertyName, Object value) {log.info("finding Employee instance with property: " + propertyName+ ", value: " + value);try {String queryString = "from Employee as model where model."+ propertyName + "= ?";return getHibernateTemplate().find(queryString, value);} catch (RuntimeException re) {log.error("find by property name failed", re);throw re;}}@SuppressWarnings("unchecked")public List<Employee> findAll() {return (List<Employee>) this.getHibernateTemplate().findByCriteria(DetachedCriteria.forClass(Employee.class));}@SuppressWarnings("unchecked")public List<Employee> findByHQL(final int id, final String name) {return (List<Employee>) this.getHibernateTemplate().execute(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException,SQLException {List result = session.createCriteria(Employee.class)      .add(Restrictions.ge("employeeId", id)) //ge >= bigger than and equal      .add(Restrictions.like("employeeName", "%" + name + "%"))      .list();return result;}});}@SuppressWarnings("unchecked")public List<Employee> findByCriteria(final int id, final String name) {return (List<Employee>) this.getHibernateTemplate().execute(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException,SQLException {Criteria criteria = session.createCriteria(Employee.class);criteria.add(Restrictions.like("employeeName", name+"%")); // Employee有个属性叫name criteria.add(Restrictions.gt("employeeId", id));          // Employee有个属性叫employeeId   List<User> list = (List<User>) criteria.list();  return list;}});}/** * 动态绑定参数 * @param id * @param name * @return */@SuppressWarnings("unchecked")public List<Employee> findByDongTaiBangDing(final int id, final String name) {return (List<Employee>) this.getHibernateTemplate().execute(new HibernateCallback() {public Object doInHibernate(Session session) throws HibernateException,SQLException {String hql ="from Employee as e where e.employeeId >= :id and e.employeeName like :name";Query query = session.createQuery(hql);query.setInteger("id", id);query.setString("name", "%"+name+"%");List<User> list = (List<User>) query.list();  return list;}});}@SuppressWarnings("unchecked")public List<Employee> findEmployeesByemployeeName(final String name) {return (List<Employee>) this.getHibernateTemplate().execute(new HibernateCallback() {public Object doInHibernate(Session session)throws HibernateException {List<Employee> result = session.createCriteria(Employee.class).add(Restrictions.like("employeeName", name + "%")).list();return result;}});}}


 

package com.scottwong.dao;import javax.annotation.Resource;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.hibernate.SessionFactory;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;public class BaseDao extends HibernateDaoSupport {@Resource(name = "sessionFactory") //为父类HibernateDaoSupport注入sessionFactory的值    public void setSuperSessionFactory(SessionFactory sessionFactory) {        try{        super.setSessionFactory(sessionFactory);        }catch (Exception e) {        e.printStackTrace();}            }}


 

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"    "http://struts.apache.org/dtds/struts-2.0.dtd"><struts><!-- 默认的视图主题 --><constant name="struts.ui.theme" value="simple"/><constant name="struts.configuration.xml.reload" value="true" />    <constant name="struts.devMode" value="true" /><!-- 使用spring的对象工厂替换struts2默认的对象工厂  由 StrutsSpringObjectFactory 负责Action对象的创建 从spring容器里获取bean实例 --><!-- org.apache.struts2.spring.StrutsSpringObjectFactory --><!-- 配也可以,不配也可以 --><constant name="struts.objectFactory" value="spring" /><!-- http://localhost:8080/ssh2/employee/list.action --><package name="employee" namespace="/employee" extends="struts-default"><action name="employeeAction" class="employeeAction"><result name="add">/employee/add_success.jsp</result><result name="list">/employee/index.jsp</result><result name="preupdate">/employee/pre_update.jsp</result><result name="update" type="redirect" >employeeAction!list.action</result></action><action name="listmemberAction" class="listmemberAction"><result name="list">/listMember.jsp</result></action></package><package name="login" namespace="/login" extends="struts-default"><action name="loginAction" class="loginAction"></action></package></struts>


原创粉丝点击