ssh + oracle 项目总结

一直在用ssm做项目,好久没有做ssh项目了。用ssm+oracle来开发真的是一步一个坑。基本上每个操作都会出问题。下面从环境搭建开始来说明各种坑。

一、使用各种环境的版本

Hibernate 5.x 其实只用到了4.x的部分功能
Struts2 2.3.16 (没用最新版)
Spring 4.x
Oracle 11g
省略其他小类库…………………………..

二、maven环境搭建

2.1 pom.xml文件

    
        4.3.1.Final
        UTF-8
      
      
        
          junit
          junit
          4.11
          test
        
     
        
        
          com.oracle
          ojdbc6
          11.2.0
        


        
        
          com.microsoft.sqlserver
          sqljdbc4
          4.0
        
        
        
          c3p0
          c3p0
          0.9.1.2
        

        
        
          javax.servlet
          javax.servlet-api
          3.0.1
          provided
        

        
        
        
          org.springframework
          spring-core
          4.1.3.RELEASE
        
        
        
          org.springframework
          spring-beans
          4.1.3.RELEASE
        
    
        
          org.springframework
          spring-orm
          4.1.3.RELEASE
        
        
          org.springframework
          spring-context
          4.1.3.RELEASE
        

        

        
          org.springframework
          spring-jdbc
          4.1.3.RELEASE
        

        
        
          org.springframework
          spring-tx
          4.1.3.RELEASE
        
    
        
          org.springframework
          spring-test
          4.1.3.RELEASE
          test
        

        
        
          org.springframework
          spring-web
          4.1.3.RELEASE
        
        
          javax.servlet.jsp
          jsp-api
          2.1
        

        
          javax.servlet.jsp.jstl
          jstl-api
          1.2
        

        
          taglibs
          standard
          1.1.2
        
        

        
        
          log4j
          log4j
          1.2.17
        


        
        
          org.hibernate
          hibernate-core
          ${org.hibernate-version}
        
        
          org.hibernate
          hibernate-validator
          ${org.hibernate-version}
        
        
          org.hibernate
          hibernate-entitymanager
          ${org.hibernate-version}
        
        
          javax.validation
          validation-api
          1.0.0.GA
          provided
        

        
      
          org.javassist
          javassist
          3.18.1-GA
        

        

        
          org.apache.struts
          struts2-core
          2.3.16
          
            
              javassist
              javassist
            
          
        

        
          org.apache.struts
          struts2-spring-plugin
          2.3.16
        

        
          org.apache.struts
          struts2-convention-plugin
          2.3.16
        
        
        
          org.apache.struts
          struts2-json-plugin
          2.3.16
        

        
        
          com.alibaba
          fastjson
          1.2.21

2.2 注意事项

2.2.1 加载oracle 驱动到本地仓库

由于oracle 没有提供第三方maven库,因此需要自己将oracle jar添加到本地maven库中去。在我本机中安装了oracle数据库,在安装包中自带了驱动。位置在下图的路径中

说明:之前用的驱动是ojdbc14.jar ,此图中ojdbc5.jar ojdbc6.jar .期中14代表支持jdk1.4版本以上。5代表支持5.0 ,6代表6.0 以此类推。我本地jdk是1.7 所以使用ojdbc6.

向本地maven库中添加ojdbc maven命令:
命令如下:

mvn install:install-file -Dfile=D:/app/zyz/product/11.2.0/dbhome_1/jdbc/lib/ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar

D:/app/zyz/product/11.2.0/dbhome_1/jdbc/lib/ojdbc6.jar:此为笔者的ojdbc6.jar绝对路径

安装完成后引入jar

<dependencies>    
      
<dependency>    
<groupId>com.oraclegroupId>   
 <artifactId>ojdbc6artifactId> 
   <version>11.2.0version>   
 dependency> 
 dependencies>

参考链接:http://www.th7.cn/db/Oracle/201502/92865.shtml

2.2.2 Struts2与hibernate中 关于javassist.jar 会有所冲突,因此要将低版本的javassist.jar 从依赖中删除。

删除依赖如下:


      org.apache.struts
      struts2-core
      2.3.16
      
        
          javassist
          javassist
        
      
    

三、ssh环境搭建

系统工程架构如下:

3.1 数据库连接配置信息-jdbc.properties

# mysql连接配置
#driverClass=com.mysql.jdbc.Driver
#jdbcUrl=jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=utf8
#user=root
#password=x5
#hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
# sqlserver连接配置
#driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
#url=jdbc:sqlserver://127.0.0.1;database=hibernate
#user=sa
#password=123
# oracle连接配置
driverClass=oracle.jdbc.driver.OracleDriver
jdbcUrl=jdbc:oracle:thin:@127.0.0.1:1521:orcl
user=keyan
password=keyan


#config hibernate properties
hibernate.dialect=org.hibernate.dialect.Oracle9Dialect
hibernate.show_sql=true
hibernate.format_sql=false
hibernate.jdbc.batch_size=10
hibernate.hibernate.connection.SetBigStringTryClob=true
hibernate.hibernate.archive.autodetection=class
hibernate.hibernate.connection.charSet=UTF-8
hibernate.hibernate.cache.use_query_cache=false
hibernate.hibernate.cache.use_second_level_cache=false

3.2 spring 配置信息

结构图如下:

3.2.1 dao配置


<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
       
       <context:annotation-config/>
       
       <context:property-placeholder location="classpath:jdbc.properties"/>
       
       <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
              
              <property name="driverClass" value="${driverClass}"/>
              <property name="jdbcUrl" value="${jdbcUrl}"/>
              <property name="user" value="${user}"/>
              <property name="password" value="${password}"/>

              
              <property name="autoCommitOnClose" value="false"/>
              <property name="checkoutTimeout" value="3000"/>
              <property name="acquireRetryAttempts" value="3"/>
              <property name="maxPoolSize" value="5"/>
              <property name="minPoolSize" value="3"/>
       bean>
       <bean id="sessionFactory"
             class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
              <property name="dataSource" ref="dataSource" />
              
              <property name="packagesToScan" value="com.web.bean" />
              <property name="hibernateProperties">
                     <props>
                            <prop key="hibernate.dialect">${hibernate.dialect}prop>
                            <prop key="hibernate.show_sql">${hibernate.show_sql}prop>
                            <prop key="hibernate.format_sql">${hibernate.format_sql}prop>
                            <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}prop>
                            <prop key="hibernate.hibernate.connection.SetBigStringTryClob">${hibernate.hibernate.connection.SetBigStringTryClob}prop>
                            <prop key="hibernate.hibernate.archive.autodetection">${hibernate.hibernate.archive.autodetection}prop>
                            <prop key="hibernate.hibernate.connection.charSet">${hibernate.hibernate.connection.charSet}prop>
                            <prop key="hibernate.hibernate.cache.use_query_cache">${hibernate.hibernate.cache.use_query_cache}prop>
                            <prop key="hibernate.hibernate.cache.use_second_level_cache">${hibernate.hibernate.cache.use_second_level_cache}prop>
                            
                            <prop key="hibernate.enable_lazy_load_no_trans">trueprop>
                     props>
              property>
       bean>
              
        <bean class="com.web.common.CommonDaoImpl">
            <property name="sessionFactory" ref="sessionFactory"/>
        bean>
beans>

3.2.2 事务配置


<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:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
      
        <context:annotation-config/>
        <context:component-scan base-package="com.web.service.impl"/>


        <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"/>
        bean>
    
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

beans>

3.2.3 spring –Struts 整合配置


<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">
      
        <context:annotation-config/>
        <context:component-scan base-package="com.web.action"/>

beans>

3.3 struts2 配置


 

<struts>
    
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    
    <constant name="struts.devMode" value="true" />
    
    <constant name="struts.action.extension" value="action,do,,">constant>
    
    <constant name="struts.serve.static.browserCache" value="true">constant>
    
     <constant name="struts.multipart.maxSize" value="2097152000">constant>
    
    <constant name="struts.multipart.saveDir" value="d:/test"/>
    
    <constant name="struts.action.excludePattern" value="/resource/.*?" />
    
    <package name="json" extends="struts-default,json-default" namespace="/">
        <action name="*JsonAction" class="jsonAction" method="{1}">
            <result  name="success" type="json">
                <param name="root">resultparam>
            result>
        action>
    package>
    
    <package name="fileupload" extends="struts-default,json-default" namespace="/">
        <action name="fileUpload" class="fileUploadAction" method="upload">
            <result  name="success" type="json">
                <param name="root">resultparam>
            result>
        action>
    package>
    
    <package name="auth" extends="struts-default" namespace="/">
        <action name="*AuthAction" class="authAction" method="{1}">
            <result  name="success">${TOJSP}result>
            <result name="redirect" type="redirect">${TOJSP}result>
        action>
    package>

    <package name="entry" extends="struts-default" namespace="/">
        <action name="*EnteryAction" class="enteryAction" method="{1}">
            <result  name="success">${TOJSP}result>
            <result name="redirect" type="redirect">${TOJSP}result>
        action>
    package>



struts>

3.4 web.xml文件配置

<web-app 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_3_0.xsd"
         version="3.0"
         metadata-complete="true">
  <display-name>Archetype Created Web Applicationdisplay-name>

    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>

    listener>
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:/spring/spring-*param-value>
    context-param>

    
    <filter>
        <filter-name>struts2filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>struts2filter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    
    <filter-mapping>
        <filter-name>openSessionInViewFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    <filter>
        <filter-name>openSessionInViewFilterfilter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilterfilter-class>
        <init-param>
            <param-name>singleSessionparam-name>
            <param-value>trueparam-value>
        init-param>
        <init-param>
            <param-name>sessionFactoryBeanNameparam-name>
            <param-value>sessionFactoryparam-value>
        init-param>
    filter>
web-app>

四、hibernate常用配置,以及出现的坑

4.1 hibernate常用的多对多配置

那两个对象来举例:用户和学院
本次系统做的是科研项目管理系统,每个用户有自己的学院,学院和用户之间是一对多关系。
用户表

@Entity(name = "Users")
public class Users {
    @Id
    private Integer userid;

    private String username;

    private String password;

    private String realName;

    private String phone;

    @JSONField(serialize = false)
    @ManyToOne(fetch = FetchType.LAZY) //用户和学院:多对一,建议不要填写cascade
    @JoinColumn(name = "fkcollid") //joinColumn 是外键对应的字段名:表示是学院中的主键
    private College college;


//省略getter和setter

}

学院:

@Entity(name = "College")
public class College {
    @Id

    private Integer collid;

    private String collegeName;

    @JSONField(serialize = false)  //mappedBy :表名由多方维护关系 “college”是Users中的字段
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "college")
    private List userses;
}

4.2 为什么用hibernate的多对多配置?

配置完成后,可以痛快的撸hql语句了。不用再进行关连查询了。直接写hql语句就可以。

4.3 常用hql语句:参考自网络

package com.tudou.hibernates.t1;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class TestGetHql {
    private static Configuration cfg = new Configuration().configure();
    private static SessionFactory fac = cfg.buildSessionFactory();
    private static Session son = fac.openSession();

    // hql普通查询 Card为类名,不是表名,可以写全路径
    public static void from() {
        String hql = "from Card";
        Query query = son.createQuery(hql);
        List cards = query.list();
        for (Card c : cards) {
            System.out.println(c.getCardName());
            System.out.println(c.getCreateDate());
        }
    }

    // 条件查询 where
    public static void where() {
        String hql = "from Card where cardName='三国无双'";
        Query query = son.createQuery(hql);
        List cardss = query.list();
        for (Card c : cardss) {
            System.out.println(c.getCardName());
            System.out.println(c.getCreateDate());
        }
    }

    // 模糊查询 like
    public static void like() {
        String hql = "from Card where cardName like '%世%'";
        Query query = son.createQuery(hql);
        List cards = query.list();
        for (Card c : cards) {
            System.out.println(c.getCardName());
            System.out.println(c.getCreateDate());
        }
    }

    // 逻辑条件查询 >
    public static void gt() {
        String hql = "from Card c where c.createDate >'2011-08-08'";
        Query query = son.createQuery(hql);
        List cards = query.list();
        for (Card c : cards) {
            System.out.println(c.getCardName());
            System.out.println(c.getCreateDate());
        }
    }

    // 逻辑条件查询 between and 此处用了别名,省略了as关键字
    public static void between() {
        String hql = "from Card c where c.createDate between '2011-08-08' and '2022-11-11'";
        Query query = son.createQuery(hql);
        List cards = query.list();
        for (Card c : cards) {
            System.out.println(c.getCardName());
            System.out.println(c.getCreateDate());
        }
    }

    // 逻辑多条件查询and
    public static void and() {
        String hql = "from Card c where c.createDate between '2011-01-08' and '2022-11-11' and c.cardName like '%世%'";
        Query query = son.createQuery(hql);
        List cards = query.list();
        for (Card c : cards) {
            System.out.println(c.getCardName());
            System.out.println(c.getCreateDate());
        }
    }

    // update 更新
    public static void update() {
        String hql = "update Card as c set c.createDate='2011-03-03' where c.cardType.cardTypeId=3";
        Query query = son.createQuery(hql);
        int num = query.executeUpdate();
        System.out.println(num + "行被更新。。。");
    }

    // delete删除
    public static void delete() {
        String hql = "delete from  Card as c where c.createDate='2011-03-04'";
        Query query = son.createQuery(hql);
        int num = query.executeUpdate();
        System.out.println(num + "行被删除。。。");
    }

    // 单个属性查询
    public static void simpleProperty() {
        String hql = "select c.cardName from  Card as c where c.cardType.cardTypeId=1";
        Query query = son.createQuery(hql);
        List name = query.list();
        for (String s : name) {
            System.out.println(s);
        }
    }

    // 多个属性查询 其中cardTypeName直接通过card对象的cardType对象获得,省去了使用普通的sql语句必须多表连接查询的麻烦
    public static void mulProperty() {
        String hql = "select c.cardName,c.cardType.cardTypeName,c.createDate from  Card as c where c.cardType.cardTypeId=1";
        Query query = son.createQuery(hql);
        List obj = query.list();
        for (Object[] o : obj) {
            System.out.println(o[0] + "\t" + o[1] + "\t" + o[2]);
        }
    }

    // 多个属性查询 面向对象方式
    public static void orientedObject() {
        String hql = "select new Card(c.cardName,c.createDate) from  Card as c";
        Query query = son.createQuery(hql);
        List cards = query.list();
        for (Card c : cards) {
            System.out.println(c.getCardName() + "\t" + c.getCreateDate());
        }
    }

    // 函数查询
    public static void function() {
        String hql = "select count(*),max(c.createDate) from  Card as c";
        Query query = son.createQuery(hql);
        List oo = query.list();
        for (Object[] o : oo) {
            System.out.println("总记录数:" + o[0] + "\t最新日期为:" + o[1]);
        }
    }

    // 排序
    public static void orderBy() {
        String hql = "from  Card as c order by c.createDate desc";
        Query query = son.createQuery(hql);
        List cards = query.list();
        for (Card c : cards) {
            System.out.println(c.getCardName() + "\t" + c.getCreateDate());
        }
    }

    // 分组
    public static void groupBy() {
        String hql = "from  Card as c group by c.cardType.cardTypeId";
        Query query = son.createQuery(hql);
        List cards = query.list();
        for (Card c : cards) {
            System.out.println(c.getCardName() + "\t" + c.getCreateDate());
        }
    }

    // 单个对象查询 呵呵,奇怪吧,对象可以查询出来
    public static void simpleObject() {
        String hql = "select c.cardType from  Card as c";
        Query query = son.createQuery(hql);
        query.setMaxResults(1);// 必须在查询之前指定,使其返回单个对象
        CardType cardType1 = (CardType) query.uniqueResult();
        System.out.println(cardType1.getCardTypeName() + "\t"
                + cardType1.getCreateDate());
    }

    // 按照命令行参数 格式为: :参数名
    public static void parameter() {
        String hql = "select c.cardType from  Card as c where c.cardType.cardTypeId=:id";
        Query query = son.createQuery(hql);
        query.setParameter("id", 1);
        query.setMaxResults(1);// 必须在查询之前指定,使其返回单个对象
        CardType cardType = (CardType) query.uniqueResult();
        System.out.println(cardType.getCardTypeName() + "\t"
                + cardType.getCreateDate());
    }

    // 按照参数位置 从0开始
    public static void parameterPosition() {
        String hql = "select c.cardType from  Card as c where c.cardType.cardTypeId=?";
        Query query = son.createQuery(hql);
        query.setParameter(0, 1);
        query.setMaxResults(1);// 必须在查询之前指定,使其返回单个对象
        CardType cardType = (CardType) query.uniqueResult();
        System.out.println(cardType.getCardTypeName() + "\t"
                + cardType.getCreateDate());
    }

    // 多个参数
    public static void mulParameter() {
        String hql = "from  Card as c where c.cardType.cardTypeId in (3,2)";
        Query query = son.createQuery(hql);
        // query.setParameterList("id", new Object[]{1,2});
        List cards = query.list();
        for (Card o : cards) {
            System.out.println(o.getCardName());
        }
    }

    // inner join 查询结果为多个对象的集合
    public static void innerJoin() {
        String hql = "from  Card as c inner join c.cardType";
        Query query = son.createQuery(hql);
        List cards = query.list();
        for (Object[] o : cards) {
            System.out.println(((Card) o[0]).getCardName() + "\t"
                    + ((CardType) o[1]).getCreateDate());
        }
    }

    // leftJoin 查询结果为多个对象的集合
    public static void leftJoin() {
        String hql = "from  CardType as c left join c.cards";
        Query query = son.createQuery(hql);
        List cards = query.list();
        for (Object[] o : cards) {
            // 由于保存卡片时在多的一方card进行操作,使用了级联。但手动插入的cardType可能没有相应的卡片
            if (o[1] != null) {// 当卡片不为空时
                System.out.println(((CardType) o[0]).getCardTypeName() + "\t"
                        + ((Card) o[1]).getCardName());
            } else {
                System.out.println(((CardType) o[0]).getCardTypeName()
                        + "\t没有相应的卡片");
            }
        }
    }

    // rightJoin 查询结果为多个对象的集合
    public static void rightJoin() {
        String hql = "from  CardType as c right join c.cards";
        Query query = son.createQuery(hql);
        List cards = query.list();
        // 插入时保证了每张卡片的类型,所以此处不用判断卡片类型是否为空
        for (Object[] o : cards) {
            System.out.println(((CardType) o[0]).getCardTypeName() + "\t"
                    + ((Card) o[1]).getCardName());
        }
    }

    // 使用子查询
    public static void childSelect() {
        String hql = "from  CardType as c where (select count(*) from c.cards)>0";
        Query query = son.createQuery(hql);
        List cards = query.list();
        for (CardType c : cards) {
            System.out.println(c.getCardTypeName() + "\t" + c.getCreateDate());
        }
    }

    // 程序入口
    public static void main(String[] args) {
        // 测试方法
        Transaction tr = son.beginTransaction();

        // update();
        mulParameter();
        tr.commit();
        son.close();
        fac.close();
    }
}

4.4 贴出一句关连查询的hql

String hql ="from Project p where 1=1";

and p.users.realName like '%张三"%'

ps:用户表和项目表相关联,直接从project中访问users即可。Hibernate自动关连
虽然性能低,但是省事啊~~~~哈哈

五.Struts2 与hibernate整合的坑

5.1 转换json串的无限循环

Hibernate采用懒加载技术,当访问一个对象的属性的时候才会发出sql语句。当两个关连对象(OneToMany 等)中有一个需要序列化时,便会关连另一个,发生无限循环。
解决方案:本次用的fastjson工具,序列化时需要加注解:

    @JSONField(serialize = false)
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "college")
    private List userses;

表示在序列化时,忽略List userses;字段。

5.2 Struts2 处理json

5.2.1.Struts2.xml

<package name="json" extends="struts-default,json-default" namespace="/">
        <action name="*JsonAction" class="jsonAction" method="{1}">
            <result  name="success" type="json">
                <param name="root">resultparam>
            result>
        action>
    package>

5.2.2 借助servlet-api来进行json处理

private void writeJson(WebResult webResult) {
        String result = JSONObject.toJSONString(webResult);
        response.setContentType("application/json;charset=utf-8");
        try {
            PrintWriter out = response.getWriter();
            out.println(result);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

5.3 Struts2 文件上传

Struts2.xml 配置


    <package name="fileupload" extends="struts-default,json-default" namespace="/">
        <action name="fileUpload" class="fileUploadAction" method="upload">
            <result  name="success" type="json">
                <param name="root">resultparam>
            result>
        action>
    package>

文件上传逻辑:

package com.web.action;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zyz on 2016/12/6.
 */
@Controller
@Scope("prototype")
public class FileUploadAction extends BaseNoAction{

    private File file;
    private String fileFileName;
    private String fileContentType;

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public String getFileContentType() {
        return fileContentType;
    }

    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }


    public void upload(){

       String rootPath= request.getServletContext().getRealPath("/uploadfiles");

       File rootFile = new File(rootPath);
       //创建跟路径
       if(!rootFile.exists()){
           rootFile.mkdirs();
       }
       String newFileName = new Date().getTime()+fileFileName.substring(fileFileName.lastIndexOf("."));

       File newFile = new File(rootFile,newFileName);

       if(newFile.exists()){
           newFile.delete();
       }
        InputStream in = null;
        OutputStream os = null;
        try{
            in = new FileInputStream(file);
            os = new FileOutputStream(newFile);
            IOUtils.copy(in,os);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        Map result = new HashMap();
        result.put("error",0);
        result.put("url","/uploadfiles/"+newFileName);
        String message = JSONObject.toJSONString(result);
        response.setContentType("application/json;charset=utf-8");
        try {
            PrintWriter out = response.getWriter();
            out.println(message);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

六、ssh中常用工具类封装

6.1 CommonDao

package com.web.common;

import com.web.dto.Page;

import java.io.Serializable;
import java.util.List;

/**
 * Created by zyz on 2016/11/16.
 */
public interface CommonDao {

    /**
     * 添加实体
     * @param t
     */
     void save(T t);

    /**
     * 添加或者保存
     * @param t
     */
    void saveOrUpdate(T t);



    /**
     * 返回一条数据
     * @param id
     * @return
     */
     T get(Class clazz, ID id);

    /**
     * 删除
     * @param t
     */
     void delete(T t);

    /**
     * 根据id删除
     * @param id
     */
    void delete(Class clazz, ID id);



    /**
     * 执行hql语句
     * @param sql
     * @param values
     */
    void executeSQL(String sql, Object... values);

    /**
     * 根据sql查找
     * @param sql
     * @param values
     * @return
     */
     T getBySql(Class clazz, String sql, Object... values);


     T  getByHql(Class clazz,String hqlString, Object... values);


    /**
     * 查询所有的实体
     * @return
     */
    public  List listAll(Class clazz);

    /**
     * 统计
     * @param sql
     * @param values
     * @return
     */
    Integer count(String sql, Object... values);

    /**
     * 有条件查询
     * @param sql
     * @param values
     * @return
     */
     List listBySql(Class clazz, String sql, Object... values);

     List listByHql(Class clazz,String hql, Object... values);

 /**
  * 分页查询
  * @param sql
  * @param pageSize
  * @param currentNum
  * @param clazz
  * @param values
  * @param 
  * @return
  */
     Page getPage(String sql, Integer pageSize, Integer currentNum, Class clazz, Object... values);
    Integer countByHql(String hql, Object... values);
     Page getPageByHQL(String hql, Integer pageSize, Integer currentNum, Class clazz, Object... values);
     T load(Class clazz, ID id);
     void update(T t);
}

6.2 commonDaoImpl

package com.web.common;

import com.web.dto.Page;
import org.hibernate.*;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;

/**
 * Created by zyz on 2016/11/16.
 */
public class CommonDaoImpl implements CommonDao {
    @Autowired
    private SessionFactory sessionFactory;

    public Session getSession(){
        return sessionFactory.getCurrentSession();
    }

    public  void save(T t) {
        this.getSession().save(t);
    }

    public  void saveOrUpdate(T t) {
        this.getSession().saveOrUpdate(t);
    }

    public  T load(Class clazz,ID id) {
        return (T) getSession().load(clazz,id);
    }

    public  void update(T t) {
        this.getSession().update(t);
    }

    public  T get(Class clazz,ID id) {

        return (T) getSession().get(clazz, id);
    }

    public  void delete(T t) {
         getSession().delete(t);
    }

    public  void delete(Class clazz,ID id) {
        delete(load(clazz,id));
    }

    public void executeHql(String hql, Object... values) {
        Query query = this.getSession().createQuery(hql);

        if(values!=null){
            for(int i = 0;ipublic void executeSQL(String sql, Object... values) {
        Query query = this.getSession().createSQLQuery(sql);

        if(values!=null){
            for(int i = 0;ipublic  T getBySql(Class clazz,String sql, Object... values) {
        Query query = this.getSession().createSQLQuery(sql);

        if(values!=null){
            for(int i = 0;ireturn  t;
    }



    public  List listAll(Class clazz) {
        return getSession().createQuery("from "+clazz.getSimpleName()).list();
    }

    public Integer count(String sql, Object... values) {
        Session session = this.sessionFactory.getCurrentSession();
        Query query = session.createSQLQuery(sql);
        if(values!=null){
            for(int i = 0;iint count = Integer.parseInt(query.uniqueResult().toString());
        return count;
    }

    public  List listBySql(Class clazz,String sql, Object... values) {
        SQLQuery query = this.getSession().createSQLQuery(sql);
        if(values!=null){
            for(int i = 0;ireturn  query.setResultTransformer(Transformers.aliasToBean(clazz)).list();
    }



    /**
     * 分页查询
     * @param sql sql
     * @param pageSize 每页大小
     * @param currentNum 当前页
     * @param clazz 转换之后的类型
     * @param values 查询条件
     * @param   返回值类型
     * @return
     */
    public  Page getPage(String sql,Integer pageSize,Integer currentNum,Class clazz,Object... values){
        String countSql =sql;
        if(sql.contains("order by"))
            countSql =sql.substring(0,sql.lastIndexOf("order by"));
        countSql="select count(*) from ( " + countSql + " ) count_temp  ";

        Integer totalNumber = this.count(countSql,values);
        SQLQuery query = this.getSession().createSQLQuery(sql);
        if(values!=null){
            for(int i = 0;i list = query.setResultTransformer(
                Transformers.aliasToBean(clazz)).setMaxResults(
                pageSize)
                .setFirstResult((currentNum - 1) * pageSize).list();

        Page page = new Page(currentNum,totalNumber,pageSize,list);

        return  page;
    }






    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }




    public  List listByHql( Class clazz,String hql, Object... values) {
        Query query = this.getSession().createQuery(hql);
        if (values != null)
        {
            for (int i = 0; i < values.length; i++)
            {
                query.setParameter(i, values[i]);
            }
        }
        return  (List)query.list();
    }

    public  T getByHql(Class clazz, String hqlString, Object... values) {
        Query query = this.getSession().createQuery(hqlString);
        if (values != null)
        {
            for (int i = 0; i < values.length; i++)
            {
                query.setParameter(i, values[i]);
            }
        }
        return  (T)query.uniqueResult();
    }

    public Integer countByHql(String hql, Object... values) {
        String countHql = "select count(*) " +hql;
        Query query = this.getSession().createQuery(countHql);
        if(values != null){
            for(int i = 0; i < values.length; i++) {
                query.setParameter(i, values[i]);
            }
        }
        return Integer.parseInt(query.uniqueResult().toString());
    }


    public  Page getPageByHQL(String hql, Integer pageSize, Integer currentNum, Class clazz, Object... values) {


        Integer totalNumber = countByHql(hql,values);
        Query query = this.getSession().createQuery(hql);
        if(values!=null){
            for(int i = 0;i list = query.setMaxResults(
                pageSize)
                .setFirstResult((currentNum - 1) * pageSize).list();

        Page page = new Page(currentNum,totalNumber,pageSize,list);

        return  page;
    }
}

6.3 BaseService

package com.web.service;

import com.web.dto.Page;

import java.io.Serializable;
import java.util.List;

/**
 * Created by zyz on 2016/11/16.
 */
public interface BaseService {

    /**
     * 添加实体
     * @param t
     */
     void save(T t);

    /**
     * 添加或者保存
     * @param t
     */
     void saveOrUpdate(T t);



    /**
     * 返回一条数据
     * @param id
     * @return
     */
     T get(Class clazz, ID id);



    /**
     * 删除
     * @param t
     */
     void delete(T t);

    /**
     * 根据id删除
     * @param id
     */
    void delete(Class clazz, ID id);


    /**
     * 执行hql语句
     * @param sql
     * @param values
     */
    void executeSQL(String sql, Object... values);

    /**
     * 根据sql查找
     * @param sql
     * @param values
     * @return
     */
     T getBySql(Class clazz, String sql, Object... values);




    /**
     * 查询所有的实体
     * @return
     */
    public  List listAll(Class clazz);

    /**
     * 统计
     * @param sql
     * @param values
     * @return
     */
    Integer count(String sql, Object... values);

    /**
     * 有条件查询
     * @param sql
     * @param values
     * @return
     */
     List listBySql(Class clazz, String sql, Object... values);

    /**
     * 分页查询
     * @param sql
     * @param pageSize
     * @param currentNum
     * @param clazz
     * @param values
     * @param 
     * @return
     */
     Page getPage(String sql, Integer pageSize, Integer currentNum, Class clazz, Object... values);


     T  getByHql(Class clazz,String hqlString, Object... values);
     List listByHql(Class clazz,String hql, Object... values);
    Integer countByHql(String hql, Object... values);
     Page getPageByHQL(String hql, Integer pageSize, Integer currentNum, Class clazz, Object... values);

     T load(Class clazz, ID id);

     void update(T t);
}

6.4 baseServiceImpl

package com.web.service.impl;

import com.web.common.CommonDao;
import com.web.dto.Page;
import com.web.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * Created by zyz on 2016/11/16.
 */
@Service
public class BaseServiceImpl implements BaseService {
    @Autowired
    private CommonDao dao;

    @Transactional(readOnly = false)
    public  void save(T t) {
        dao.save(t);
    }
    @Transactional(readOnly = false)
    public  void saveOrUpdate(T t) {
        dao.saveOrUpdate(t);
    }

    @Transactional(readOnly = true)
    public  T get(Class clazz, ID id) {
        return dao.get(clazz,id);
    }
    @Transactional(readOnly = false)
    public  void delete(T t) {
        dao.delete(t);
    }
    @Transactional(readOnly = false)
    public  void delete(Class clazz, ID id) {
            dao.delete(clazz,id);
    }


    @Transactional(readOnly = false)
    public void executeSQL(String sql, Object... values) {
        dao.executeSQL(sql, values);
    }

    @Transactional(readOnly = true)
    public  T getBySql(Class clazz,String sql, Object... values) {
        return dao.getBySql(clazz,sql, values);
    }
    @Transactional(readOnly = true)
    public  List listAll(Class clazz) {
        return dao.listAll(clazz);
    }
    @Transactional(readOnly = true)
    public Integer count(String sql, Object... values) {
        return dao.count(sql, values);
    }

    @Transactional(readOnly = true)
    public  List listBySql(Class clazz,String sql, Object... values) {
        return dao.listBySql(clazz,sql, values);
    }
    @Transactional(readOnly = true)
    public  Page getPage(String sql, Integer pageSize, Integer currentNum, Class clazz, Object... values) {
        return dao.getPage(sql, pageSize, currentNum, clazz, values);
    }
    @Transactional(readOnly = true)
    public  T getByHql(Class clazz,String hqlString, Object... values) {
        return dao.getByHql(clazz,hqlString,values);
    }
    @Transactional(readOnly = true)
    public  List listByHql(Class clazz,String hql, Object... values) {
        return dao.listByHql(clazz,hql, values);
    }
    @Transactional(readOnly = true)
    public Integer countByHql(String hql, Object... values) {
        return dao.countByHql(hql,values);
    }
    @Transactional(readOnly = true)
    public  Page getPageByHQL(String hql, Integer pageSize, Integer currentNum, Class clazz, Object... values) {
        return dao.getPageByHQL(hql,pageSize,currentNum,clazz,values);
    }
    @Transactional(readOnly = true)
    public  T load(Class clazz, ID id) {
        return dao.load(clazz,id);
    }

    public  void update(T t) {
        dao.update(t);
    }
}

6.5 BaseAction

package com.web.action;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {

    protected HttpServletRequest request = ServletActionContext.getRequest();
    protected HttpServletResponse response = ServletActionContext.getResponse();
    protected HttpSession session = ServletActionContext.getRequest()
            .getSession();

    protected final static String PREFIX = "/jsp";

    protected final static String SUBFIX = ".jsp";

    protected String TOJSP = null;

    public String getTOJSP() {
        return TOJSP;
    }

    public void setTOJSP(String tOJSP) {
        TOJSP = PREFIX + tOJSP + SUBFIX;
    }

    protected T t;

    public T getModel() {

        if (t == null) {
            Type genType = getClass().getGenericSuperclass();
            Type[] params = ((ParameterizedType) genType)
                    .getActualTypeArguments();
            Class entityClass = (Class) params[0];
            try {
                t = (T) Class.forName(entityClass.getName()).newInstance();
            } catch (Exception e) {
            }
        }
        return t;
    }

    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }

}

6.6 分页工具

package com.web.dto;


import java.util.ArrayList;
import java.util.List;

/**
 * 分页对象
 */
public class Page<T> {
    /**
     * 当前页
     */
    private Integer currentPage=1;
    /**
     * 总记录数
     */
    private Integer totalCount;
    /**
     * 每页大小
     */
    private Integer pageSize=10;
    /**
     * 每页数据
     */
    private List data;
    /**
     * 每页显示的url
     */
    private List urls;
    /**
     * 总页数
     */
    private Integer totalPage;

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public Integer getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(Integer totalCount) {
        this.totalCount = totalCount;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public List getData() {
        return data;
    }

    public void setData(List data) {
        this.data = data;
    }

    public List getUrls() {
        return urls;
    }

    public void setUrls(List urls) {
        this.urls = urls;
    }

    public Page(Integer currentPage, Integer totalCount, Integer pageSize, List data) {
        this.currentPage = currentPage;
        this.totalCount = totalCount;
        this.pageSize = pageSize;
        //总页数
        this.totalPage= totalCount%pageSize==0?totalCount/pageSize:(totalCount/pageSize+1);
        this.data = data;
        initUrls(currentPage,totalCount);
    }

    private void initUrls(Integer currentPage, Integer totalCount) {

        urls = new ArrayList();

        int start = currentPage-3<1?1:currentPage-3;

        int end = currentPage+3>totalPage?totalPage:currentPage+3;

        for (int i = start; i <=end ; i++) {
            urls.add(i+"");
        }

    }

    @Override
    public String toString() {
        return "Page{" +
                "currentPage=" + currentPage +
                ", totalCount=" + totalCount +
                ", pageSize=" + pageSize +
                ", data=" + data +
                ", urls=" + urls +
                ", totalPage=" + totalPage +
                '}';
    }
}

6.7 json 处理返回结果

package com.web.dto;


/**
 * Created by zyz on 2016/11/10.
 */
public class WebResult {

    private boolean success;

    private String message;

    private T data;

    public WebResult(boolean success, String message) {
        this.success = success;
        this.message = message;
    }

    public WebResult(boolean success, String message, T data) {
        this.success = success;
        this.message = message;
        this.data = data;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

你可能感兴趣的:(java)