Spring、hibernate以及struts2三大框架的整合

1、首先导入整合框架所需要的43个jar包:

2、配置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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:p="http://www.springframework.org/schema/p"
    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/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<!-- 基于c3p0连接池的数据源 -->
<!-- 加载外部配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>

<!-- 连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver_class}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>

<!-- hibernate的sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 数据连接 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 加载Hibernate的配置文件 -->        
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<!-- 映射文件, 可以使用*作为通配符-->
<property name="mappingLocations" value="classpath:com/hanqi/entity/*.hbm.xml"></property>
</bean>

<!-- bean -->
<bean id="StudentDAOImpl" class="com.hanqi.dao.impl.StudentDAOImpl"
p:sessionFactory-ref="sessionFactory"></bean>

<bean id="StudentServiceImpl" class="com.hanqi.service.impl.StudentServiceImpl" p:studentDAO-ref="StudentDAOImpl">
</bean>
<bean id="StudentAction" class="com.hanqi.action.StudentAction" scope="prototype" p:studentService-ref="StudentServiceImpl">
</bean>
<!-- 声明式事务 -->
<!-- 1.事务管理器 和sessionFactory关联 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 事务通知 -->
<tx:advice id="adv" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/><!-- 使用事务的方法 -->
<tx:method name="get" read-only="true"/><!-- get开头的只读方法,不使用事务 -->
<tx:method name="find" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 事务切点 -->
<aop:config>
<aop:advisor advice-ref="adv" pointcut="execution(* com.hanqi.service.*.*(..))"/>
</aop:config>
</beans>

 

 3、配置properties文件(便于对引用数据库用户名称的修改):

jdbc.driver_class=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=test0816
jdbc.password=123
jdbc.initPoolSize=1
jdbc.maxPoolSize=10

4、配置hibernate.cfg.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.default_schema">TEST0816</property>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
         <property name="hibernate.show_sql">true</property>
  <property name="hibernate.format_sql">true</property>
  <!-- 自动建表方式 -->
  <property name="hibernate.hbm2ddl.auto">update</property>
    </session-factory>
</hibernate-configuration>

5、配置struts2.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.action.extension" value="do,action,,"></constant>    
    <!-- 运行调用静态方法和静态属性 -->
    <constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>
    
  <package name="test" extends="struts-default">
  
  <action name="getStudentList" class="StudentAction" method="getStudentList">
  
  </action>
  
  </package>
  
</struts>

6、导入jquery-easyui的所有包

7、配置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">
  <display-name>Test42</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- Spring -->
  <!-- needed for ContextLoaderListener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:app.xml</param-value>
    </context-param>

    <!-- Bootstraps the root web application context before servlet initialization -->
    <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>
          <init-param>
               <param-name>forceEncoding</param-name>
               <param-value>true</param-value>
          </init-param>
     </filter>
  <filter-mapping>
          <filter-name>encodingFilter</filter-name>
          <url-pattern>/*</url-pattern>
     </filter-mapping>
     
     
     
      <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>

 

配置好的文件如下:

 

 整个的框架所需要的包和文件全部配置完毕,那么我们来拿一个项目来举个例子吧:

首先需要先建立底层的数据:

1:先建一个com.hanqi.dao的包在里面写一个dao层的接口:

package com.hanqi.dao;

import java.util.List;
import java.util.Map;

import com.hanqi.entity.Student;

public interface StudentDAO {

    List<Student> find(int page,int rows,String sort,Map<String, String>where);
    
    int getTotal(Map<String, String>where);
    
    
}

1.1:在这个包的下面再建一个com.hanqi.dao.impl包,里面写上dao的实现类:

package com.hanqi.dao.impl;

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

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.hanqi.dao.StudentDAO;
import com.hanqi.entity.Student;

public class StudentDAOImpl implements StudentDAO {

//注意sessionFactory的调用,只写一个set方法即可,下面可以调用sessionFactory
private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public List<Student> find(int page, int rows, String sort, Map<String, String> where) { List<Student> rtn=new ArrayList<Student>(); int num=(page-1)*rows; String sql="from Student where 1=1"; String sname=where.get("sname_s"); if(sname!=null&&!sname.equals("")) { sql+="and sname=:sname"; } String sclass=where.get("sclass_s"); if(sclass!=null&&!sclass.equals("")) { sql+=" and sclass=:sclass"; } //排序 if(sort!=null&&!sort.equals("")) { sql+=" order by "+sort; } Query q=sessionFactory.getCurrentSession().createQuery(sql); if(sname!=null&&!sname.equals("")) { q.setString("sname", sname); } if(sclass!=null&&!sclass.equals("")) { q.setString("sclass", sclass);; } rtn=q.setFirstResult(num). setMaxResults(rows).list(); return rtn; } @Override public int getTotal(Map<String, String> where) { int rtn=0; String sql="select count(1) from Student where 1=1"; String sname=where.get("sname_s"); if(sname!=null&&!sname.equals("")) { sql+="and sname=:sname"; } String sclass=where.get("sclass_s"); if(sclass!=null&&!sclass.equals("")) { sql+=" and sclass=:sclass"; } Query q=sessionFactory.getCurrentSession().createQuery(sql); if(sname!=null&&!sname.equals("")) { q.setString("sname", sname); } if(sclass!=null&&!sclass.equals("")) { q.setString("sclass", sclass);; } List<Object>lo=q.list(); if(lo!=null&&lo.size()>0) { rtn=Integer.parseInt(lo.get(0).toString()); } return rtn; } }

2.同样的道理我们来建service层:

先写接口再在接口的包下面写上实现的类:

package com.hanqi.service;

import java.util.List;
import java.util.Map;

import com.hanqi.entity.Student;

public interface StudentService {

    List<Student> getlist(int page,int rows,String sort,Map<String, String>where);
    
    int getTotal(Map<String, String>where);
    String getPageJSON(int page,int rows,String sort,Map<String, String>where);
}

service接口的实现类:

package com.hanqi.service.impl;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.hanqi.dao.StudentDAO;
import com.hanqi.entity.Student;
import com.hanqi.service.PageJSON;
import com.hanqi.service.StudentService;

public class StudentServiceImpl implements StudentService {
    private StudentDAO studentDAO;
    public void setStudentDAO(StudentDAO studentDAO) {
        this.studentDAO = studentDAO;
    }
    @Override
    public List<Student> getlist(int page, int rows, String sort, Map<String, String> where) {
        
        
        
        return studentDAO.find(page, rows, sort, where);
    }
    @Override
    public int getTotal(Map<String, String> where) {
        
        return studentDAO.getTotal(where);
    }
    @Override
    public String getPageJSON(int page, int rows, String sort, Map<String, String> where) {
        
        PageJSON<Student> pj=new PageJSON<>();
        
        String rtn=JSONObject.toJSONString(pj);
        
        int total=studentDAO.getTotal(where);
        if(total>0)
        {
            List<Student>ls= studentDAO.find(page, rows, sort, where);
        
            pj.setTotal(total);
            pj.setRows(ls);
            rtn=JSONObject.toJSONString(pj);
            
        }    
        return rtn;
        
    }

}

注意:service还需要一个转JSON的实现类:

package com.hanqi.service;

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

public class PageJSON<T> {
//封装Json数据格式
    private int total=0;
    
    private List<T> rows= new ArrayList<T>();

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public List<T> getRows() {
        return rows;
    }

    public void setRows(List<T> rows) {
        this.rows = rows;
    }
    
}

 

最后一步我们写上action类返回给struts.xml调用:

package com.hanqi.action;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.hanqi.service.StudentService;
public class StudentAction {

    private StudentService studentService; 
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }

    private int page;    
    private int rows;
    private String sort;
    private String order;
    private String sname_s;
    private String sclass_s;
    
    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public String getOrder() {
        return order;
    }

    public void setOrder(String order) {
        this.order = order;
    }

    public String getSname_s() {
        return sname_s;
    }

    public void setSname_s(String sname_s) {
        this.sname_s = sname_s;
    }

    public String getSclass_s() {
        return sclass_s;
    }

    public void setSclass_s(String sclass_s) {
        this.sclass_s = sclass_s;
    }

    @Override
    public String toString() {
        return "StudentAction [page=" + page + ", rows=" + rows + ", sort=" + sort + ", order=" + order + ", sname_s="
                + sname_s + ", sclass_s=" + sclass_s + "]";
    }

    //返回数据列表
    public void getStudentList()
    {
        
        //调用service
        
        try{
        if(sname_s!=null)
        {
        sname_s=new String(sname_s.getBytes("ISO-8859-1"),"UTF-8");
        }
        
        if(sclass_s!=null)
        {
        sclass_s=new String(sclass_s.getBytes("ISO-8859-1"),"UTF-8");
        }
        
        Map<String, String> where= new  HashMap<String, String>();
        
        where.put("sname_s", sname_s);
        
        where.put("sclass_s", sclass_s);
        String ls="";
        if(sort!=null&&order!=null)
        {
            ls=sort+" "+order;
        }
        String json =studentService.getPageJSON(page, rows,ls,where);
        HttpServletResponse response=ServletActionContext.getResponse();
        
        response.getWriter().print(json);
        
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
    }
    
    
}

显示层调用struts.xml的action方法:

 

 

 

posted @ 2016-12-19 21:42  -加勒比海带  阅读(379)  评论(0编辑  收藏  举报