SSH

来源:互联网 发布:单片机数码管显示数字 编辑:程序博客网 时间:2024/06/05 17:26

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_3_0.xsd"    id="WebApp_ID" version="3.0">    <display-name>zs</display-name>    <welcome-file-list>        <welcome-file>pages/login/login.jsp</welcome-file>    </welcome-file-list>    <!-- 添加对spring的支持 -->    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath:applicationContext.xml</param-value>    </context-param>    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <!-- 添加对struts2的支持 -->    <filter>        <filter-name>struts2</filter-name>        <filter-class>com.jinmayi.util.MyStrutsFilter</filter-class><!--        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> -->    </filter>    <!-- 当hibernate+spring配合使用的时候,如果设置了lazy=true,那么在读取数据的时候,当读取了父数据后, hibernate会自动关闭session,这样,当要使用子数据的时候,系统会抛出lazyinit的错误,         这时就需要使用spring提供的 OpenSessionInViewFilter,OpenSessionInViewFilter主要是保持Session状态         知道request将全部页面发送到客户端,这样就可以解决延迟加载带来的问题 -->    <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>    <filter-mapping>        <filter-name>struts2</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>    <filter-mapping>        <filter-name>openSessionInViewFilter</filter-name>        <!-- <url-pattern>*.html,*.do,*.action</url-pattern> -->        <url-pattern>/*</url-pattern>    </filter-mapping>    <jsp-config>        <taglib>            <taglib-uri>/tags</taglib-uri>            <taglib-location>/WEB-INF/util/datetag.tld</taglib-location>        </taglib>    </jsp-config>    <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></web-app>

3.applicationContext.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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"     xsi:schemaLocation="                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd              http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd              http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd              http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">    <!-- 加载数据库属性配置文件 -->    <!-- <context:property-placeholder location="classpath:db.properties" /> -->    <!-- 数据库连接池c3p0配置 -->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"        destroy-method="close">        <!-- <property name="jdbcUrl" value="${db.url}" />        <property name="user" value="${db.username}" />        <property name="password" value="${db.password}" />        <property name="driverClass" value="${db.driverClassName}" /> -->        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/zs" />        <property name="user" value="root" />        <property name="password" value="123" />        <property name="driverClass" value="com.mysql.jdbc.Driver" />        <property name="maxPoolSize" value="40" />        <property name="minPoolSize" value="1" />        <property name="initialPoolSize" value="1" />        <property name="maxIdleTime" value="20" />    </bean>    <!-- session工厂 -->    <bean id="sessionFactory"        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">        <property name="dataSource">            <ref bean="dataSource" />        </property>        <property name="configLocation" value="classpath:hibernate.cfg.xml" />        <!-- 自动扫描注解方式配置的hibernate类文件 -->        <property name="packagesToScan">            <list>                <value>com.jinmayi.entity</value>            </list>        </property>    </bean>    <!-- 配置事务管理器 -->    <bean id="transactionManager"        class="org.springframework.orm.hibernate4.HibernateTransactionManager">        <property name="sessionFactory" ref="sessionFactory" />    </bean>    <!-- 使用annotation配置事务,注意,服务层一定要配置事务,否则报错:No Session found for current thread -->      <tx:annotation-driven transaction-manager="transactionManager"/>      <!-- 配置事务通知属性 -->    <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="check*" propagation="REQUIRED" />            <tx:method name="print*" propagation="REQUIRED" />            <tx:method name="package*" propagation="REQUIRED" />            <tx:method name="sell*" propagation="REQUIRED" />            <tx:method name="register*" 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>    <!-- 应用普通类获取bean <bean id="appContext" class="com.soanl.util.tool.ApplicationUtil"/> -->    <!-- 配置事务切面 -->    <aop:config>        <aop:pointcut id="serviceOperation"            expression="execution(* com.jinmayi.service..*.*(..))" />        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />    </aop:config>    <!-- 自动加载构建bean -->    <context:component-scan base-package="com.jinmayi">            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>       </context:component-scan></beans>  

4.ehcache.xml

<ehcache>    <!-- Sets the path to the directory where cache .data files are created.         If the path is a Java System Property it is replaced by         its value in the running VM.         The following properties are translated:         user.home - User's home directory         user.dir - User's current working directory         java.io.tmpdir - Default temp file path -->    <diskStore path="java.io.tmpdir"/>    <!--Default Cache configuration. These will applied to caches programmatically created through        the CacheManager.        The following attributes are required for defaultCache:        maxInMemory       - Sets the maximum number of objects that will be created in memory        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element                            is never expired.        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used                            if the element is not eternal. Idle time is now - last accessed time        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used                            if the element is not eternal. TTL is now - creation time        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache                            has reached the maxInMemory limit.        -->    <defaultCache        maxElementsInMemory="10000"        eternal="false"        timeToIdleSeconds="120"        timeToLiveSeconds="120"        overflowToDisk="true"        />    <!--Predefined caches.  Add your cache configuration settings here.        If you do not have a configuration for your cache a WARNING will be issued when the        CacheManager starts        The following attributes are required for defaultCache:        name              - Sets the name of the cache. This is used to identify the cache. It must be unique.        maxInMemory       - Sets the maximum number of objects that will be created in memory        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element                            is never expired.        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used                            if the element is not eternal. Idle time is now - last accessed time        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used                            if the element is not eternal. TTL is now - creation time        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache                            has reached the maxInMemory limit.        -->    <!-- Sample cache named sampleCache1        This cache contains a maximum in memory of 10000 elements, and will expire        an element if it is idle for more than 5 minutes and lives for more than        10 minutes.        If there are more than 10000 elements it will overflow to the        disk cache, which in this configuration will go to wherever java.io.tmp is        defined on your system. On a standard Linux system this will be /tmp"        -->    <cache name="sampleCache1"        maxElementsInMemory="10000"        eternal="false"        timeToIdleSeconds="300"        timeToLiveSeconds="600"        overflowToDisk="true"        />    <!-- Sample cache named sampleCache2        This cache contains 1000 elements. Elements will always be held in memory.        They are not expired. -->    <cache name="sampleCache2"        maxElementsInMemory="1000"        eternal="true"        timeToIdleSeconds="0"        timeToLiveSeconds="0"        overflowToDisk="false"        /> -->    <!-- Place configuration for your caches following --></ehcache>

5.hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>  <!DOCTYPE hibernate-configuration PUBLIC               "-//Hibernate/Hibernate Configuration DTD 3.0//EN"          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration>    <session-factory>        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>        <property name="jdbc.batch_size">20</property>        <property name="connection.autocommit">true</property>        <!-- 显示sql语句 -->        <property name="show_sql">true</property>        <property name="connection.useUnicode">true</property>        <property name="connection.characterEncoding">UTF-8</property>        <!-- 缓存设置 -->        <property name="cache.provider_configuration_file_resource_path">/ehcache.xml</property>        <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>        <property name="cache.use_query_cache">true</property>        <mapping resource="com/jinmayi/entity/Admin.hbm.xml" />        <mapping resource="com/jinmayi/entity/Employee.hbm.xml" />        <mapping resource="com/jinmayi/entity/Enterprise.hbm.xml" />        <mapping resource="com/jinmayi/entity/Circulate.hbm.xml" />        <mapping resource="com/jinmayi/entity/Product.hbm.xml" />        <mapping resource="com/jinmayi/entity/Qrcode.hbm.xml" />        <mapping resource="com/jinmayi/entity/Productproperty.hbm.xml" />        <mapping resource="com/jinmayi/entity/Logininformation.hbm.xml" />        <mapping resource="com/jinmayi/entity/Waybill.hbm.xml" />        <mapping resource="com/jinmayi/entity/Qrcodeproperty.hbm.xml" />        <mapping resource="com/jinmayi/entity/CoiCategoryOne.hbm.xml"/>        <mapping resource="com/jinmayi/entity/CoiCategoryThree.hbm.xml"/>        <mapping resource="com/jinmayi/entity/CoiCategoryTwo.hbm.xml"/>        <mapping resource="com/jinmayi/entity/Statistical.hbm.xml"/>        <mapping resource="com/jinmayi/entity/Scaninformation.hbm.xml"/>        <mapping resource="com/jinmayi/entity/Repertory.hbm.xml"/>        <mapping resource="com/jinmayi/entity/Evaluate.hbm.xml"/>        <mapping resource="com/jinmayi/entity/Makeqrcode.hbm.xml"/>        <mapping resource="com/jinmayi/entity/Packageinformation.hbm.xml"/>        <mapping resource="com/jinmayi/entity/Sellinformation.hbm.xml"/>    </session-factory></hibernate-configuration>  

6.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{1}:%L - %m%n### direct messages to file hibernate.log ###log4j.appender.file=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.file.File=${catalina.home}/logs/zs/zs.log log4j.appender.file.DatePattern = '.'yyyy-MM-dd log4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%nlog4j.appender.file.encoding=UTF-8### set log levels - for more verbose logging change 'info' to 'debug' ###log4j.rootLogger=info, stdout, file

7.struts.xml

<?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.i18n.encoding" value="UTF-8" />    <constant name="struts.action.extension" value="action" />    <constant name="struts.serve.static.browserCache" value="false" />    <constant name="struts.action.extension" value="php,jmy"></constant>    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>    <constant name="struts.devMode" value="true" />    <package name="app" extends="json-default">        <action name="app-login" method="login" class="com.jinmayi.action.app.AppEmployeeAction">            <result type="json"></result>        </action>           </package>    <package name="inter" extends="struts-default">        <interceptors>             <interceptor name="loginedCheck" class="com.jinmayi.util.LoginedCheckInterceptor" />             <interceptor-stack name="mystack">                  <interceptor-ref name="loginedCheck" />                  <interceptor-ref name="defaultStack" />            </interceptor-stack>        </interceptors>         <global-results>            <result name="exception">/pages/login/login.jsp</result>            <result name="tologin">/pages/login/login.jsp</result>        </global-results>        <global-exception-mappings>            <exception-mapping exception="java.lang.Exception" result="exception" />        </global-exception-mappings>     </package>    <package name="jsp" extends="inter">        <default-interceptor-ref name="mystack" />        <action name="show" method="show" class="com.jinmayi.action.ShowAction">            <result>/pages/show/show.jsp</result>        </action>               <action name="verCode" method="verCode" class="com.jinmayi.action.SubscriberAction"></action>           </package></struts>   

8.BaseDAO.java接口

package com.jinmayi.dao;  import java.io.Serializable;  import java.util.List;  /**  * 基础数据库操作类  *   * @author ss  *   */  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);  }  

9.BaseDAOImpl.java

package com.jinmayi.dao.impl;import java.io.Serializable;import java.util.List;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 com.jinmayi.dao.BaseDAO;@Repository("baseDAO")@SuppressWarnings("all")public class BaseDAOImpl<T> implements BaseDAO<T> {    private SessionFactory sessionFactory;    public SessionFactory getSessionFactory() {        return sessionFactory;    }    @Autowired    public void setSessionFactory(SessionFactory sessionFactory) {        this.sessionFactory = sessionFactory;    }    private Session getCurrentSession() {        return sessionFactory.getCurrentSession();    }    @Override    public Serializable save(T o) {        return this.getCurrentSession().save(o);    }    @Override    public void delete(T o) {        this.getCurrentSession().delete(o);    }    @Override    public void update(T o) {        this.getCurrentSession().update(o);    }    @Override    public void saveOrUpdate(T o) {        this.getCurrentSession().saveOrUpdate(o);    }    @Override    public List<T> find(String hql) {        return this.getCurrentSession().createQuery(hql).list();    }    @Override    public List<T> find(String hql, Object[] param) {        Query q = null;        try {            q = this.getCurrentSession().createQuery(hql);        } catch (Exception e) {            e.printStackTrace();        }        if (param != null && param.length > 0) {            for (int i = 0; i < param.length; i++) {                q.setParameter(i, param[i]);            }        }        return q.list();    }    @Override    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();    }    @Override    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();    }    @Override    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();    }    @Override    public T get(Class<T> c, Serializable id) {        return (T) this.getCurrentSession().get(c, id);    }    @Override    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;        }    }    @Override    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;        }    }    @Override    public Long count(String hql) {        return (Long) this.getCurrentSession().createQuery(hql).uniqueResult();    }    @Override    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();    }    @Override    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();    }    @Override    public Integer executeHql(String hql) {        return this.getCurrentSession().createQuery(hql).executeUpdate();    }    @Override    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();    }    @Override    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();    }}

10.Page.java

package com.jinmayi.domain;import java.util.List;public class Page<T> {    // 当前第几页    private Long pageNow;    // 当前页的 List    private List<T> list;    // 每页显示多少条记录    private long pageSize = 10;    // 共有多少条记录    private long totalItemNumber;    // 构造器中需要对 pageNow 进行初始化    public Page(Long pageNow) {        super();        this.pageNow = pageNow;    }    // 需要校验一下    public long getpageNow() {        if (pageNow <= 0)            pageNow = 1l;        if (getTotalPageNumber() != 0 && pageNow > getTotalPageNumber()) {            pageNow = getTotalPageNumber();        }        return pageNow;    }    public long getPageSize() {        return pageSize;    }    public long setPageSize(long pageSize) {        return this.pageNow = pageSize;    }    public void setList(List<T> list) {        this.list = list;    }    public List<T> getList() {        return list;    }    // 获取总页数    public Long getTotalPageNumber() {        long totalPageNumber =  totalItemNumber / pageSize;        if (totalItemNumber % pageSize != 0) {            totalPageNumber++;        }        return totalPageNumber;    }    public void setTotalItemNumber(long totalItemNumber) {        this.totalItemNumber = totalItemNumber;    }    public boolean isHasNext() {        if (getpageNow() < getTotalPageNumber()) {            return true;        }        return false;    }    public boolean isHasPrev() {        if (getpageNow() > 1) {            return true;        }        return false;    }    public long getPrevPage() {        if (isHasPrev()) {            return getpageNow() - 1;        }        return getpageNow();    }    public long getNextPage() {        if (isHasNext()) {            return getpageNow() + 1;        }        return getpageNow();    }    @Override    public String toString() {        return "Page [pageNow=" + pageNow + ", list=" + list + ", pageSize="                + pageSize + ", totalItemNumber=" + totalItemNumber + "]";    }}
0 0
原创粉丝点击