Spring 4 整合 Hibernate 5 技术

在J2EE开发平台中,Spring是一种优秀的轻量级企业应用解决方案。Spring的核心技术就是IOC控制反转和AOP面向切面编程技术。

下面给出一个项目代码示例对Sping的相关技术进行讲解,该项目代码整合了最新的Spring4.2.5和Hibernate5.1技术,项目代码结构图如下:

Spring 4 整合 Hibernate 5 技术_第1张图片Spring 4 整合 Hibernate 5 技术_第2张图片Spring 4 整合 Hibernate 5 技术_第3张图片

下面给出详细配置代码

package com.kj.test.domain;

import java.io.Serializable;

/**
 * 用户实体类
 * @author KJ
 *
 */
public class User implements Serializable{

	private static final long serialVersionUID = 7178219894611819140L;
	/** 性别 */
	public static final int MAN = 1; //男
	public static final int FEMAN = 2; //女
	
	private Long id;
	/** 姓名 */
	private String name;
	/** 性别 */
	private Integer sex;
	/** 年龄 */
	private Integer age;

	public User () {
		
	}
	
	public User (Long id) {
		this.id = id;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getSex() {
		return sex;
	}

	public void setSex(Integer sex) {
		this.sex = sex;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}
	

}

package com.kj.test.domain;

/**
 * 学生实体类
 * @author KJ
 *
 */
public class Student extends User {

	private static final long serialVersionUID = 7178219894611868560L;
	
	/** 学号 */
	private String studentId;
	/** 班级 */
	private NaturalClass naturalClass;
	/**学生信息修改*/
	private StudentInfoModify studentInfoModify;
	
	public Student () {
		
	}

	public String getStudentId() {
		return studentId;
	}

	public void setStudentId(String studentId) {
		this.studentId = studentId;
	}

	public NaturalClass getNaturalClass() {
		return naturalClass;
	}

	public void setNaturalClass(NaturalClass naturalClass) {
		this.naturalClass = naturalClass;
	}

	public StudentInfoModify getStudentInfoModify() {
		return studentInfoModify;
	}

	public void setStudentInfoModify(StudentInfoModify studentInfoModify) {
		this.studentInfoModify = studentInfoModify;
	}

}

package com.kj.test.domain;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
 * 班级实体类
 * @author KJ
 *
 */
public class NaturalClass implements Serializable{

	private static final long serialVersionUID = 7178219894611819142L;

	private Long id;
	/** 名称 */
	private String name;
	/** 学生列表 */
	private Set students = new HashSet();

	public NaturalClass () {
		
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set getStudents() {
		return students;
	}

	public void setStudents(Set students) {
		this.students = students;
	}

}
package com.kj.test.domain;

import java.io.Serializable;

/**
 * 学生基本信息修改,信息修改后,需要经过管理员审核,审核通过后方可更新到Student学生实体类中
 * @author KJ
 *
 */
public class StudentInfoModify implements Serializable {
    
	private static final long serialVersionUID = -2705163477469273274L;
	/** 性别 */
	public static final int MAN = 1; //男
	public static final int FEMAN = 2; //女
	
	private Long id;
	/** 对应学生 */
	private Student student;
	/** 姓名 */
	private String name;
	/** 性别 */
	private Integer sex;
	/** 年龄 */
	private Integer age;
	/** 学号 */
	private String studentId;
	/** 班级 */
	private NaturalClass naturalClass;
	
	public StudentInfoModify() {
		
	}
	
	public StudentInfoModify(Long id) {
		this.id = id;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Student getStudent() {
		return student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getSex() {
		return sex;
	}

	public void setSex(Integer sex) {
		this.sex = sex;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getStudentId() {
		return studentId;
	}

	public void setStudentId(String studentId) {
		this.studentId = studentId;
	}

	public NaturalClass getNaturalClass() {
		return naturalClass;
	}

	public void setNaturalClass(NaturalClass naturalClass) {
		this.naturalClass = naturalClass;
	}

}
User.hbm.xml




    
        
            
        
        
        
        
    


Student.hbm.xml




	
  	
	  	
	  	
	  	
	  	
		
		
	  	
	  	
StudentInfoModify.hbm.xml




  
    
  		
  	
  	
    
    
    
    
  	
  	
	
  
NaturalClass.hbm.xml




    
        
            
        
        
        
		
			
			
		
    


上面是实体类和hibernate映射文件配置


接下面的是封装通用hibernate dao接口、service接口和分页工具类

通用泛型dao接口类:

package com.kj.test.dao;

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

import com.kj.test.util.PageResults;
import com.kj.test.util.RowMapper;
 
/**
 * @ClassName: IGenericDao
 * @Description: Dao封装接口
 * @author kj
 * @date 2016年5月2日18:00:00
 */
public interface IGenericDao {
     
    /**
     * <保存实体>
     * <完整保存实体>
     * @param t 实体参数
     */
    public abstract void save(T t);
 
    /**
     * <保存或者更新实体>
     * @param t 实体
     */
    public abstract void saveOrUpdate(T t);
 
    /**
     * 
     * <加载实体的load方法>
     * @param id 实体的id
     * @return 查询出来的实体
     */
    public abstract T load(ID id);
 
    /**
     * 
     * <查找的get方法>
     * @param id 实体的id
     * @return 查询出来的实体
     */
    public abstract T get(ID id);
 
    /**
     * 
     * @param t 实体
     * @return 是否包含
     */
    public abstract boolean contains(T t);
 
    /**
     * 
     * <删除表中的t数据>
     * @param t 实体
     */
    public abstract void delete(T t);
 
    /**
     * <根据ID删除数据>
     * @param Id 实体id
     * @return 是否删除成功
     */
    public abstract boolean deleteById(ID Id);
 
    /**
     * <删除所有>
     * @param entities 实体的Collection集合
     */
    public abstract void deleteAll(Collection entities);
     
    /**
     * <执行Hql语句>
     * @param hqlString hql
     * @param values 不定参数数组
     */
    public abstract void queryHql(String hqlString, Object... values); 
     
    /**
     * <执行Sql语句>
     * @param sqlString sql
     * @param values 不定参数数组
     */
    public abstract void querySql(String sqlString, Object... values); 
 
    /**
     * <根据HQL语句查找唯一实体>
     * @param hqlString HQL语句
     * @param values 不定参数的Object数组
     * @return 查询实体
     */
    public abstract T getByHQL(String hqlString, Object... values);
 
    /**
     * <根据SQL语句查找唯一实体>
     * @param sqlString SQL语句
     * @param values 不定参数的Object数组
     * @return 查询实体
     */
    public abstract T getBySQL(String sqlString, Object... values);
 
    /**
     * <根据HQL语句,得到对应的list>
     * @param hqlString HQL语句
     * @param values 不定参数的Object数组
     * @return 查询多个实体的List集合
     */
    public abstract List getListByHQL(String hqlString, Object... values);
 
    /**
     * <根据SQL语句,得到对应的list>
     * @param sqlString HQL语句
     * @param values 不定参数的Object数组
     * @return 查询多个实体的List集合
     */
    public abstract List getListBySQL(String sqlString, Object... values);
     
    /**
     * 由sql语句得到List
     * @param sql
     * @param map
     * @param values
     * @return List
     */
    public List findListBySql(final String sql, final RowMapper map, final Object... values);
 
    /**
     * 
     * @param t 实体
     */
    public abstract void refresh(T t);
 
    /**
     * 
     * @param t 实体
     */
    public abstract void update(T t);
 
    /**
     * <根据HQL得到记录数>
     * @param hql HQL语句
     * @param values 不定参数的Object数组
     * @return 记录总数
     */
    public abstract Long countByHql(String hql, Object... values);
     
    /**
     * 
     * @param hql HQL语句
     * @param countHql 查询记录条数的HQL语句
     * @param pageNo 下一页
     * @param pageSize 一页总条数
     * @param values 不定Object数组参数
     * @return PageResults的封装类,里面包含了页码的信息以及查询的数据List集合
     */
    public abstract PageResults findPageByFetchedHql(String hql, String countHql, int pageNo, int pageSize, Object... values);
 
}
通用泛型dao实现类
package com.kj.test.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.jdbc.Work;
import org.springframework.beans.factory.annotation.Autowired;

import com.kj.test.dao.IGenericDao;
import com.kj.test.util.PageResults;
import com.kj.test.util.RowMapper;

/**
 * @ClassName: GenericDaoImpl
 * @Description: IGenericDao实现
 * @author kj
 * @date 2016年5月2日18:00:00
 *
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class GenericDaoImpl implements IGenericDao {

	@Autowired
	private SessionFactory sessionFactory;
	protected Class entityClass;

	public GenericDaoImpl() {

	}

	protected Class getEntityClass() {
		if (entityClass == null) {
			entityClass = (Class) ((ParameterizedType) getClass()
					.getGenericSuperclass()).getActualTypeArguments()[0];
		}
		return entityClass;
	}

	/**
	 * <保存实体> <完整保存实体>
	 * 
	 * @param t
	 *            实体参数
	 * @see com.itv.launcher.util.IBaseDao#save(java.lang.Object)
	 */
	@Override
	public void save(T t) {
		this.getSession().save(t);
	}

	/**
	 * <保存或者更新实体>
	 * 
	 * @param t
	 *            实体
	 * @see com.itv.launcher.util.IBaseDao#saveOrUpdate(java.lang.Object)
	 */
	@Override
	public void saveOrUpdate(T t) {
		this.getSession().saveOrUpdate(t);
	}

	/**
	 *  <加载实体的load方法>
	 * 
	 * @param id
	 *            实体的id
	 * @return 查询出来的实体
	 * @see com.itv.launcher.util.IBaseDao#load(java.io.Serializable)
	 */
	@Override
	public T load(ID id) {
		T load = (T) this.getSession().load(getEntityClass(), id);
		return load;
	}

	/**
	 *  <查找的get方法>
	 * 
	 * @param id
	 *            实体的id
	 * @return 查询出来的实体
	 * @see com.itv.launcher.util.IBaseDao#get(java.io.Serializable)
	 */
	@Override
	public T get(ID id) {
		T load = (T) this.getSession().get(getEntityClass(), id);
		return load;
	}

	/**
	 * 
	 * 
	 * @param t
	 *            实体
	 * @return 是否包含
	 * @see com.itv.launcher.util.IBaseDao#contains(java.lang.Object)
	 */
	@Override
	public boolean contains(T t) {
		return this.getSession().contains(t);
	}

	/**
	 *  <删除表中的t数据>
	 * 
	 * @param t
	 *            实体
	 * @see com.itv.launcher.util.IBaseDao#delete(java.lang.Object)
	 */
	@Override
	public void delete(T t) {
		this.getSession().delete(t);
	}

	/**
	 * <根据ID删除数据>
	 * 
	 * @param Id
	 *            实体id
	 * @return 是否删除成功
	 * @see com.itv.launcher.util.IBaseDao#deleteById(java.io.Serializable)
	 */
	@Override
	public boolean deleteById(ID Id) {
		T t = get(Id);
		if (t == null) {
			return false;
		}
		delete(t);
		return true;
	}

	/**
	 * <删除所有>
	 * 
	 * @param entities
	 *            实体的Collection集合
	 * @see com.itv.launcher.util.IBaseDao#deleteAll(java.util.Collection)
	 */
	@Override
	public void deleteAll(Collection entities) {
		for (Object entity : entities) {
			this.getSession().delete(entity);
		}
	}

	/**
	 * <执行Hql语句>
	 * 
	 * @param hqlString
	 *            hql
	 * @param values
	 *            不定参数数组
	 * @see com.itv.launcher.util.IBaseDao#queryHql(java.lang.String,
	 *      java.lang.Object[])
	 */
	@Override
	public void queryHql(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]);
			}
		}
		query.executeUpdate();
	}

	/**
	 * <执行Sql语句>
	 * 
	 * @param sqlString
	 *            sql
	 * @param values
	 *            不定参数数组
	 * @see com.itv.launcher.util.IBaseDao#querySql(java.lang.String,
	 *      java.lang.Object[])
	 */
	@Override
	public void querySql(String sqlString, Object... values) {
		Query query = this.getSession().createSQLQuery(sqlString);
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				query.setParameter(i, values[i]);
			}
		}
		query.executeUpdate();
	}

	/**
	 * <根据HQL语句查找唯一实体>
	 * 
	 * @param hqlString
	 *            HQL语句
	 * @param values
	 *            不定参数的Object数组
	 * @return 查询实体
	 * @see com.itv.launcher.util.IBaseDao#getByHQL(java.lang.String,
	 *      java.lang.Object[])
	 */
	@Override
	public T getByHQL(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();
	}

	/**
	 * <根据SQL语句查找唯一实体>
	 * 
	 * @param sqlString
	 *            SQL语句
	 * @param values
	 *            不定参数的Object数组
	 * @return 查询实体
	 * @see com.itv.launcher.util.IBaseDao#getBySQL(java.lang.String,
	 *      java.lang.Object[])
	 */
	@Override
	public T getBySQL(String sqlString, Object... values) {
		Query query = this.getSession().createSQLQuery(sqlString);
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				query.setParameter(i, values[i]);
			}
		}
		return (T) query.uniqueResult();
	}

	/**
	 * <根据HQL语句,得到对应的list>
	 * 
	 * @param hqlString
	 *            HQL语句
	 * @param values
	 *            不定参数的Object数组
	 * @return 查询多个实体的List集合
	 * @see com.itv.launcher.util.IBaseDao#getListByHQL(java.lang.String,
	 *      java.lang.Object[])
	 */
	@Override
	public List getListByHQL(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 query.list();
	}

	/**
	 * <根据SQL语句,得到对应的list>
	 * 
	 * @param sqlString
	 *            HQL语句
	 * @param values
	 *            不定参数的Object数组
	 * @return 查询多个实体的List集合
	 * @see com.itv.launcher.util.IBaseDao#getListBySQL(java.lang.String,
	 *      java.lang.Object[])
	 */
	@Override
	public List getListBySQL(String sqlString, Object... values) {
		Query query = this.getSession().createSQLQuery(sqlString);
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				query.setParameter(i, values[i]);
			}
		}
		return query.list();
	}

	/**
	 * 由sql语句得到List
	 * 
	 * @param sql
	 * @param map
	 * @param values
	 * @return List
	 * @see com.itv.launcher.util.IBaseDao#findListBySql(java.lang.String,
	 *      com.itv.launcher.util.RowMapper, java.lang.Object[])
	 */
	@Override
	public List findListBySql(final String sql, final RowMapper map,
			final Object... values) {
		final List list = new ArrayList();
		// 执行JDBC的数据批量保存
		Work jdbcWork = new Work() {
			public void execute(Connection connection) throws SQLException {
				PreparedStatement ps = null;
				ResultSet rs = null;
				try {
					ps = connection.prepareStatement(sql);
					for (int i = 0; i < values.length; i++) {
						setParameter(ps, i, values[i]);
					}
					rs = ps.executeQuery();
					int index = 0;
					while (rs.next()) {
						Object obj = map.mapRow(rs, index++);
						list.add(obj);
					}
				} finally {
					if (rs != null) {
						rs.close();
					}
					if (ps != null) {
						ps.close();
					}
				}
			}
		};
		this.getSession().doWork(jdbcWork);
		return list;
	}

	/**
	 * 
	 * 
	 * @param t
	 *            实体
	 * @see com.itv.launcher.util.IBaseDao#refresh(java.lang.Object)
	 */
	@Override
	public void refresh(T t) {
		this.getSession().refresh(t);
	}

	/**
	 * 
	 * 
	 * @param t
	 *            实体
	 * @see com.itv.launcher.util.IBaseDao#update(java.lang.Object)
	 */
	@Override
	public void update(T t) {
		this.getSession().update(t);
	}

	/**
	 * <根据HQL得到记录数>
	 * 
	 * @param hql
	 *            HQL语句
	 * @param values
	 *            不定参数的Object数组
	 * @return 记录总数
	 * @see com.itv.launcher.util.IBaseDao#countByHql(java.lang.String,
	 *      java.lang.Object[])
	 */
	@Override
	public Long countByHql(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 (Long) query.uniqueResult();
	}

	/**
	 * 
	 * 
	 * @param hql
	 *            HQL语句
	 * @param countHql
	 *            查询记录条数的HQL语句
	 * @param pageNo
	 *            下一页
	 * @param pageSize
	 *            一页总条数
	 * @param values
	 *            不定Object数组参数
	 * @return PageResults的封装类,里面包含了页码的信息以及查询的数据List集合
	 * @see com.itv.launcher.util.IBaseDao#findPageByFetchedHql(java.lang.String,
	 *      java.lang.String, int, int, java.lang.Object[])
	 */
	@Override
	public PageResults findPageByFetchedHql(String hql, String countHql,
			int pageNo, int pageSize, Object... values) {
		PageResults retValue = new PageResults();
		Query query = this.getSession().createQuery(hql);
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				query.setParameter(i, values[i]);
			}
		}
		int currentPage = pageNo > 1 ? pageNo : 1;
		retValue.setCurrentPage(currentPage);
		retValue.setPageSize(pageSize);
		if (countHql == null) {
			ScrollableResults results = query.scroll();
			results.last();
			retValue.setTotalCount(results.getRowNumber() + 1);// 设置总记录数
		} else {
			Long count = countByHql(countHql, values);
			retValue.setTotalCount(count.intValue());
		}
		retValue.resetPageNo();
		List itemList = query.setFirstResult((currentPage - 1) * pageSize)
				.setMaxResults(pageSize).list();
		if (itemList == null) {
			itemList = new ArrayList();
		}
		retValue.setResults(itemList);

		return retValue;
	}

	/**
	 * @return the sessionFactory
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * @param sessionFactory
	 *            the sessionFactory to set
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * 
	 * @return session
	 */
	public Session getSession() {
		// 需要开启事物,才能得到CurrentSession
		return sessionFactory.getCurrentSession();
	}

	/**
	 * 
	 * 设置每行批处理参数
	 * 
	 * @param ps
	 * @param pos
	 *            ?占位符索引,从0开始
	 * @param data
	 * @throws SQLException
	 * @see [类、类#方法、类#成员]
	 */
	private void setParameter(PreparedStatement ps, int pos, Object data)
			throws SQLException {
		if (data == null) {
			ps.setNull(pos + 1, Types.VARCHAR);
			return;
		}
		Class dataCls = data.getClass();
		if (String.class.equals(dataCls)) {
			ps.setString(pos + 1, (String) data);
		} else if (boolean.class.equals(dataCls)) {
			ps.setBoolean(pos + 1, ((Boolean) data));
		} else if (int.class.equals(dataCls)) {
			ps.setInt(pos + 1, (Integer) data);
		} else if (double.class.equals(dataCls)) {
			ps.setDouble(pos + 1, (Double) data);
		} else if (Date.class.equals(dataCls)) {
			Date val = (Date) data;
			ps.setTimestamp(pos + 1, new Timestamp(val.getTime()));
		} else if (BigDecimal.class.equals(dataCls)) {
			ps.setBigDecimal(pos + 1, (BigDecimal) data);
		} else {
			// 未知类型
			ps.setObject(pos + 1, data);
		}

	}

}

service层接口

package com.kj.test.service;


import com.kj.test.dao.IGenericDao;
import com.kj.test.domain.User;


/**
 * 用户操作service接口
 * @author kj
 */
public interface IUserService extends IGenericDao{

//该接口继承了IGenericDao通用接口的所有抽象方法,另可自行定义所需方法

}

service层实现类

package com.kj.test.service.impl;


import com.kj.test.dao.impl.GenericDaoImpl;
import com.kj.test.domain.User;
import com.kj.test.service.IUserService;


/**
 * 用户操作service实现类
 * @author KJ
 *
 */
public class UserServiceImpl extends GenericDaoImpl implements IUserService {

//所有方法均已在GenericDaoImpl中实现,其中传递了泛型参数, 注意:泛型必须在编译时指定,不能在运行时再指定。


}

package com.kj.test.util;

import java.util.List;

/**
 * 分页封装类 用于做分页查询的基础类,封装了一些分页的相关属性
 * 
 * @author kj
 * @version v1.0
 * @param 
 */
public class PageResults {

	// 下一页
	private int pageNo;

	// 当前页
	private int currentPage;

	// 每页个个数
	private int pageSize;

	// 总条数
	private int totalCount;

	// 总页数
	private int pageCount;

	// 记录
	private List results;

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public int getPageNo() {
		if (pageNo <= 0) {
			return 1;
		} else {
			return pageNo > pageCount ? pageCount : pageNo;
		}
	}

	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	public List getResults() {
		return results;
	}

	public void setResults(List results) {
		this.results = results;
	}

	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 <= 0 ? 10 : pageSize;
	}

	public int getTotalCount() {
		return totalCount;
	}

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

	public void resetPageNo() {
		pageNo = currentPage + 1;
		pageCount = totalCount % pageSize == 0 ? totalCount / pageSize
				: totalCount / pageSize + 1;
	}

}

package com.kj.test.util;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * RowMapper
 * 
 * @author kj
 * @version v1.0
 */
public interface RowMapper {
	
	public Object mapRow(ResultSet rs, int index) throws SQLException;
	
}

下面给出spring的关键配置文件

web.xml



  TestSpring
  
  
  
  
  
      org.springframework.web.context.ContextLoaderListener
  
  
  
      contextConfigLocation
      classpath*:/applicationContext.xml 
  
  

  
  
   
  
  
  	MyFilter
  	com.kj.test.action.MyFilter
  	
  		encode
  		UTF-8
  	
  
  
  	MyFilter
  	/*
  
  
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  

applicationContext.xml




	
	
        
            
                classpath*:/mysql.properties
            
        
    
    
        
        
    
    
	
	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	

	
		
		
			
				com/kj/test/domain/User.hbm.xml
				com/kj/test/domain/Student.hbm.xml
				com/kj/test/domain/StudentInfoModify.hbm.xml
				com/kj/test/domain/NaturalClass.hbm.xml
			
		
		
			
				
				org.hibernate.dialect.MySQL5InnoDBDialect
				
				update
				
				false
				
				true
				true 1, false 0
				3
				pojo
				16
				20
				true
				net.sf.ehcache.hibernate.EhCacheProvider
				true
				true
				true
			
		
		
		
	
	
	
	
		
	

	
	
		
			 
			
			
			
			
			
			
			
		
	
	
	
	
		
		
	
	
	
	
		
	
	
	
	
	
		
	
	
	
	

mysql.properties

########\u6570\u636e\u5e93\u8fde\u63a5\u4fe1\u606f#######
driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/kj
username = root
password = root
initialSize = 10
maxIdle = 30
minIdle = 5
removeAbandonedTimeout = 3000
logAbandoned = false
########\u6ce8\u610f\u683c\u5f0f#######
log4j.properties
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

webBeans.xml



       
	
	
		
	

以上就是所有的配置文件和接口实现

下面提供action控制操作类代码如下:

package com.kj.test.action;

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kj.test.dao.impl.GenericDaoImpl;
import com.kj.test.domain.User;
import com.kj.test.service.IUserService;

public class UserBean implements Serializable {

	private static final long serialVersionUID = -7754405684414619372L;

	private User user;

	private IUserService userService;

	public UserBean() {
		super();
	}

	public void addUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 获取页面传递过来的参数
		String name = request.getParameter("name");
		String sex = request.getParameter("sex");
		String age = request.getParameter("age");
		User user = new User(); // 实例化用户类
		try {
			user.setAge(Integer.parseInt(age));
		} catch (Exception e) {
		}
		try {
			user.setSex(Integer.parseInt(sex));
		} catch (Exception e) {
		}
		user.setName(name);
		boolean result = false;
		try {
			userService.saveOrUpdate(user);
			result = true;
		} catch (Exception e) {
			result = false;
			System.out.println("添加用户失败");
			e.printStackTrace();
		}
		String url;
		if (result) {
			getUserList(request, response);
		} else {
			getErrorMessage(request, response);
		}
	}

	public void getUserList(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String hql = "from User";// hql查询语句
		List userList = new ArrayList();
		userList = userService.getListByHQL(hql, null);
		request.setAttribute("users", userList);
		String url = "manageUser.jsp";
		RequestDispatcher dispathcer = request.getRequestDispatcher(url);
		dispathcer.forward(request, response);

	}

	public void getErrorMessage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String url = "error.jsp";
		RequestDispatcher dispathcer = request.getRequestDispatcher(url);
		dispathcer.forward(request, response);

	}

	public User getUser() {
		return user;
	}

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

	public IUserService getUserService() {
		return userService;
	}

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

}


过滤中文字符Filter
package com.kj.test.action;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class MyFilter implements Filter {
	
	private String encode;

	public MyFilter() {
		
    }

	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		if (encode != null) {
			request.setCharacterEncoding(encode);
			response.setContentType("text/html;charset="+encode);
		}
		chain.doFilter(request, response);
		
	}

	public void init(FilterConfig fConfig) throws ServletException {
		encode = fConfig.getInitParameter("encode");
	}

}


最后给出jsp页面代码如下:

index.jsp

<%@page import="org.springframework.web.bind.ServletRequestUtils"%>
<%@page import="com.kj.test.action.UserBean"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="org.springframework.web.context.WebApplicationContext"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(application);
	UserBean userBean = (UserBean)context.getBean("userBean");
	String beanAction = ServletRequestUtils.getStringParameter(request, "beanAction","");
	if (beanAction.equals("save")) {
		userBean.addUser(request, response);
	} else if (beanAction.equals("list")) {
		userBean.getUserList(request, response);
	}
%>



	
	添加用户入口
	


	
添加用户页面
姓名:
性别: 男 
年龄:
  
manageUser.jsp

<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="org.springframework.web.bind.ServletRequestUtils"%>
<%@page import="com.kj.test.action.UserBean"%>
<%@page import="org.springframework.web.context.WebApplicationContext"%>
<%@page import="com.kj.test.domain.User"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
	pageContext.setAttribute("MAN",User.MAN);
	pageContext.setAttribute("FEMAN",User.FEMAN);
%>



	
	管理用户页面


管理用户页面
对不起,当前还没有用户记录,请先返回添加页面进行添加。
主键ID 姓名 性别 年龄

error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>



	
	错误页面


	
操作失败





你可能感兴趣的:(JAVA,Web编程宝典)