SSH整合(附上IbaseDao和分页查询)

第一步:导入jar包

需要准备以下jar包

ssh:jar包链接:hibernate4.3版本,spring4.3版本,struts2.0版本 ------------------http://pan.baidu.com/s/1nvfo4el

tomcat8.0的jar包链接-------------------------http://pan.baidu.com/s/1o78cy9c


web.xml配置

xml version="1.0" encoding="UTF-8"?>
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    
        openSessionInView
        org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
    
    
        openSessionInView
        /*
    

    
        struts2
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    
    
        struts2
        /*
    

    
        contextConfigLocation
        classpath:spring.xml
    
    
        org.springframework.web.context.ContextLoaderListener
    



第二步:model层用hibernate;

1.建立hibernate.xml

xml version='1.0' encoding='utf-8'?>
hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

  
    name="connection.url">jdbc:mysql://localhost:3306/test
    name="connection.driver_class">com.mysql.jdbc.Driver
      class="com.iotek.entity.District"/>
      resource="com/iotek/entity/District.hbm.xml"/>
      class="com.iotek.entity.Street"/>
      resource="com/iotek/entity/Street.hbm.xml"/>
    class="com.iotek.entity.User"/>
    resource="com/iotek/entity/User.hbm.xml"/>
      
    

    
    
  




2.User.hbm.xml


xml version='1.0' encoding='utf-8'?>
hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

    name="com.iotek.entity.User" table="user" schema="test">
        name="userId">
            name="userId" sql-type="int(11)"/>
            
            class="identity"/>
        
        name="userName">
            name="userName" sql-type="varchar(40)" length="40"/>
        
        name="userPwd">
            name="userPwd" sql-type="varchar(40)" length="40"/>
        
    


3.实体类

@Entity
public class User {
    private Integer userId;
    private String userName;
    private String userPwd;

    @Id
    @Column(name = "userId", nullable = false)
    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    @Basic
    @Column(name = "userName", nullable = false, length = 40)
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Basic
    @Column(name = "userPwd", nullable = false, length = 40)
    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (userId != null ? !userId.equals(user.userId) : user.userId != null) return false;
        if (userName != null ? !userName.equals(user.userName) : user.userName != null) return false;
        if (userPwd != null ? !userPwd.equals(user.userPwd) : user.userPwd != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = userId != null ? userId.hashCode() : 0;
        result = 31 * result + (userName != null ? userName.hashCode() : 0);
        result = 31 * result + (userPwd != null ? userPwd.hashCode() : 0);
        return result;
    }
}



第三步.Dao,Service,用spring来管理

spring配置


xml version="1.0" encoding="UTF-8"?>
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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"

       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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd">

       <context:component-scan base-package="com.iotek"/>

       
       id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
              name="driverClass" value="com.mysql.jdbc.Driver"/>
              name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
              name="user" value="root"/>
              name="password" value="12345"/>
              name="initialPoolSize" value="3"/>
              name="maxPoolSize" value="100"/>
              name="maxStatements" value="1000"/>
              name="acquireIncrement" value="5"/>
       

       
       id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
              name="dataSource" ref="dataSource"/>
              name="hibernateProperties">
                     
                            key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect
                            key="hibernate.show_sql">true
                            key="hibernate.format_sql">true
                     
              
              name="mappingDirectoryLocations">
                     
                            classpath:com/iotek/entity/
                     
              

       

       
       id="ht" class="org.springframework.orm.hibernate4.HibernateTemplate">
              name="sessionFactory" ref="sessionFactory"/>
       

       
       id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
              name="sessionFactory" ref="sessionFactory"/>
              name="dataSource" ref="dataSource"/>
       

       

       
       <tx:advice id="txAdvice" transaction-manager="txManager">
              <tx:attributes>
                     <tx:method name="get*" read-only="true"/>
                     <tx:method name="*" read-only="false"/>
              tx:attributes>
       tx:advice>

       
       <aop:config>
              <aop:pointcut id="pt" expression="execution(* com.iotek.service.*.*(..))"/>
              <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
       aop:config>


顶级接口,IBaseDao

public interface IBaseDAO<T> {
    public List<T> getAll(String hql);
    public List<T> getAll(Class<T> clazz);
    public T getEntityById(Class<T> clazz, Serializable id);
    public List<T> getEntityByParams(String hql, Object... params);
    public T getUniqueEntityByParam(final String hql, final Object... params);
    public void save(T obj);
    public void update(T t);
    public void delete(String hql, Serializable id);
    public PageBean<T> getPageBean(final int currentPage, final int pageSize,
                                   final String hql, final Object... params);
}
顶级公共接口实现类

/*创建顶级接口*/
public class BaseDAOImpl<T> implements IBaseDAO<T> {
    @Resource(name="ht")
    private HibernateTemplate ht;

    public void setHt(HibernateTemplate ht) {
        this.ht = ht;
    }
   /*通过外面传入hql语句查询所有*/
    @Override
    public List<T> getAll(String hql) {
        return (List<T>)ht.find(hql);
    }

    /*通过传入类class文件查询所有*/
    @Override
    public List<T> getAll(Class<T> clazz) {
        String hql = "from "+clazz.getSimpleName();
        return (List<T>) ht.find(hql);
    }

    /*通过id来查*/
    @Override
    public T getEntityById(Class<T> clazz,Serializable id) {
        return  ht.get(clazz,id);
    }

    /*通过hql语句和传入参数查询*/
    @Override
    public List<T> getEntityByParams(String hql, Object... params) {
        return  (List<T>)ht.find(hql,params);
    }

    /*增加*/
    @Override
    public void save(T obj) {
        ht.save(obj);
    }

    /*更改*/
    @Override
    public void update(T obj) {
        ht.update(obj);
    }

    /*删除,通过ht未定义的语句,需要回调方法*/
    @Override
    public void delete(final String hql,final Serializable id) {
        ht.execute(new HibernateCallback<T>() {
            @Override
            public T doInHibernate(Session session) throws HibernateException{
                Query query = session.createQuery(hql);
                query.setParameter(0,id);
                query.executeUpdate();
                return null;
            }
        });
    }

    /*分页查询*/
    @Override
    public PageBean<T> getPageBean(int currentPage, int pageSize, String hql, Object... params) {
        final PageBean<T> pageBean = new PageBean<T>();
        pageBean.setCurrentPage(currentPage);
        pageBean.setPageSize(pageSize);

        ht.execute(new HibernateCallbackT>>() {

            @Override
            public List<T> doInHibernate(Session session) throws HibernateException{
                Query query = session.createQuery(hql);

                if(params!=null){
                    for(int i=0;i<params.length;i++){
                        query.setParameter(i,params[i]);
                    }
                }

                ScrollableResults scroll = query.scroll();
                scroll.last();
                int totalCount = scroll.getRowNumber()+1;
                pageBean.calcTotalPage(totalCount);

                query.setFirstResult(pageBean.getBeginIndex());
                query.setMaxResults(pageSize);
                List<T> entityList = query.list();
                pageBean.setDataList(entityList);
                return entityList;
            }

        });

        return pageBean;

    }

    /*返回一条语句进行查询*/
    @Override
    public T getUniqueEntityByParam(final String hql, final Object... params) {
        T obj = ht.execute(new HibernateCallback<T>() {

            @Override
            public T doInHibernate(Session session) throws HibernateException{
                Query query = session.createQuery(hql);
                for(int i=0;i<params.length;i++){
                    query.setParameter(i,params[i]);
                }
                return (T)query.uniqueResult();
            }

        });
        return obj;
    }
}

dao层子接口(写上子接口私有方法)

public interface IUserDAO extends IBaseDAO {
    public User getUserByNameAndPwd(User user);
    public PageBean getPageBean(int currentPage, int PageSize);
    public List getAllByHql();
    public List getAllByClass();

}

daoImpl实现类方法

@Repository("userDAO")
public class UserDAOImpl extends BaseDAOImpl implements IUserDAO {
    @Resource(name="ht")
    private HibernateTemplate ht;

    public HibernateTemplate getHt() {
        return ht;
    }

    public void setHt(HibernateTemplate ht) {
        this.ht = ht;
    }

    @Override
    public User getUserByNameAndPwd(User user) {
        String hql = "from User user where user.userName=? and user.userPwd=?";
        List userList = (List) ht.find(hql,user.getUserName(),user.getUserPwd());
        return userList.size()>0?userList.get(0):null;
    }

    @Override
    public PageBean getPageBean(int currentPage, int pageSize) {
        return super.getPageBean(currentPage,pageSize,"from User");
    }

    @Override
    public List getAllByHql() {
        return super.getAll("from User");
    }

    @Override
    public List getAllByClass() {
        return super.getAll(User.class);
    }
}


.service层

public interface IUserService {
    /*登录业务*/
    public boolean isLogin(User user);
    /*分页查询*/
    public PageBean getPageBean(int currentPage, int pageSize);
    /*查询所有的业务*/
    public List getAllByHql();
    public List getAllByClass();
}

serviceImpl层

@Service("userService")
public class UserServiceImpl implements IUserService {
    @Resource(name="userDAO")
    private IUserDAO userDAO;

    public IUserDAO getUserDAO() {
        return userDAO;
    }

    public void setUserDAO(IUserDAO userDAO) {
        this.userDAO = userDAO;
    }

    @Override
    public boolean isLogin(User user) {
        return userDAO.getUserByNameAndPwd(user) == null ? false : true;
    }

    @Override
    public PageBean getPageBean(int currentPage, int pageSize) {
        return userDAO.getPageBean(currentPage,pageSize);
    }

    @Override
    public List getAllByHql() {
        return userDAO.getAllByHql();
    }

    @Override
    public List getAllByClass() {
        return userDAO.getAllByClass();
    }
}


第四步:controller层

struts.xml配置

xml version="1.0" encoding="UTF-8"?>

struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">


    name="default" namespace="/" extends="struts-default">
        
        name="*Test" class="TestAction" method="{1}">
            name="{1}">/{1}.jsp
        

        name="*User" class="UserAction" method="{1}">
            name="{1}_success">/hello.jsp
            name="{1}_faile">/index.jsp
            name="user_page">/userPage.jsp
            name="query_all">/query_all.jsp
        

        name="*District" class="DistrictAction" method="{1}">
            name="detail">/district_detail.jsp
        
    




controller层

@Controller("UserAction")
public class UserAction {
    private User user;
    private int currentPage;
    private int pageSize;
    @Resource(name="userService")
    private IUserService userService;

    public User getUser() {
        return user;
    }

    public int getCurrentPage() {
        return currentPage;
    }

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

    public int getPageSize() {
        return pageSize;
    }

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

    public void setUser(User user) {
        this.user = user;
    }

    public IUserService getUserService() {
        return userService;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    public String login(){
        boolean flag = userService.isLogin(user);
        if(flag == true){
            return "login_success";
        }
        else{
            return "login_faile";
        }
    }

    public String page(){
        PageBean userPageBean = userService.getPageBean(currentPage,pageSize);
        ActionContext.getContext().getSession().put("userPageBean",userPageBean);
        return "user_page";
    }

    public String allSql(){
        List userList=userService.getAllByHql();
        HttpServletRequest request= ServletActionContext.getRequest();
        HttpSession session=request.getSession();
        session.setAttribute("userList",userList);
        return "query_all";
    }


    public String allClass(){
        List userList=userService.getAllByClass();
       ActionContext.getContext().getSession().put("userList",userList);
        return "query_all";
    }
    
}

第五步.View层(jsp页面)

userPage

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":"
            + request.getServerPort() + path + "/";
%>


    href="<%=basePath%>">
    


<s:iterator value="#session.userPageBean.dataList" id="user">
    <s:property value="#user.id"/>     
    <s:property value="#user.userName"/>
s:iterator> href="pageUser.action?currentPage=${sessionScope.userPageBean.prePage}">上一页   <s:textfield name="currentPage" value=""/> ${sessionScope.userPageBean.currentPage} / ${sessionScope.userPageBean.totalPage}  href="pageUser.action?currentPage=${sessionScope.userPageBean.nextPage}">下一页

query_all.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>


    </span>Title<span style="color:#e8bf6a;">


<s:iterator value="#session.userList" id="user">
    <s:property value="#user.userName">s:property>
s:iterator>










你可能感兴趣的:(【Java】)