Hibernate+struts2之ajax异步实现简单的增删改查例子

  • 使用hibernate表连接
  • entity代码(代码过多就不上传了,自行封装)

Publisher实体

public class Publisher implements Serializable{
	private int id;
	private String name;
	private String address;
}

Publisher.hbm.xnl

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
	<hibernate-mapping package="entity">
	<class name="Publisher" table="t_publisher">
	   <id name="id">
	      <generator class="increment"></generator>
	   </id>
	   <property name="name"></property>
	   <property name="address"></property>
	</class>
	</hibernate-mapping>
  • hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<!-- 会话工厂 -->
	<session-factory>
		<!-- 基本连接配置 -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost/book</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		<!-- 数据库连接池配置 -->
		<property name="hibernate.c3p0.max_size">20</property>
		<property name="hibernate.c3p0.min_size">1</property>
		<property name="hibernate.c3p0.timeout">5000</property>
		<property name="hibernate.c3p0.max_statements">100</property>
		<property name="hibernate.c3p0.idle_test_period">3000</property>
		<property name="hibernate.c3p0.acquire_increment">2</property>
		<property name="hibernate.c3p0.validate">true</property>
		<!-- 数据库方言,hibernate-distribution-3.6.10.Final\project\etc\下的hibernate.properties文件中有 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- 是否需要根据配置自动生成数据表 -->
		<property name="hbm2ddl.auto">update</property>
		<!-- 是否显示发送的sql语句 -->
		<property name="show_sql">false</property>
		<!-- 是否sql格式化后输出 -->
		<property name="hibernate.format_sql">true</property>
		
		<!-- 开启二级缓存 -->
		<property name="hibernate.cache.use_second_level_cache">true</property>
		<!-- 配置二级缓存的实现类3.x版 -->	
		<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
		<!-- 配置二级缓存的实现类4.x版	
		<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
		 -->
		
		<!-- 二级缓存的管理 --> 
		<!-- 开启二级缓存的统计功能 -->
		<property name="hibernate.generate_statistics">true</property>
		<!-- 设置使用结构化方式来维护缓存项 -->
		<property name="hibernate.cache.use_structured_entries">true</property>
		
		<!-- 使用查询缓存 -->
		<property name="hibernate.cache.use_query_cache">true</property>
		 
		<!-- 需要hibernate管理的配置文件 -->
		<mapping resource="entity/Publisher.hbm.xml"/>
	</session-factory>
</hibernate-configuration>
  • utils

创建表(数据可手动添加)

public class ExportDB {
	public static void main(String[] args) {
		//读取配置文件,configure()该方法默认读取src下名为hibernate.cfg.xml
		Configuration cfg=new Configuration().configure();
		//将类导成表
		SchemaExport se=new SchemaExport(cfg);
		//参数,显示一些脚本等信息,true即可
		se.create(true, true);
	}
}

HibernateUtils

public class HibernateUtils {
	private static SessionFactory sessionFactory;
	static{
		try {
			sessionFactory=new Configuration().configure().buildSessionFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static SessionFactory getSessionFactory(){
		return sessionFactory;
	}
	public static Session getSession(){
		return sessionFactory.openSession();
	}
	public static void closeSession(Session session){
		if(session!=null&&session.isOpen()){
			session.close();
		}
	}
}
  • dao

PublisherDao

public class PublisherDao {
	private static PublisherDao instances=new PublisherDao();
	public static PublisherDao getInstances() {
		return instances;
	}
	public void add(Publisher publisher){
		Session session=HibernateUtils.getSession();
		session.beginTransaction();
		
		session.save(publisher);
		
		session.getTransaction().commit();
		HibernateUtils.closeSession(session);
	}
	public void upd(Publisher publisher){
		Session session=HibernateUtils.getSession();
		session.beginTransaction();
		
		session.update(publisher);
		
		session.getTransaction().commit();
		HibernateUtils.closeSession(session);
	}
	public Publisher findOne(int id){
		Publisher publisher=new Publisher(); 
		Session session=HibernateUtils.getSession();
		
		//建议使用select
		//session.load(publisher, id);
		publisher=(Publisher)session.createQuery("from Publisher p where p.id=?")
			.setInteger(0, id)
			.list()
			.get(0);
		
		HibernateUtils.closeSession(session);
		return publisher;
	}
	public List findAll(){
		List list=new ArrayList();
		Session session=HibernateUtils.getSession();
		
		list=session.createQuery("from Publisher").list();
		
		HibernateUtils.closeSession(session);
		return list;
	}
	public void del(int id){
		Session session=HibernateUtils.getSession();
		session.beginTransaction();
		
		session.delete(findOne(id));
		
		session.getTransaction().commit();
		HibernateUtils.closeSession(session);
	}
}
  • gson

GsonUtils

public class GsonUtils {
	private static Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
	public static String object2json(Object obj){
		return gson.toJson(obj);
	}
	public static Object json2Object(String json,Class c){
		return gson.fromJson(json, c);
	}
	public static List json2List(String json,TypeToken tt){
		return gson.fromJson(json, tt.getType());
	}
}
  • action

BaseAction

/**
 * action基类
 * @author zy
 * 封装了常用的方法,以解耦方式获得常用对象
 */
public class BaseAction extends ActionSupport {
	/**
	 * get request obj
	 * @return
	 */
	public Map<String, Object> getRequest(){
		//得到上下文
		ActionContext ac=ActionContext.getContext();
		return (Map<String, Object>)ac.get("request");
	}
	/**
	 * get session obj
	 * @return
	 */
    public Map<String, Object> getSession(){
    	ActionContext ac=ActionContext.getContext();
    	return ac.getSession();
    }
    /**
	 * get application obj
	 * @return
	 */
	public Map<String, Object> getApplication() {
		ActionContext ctx = ActionContext.getContext();
		return ctx.getApplication();
	}
	/**
	 * 获得Response对象,只能用耦合形式,Response可以获得out对象,用于ajax
	 * @return
	 */
	public HttpServletResponse getResponse() {
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		return ServletActionContext.getResponse();
	}
	/**
	 * 获得out对象
	 * @return
	 * @throws IOException
	 */
	public PrintWriter getOut() throws IOException {
		return getResponse().getWriter();
	}
	
}

PublisherAction

public class PublisherAction extends BaseAction{
	private List list;
	private Publisher publisher=new Publisher();
	private String name;
	private String address;
	private int id;
	public String list() throws Exception {
		list=PublisherDao.getInstances().findAll();
		String json=GsonUtils.object2json(list);
		getOut().println(json);
		return null;
	}
	public String add() throws Exception {
		publisher.setName(name);
		publisher.setAddress(address);
		PublisherDao.getInstances().add(publisher);
		return null;
	}
	public String toUpd() throws Exception {
		publisher=PublisherDao.getInstances().findOne(id);
		String json=GsonUtils.object2json(publisher);
		getOut().println(json);
		return null;
	}
	public String del() throws Exception {
		PublisherDao.getInstances().del(id);
		return null;
	}
	public String upd() throws Exception {
		publisher.setId(id);
		publisher.setName(name);
		publisher.setAddress(address);
		PublisherDao.getInstances().upd(publisher);
		return null;
	}
	//---
	public List getList() {
		return list;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public void setList(List list) {
		this.list = list;
	}
	public Publisher getPublisher() {
		return publisher;
	}
	public void setPublisher(Publisher publisher) {
		this.publisher = publisher;
	}
}
  • index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    <script type="text/javascript" src="jquery-1.8.3.js"></script>
    <script type="text/javascript">
     
    $(function(){
			showList();
			//添加
			$("#btnAdd").click(function(){
				$.post("PublisherAction_add",{
					name:$("#name").val(),
					address:$("#address").val()
				},function(data){
					showList();
				});
			});
			//修改
			$("#btnUpd").click(function(){
				$.post("PublisherAction_upd",{
					id:$("#id").val(),
					name:$("#name").val(),
					address:$("#address").val()
				},function(data){
					showList();
				});
			});
		});
		//显示列表
		function showList(){
			$("#mytable").html("");
			$.get("PublisherAction_list",null,function(data){
				var html="<tr><td>编号</td><td>名称</td><td>地址</td><td>操作</td></tr><tr>";
				for(var i=0;i<data.length;i++){
					html+="<td>"+data[i].id+"</td>";
					html+="<td>"+data[i].name+"</td>";
					html+="<td>"+data[i].address+"</td>";
					html+="<td><a href='javascript:toUpd("+data[i].id+");'>编辑</a>|<a href='javascript:del("+data[i].id+");'>删除</a></td>";
					html+="</tr>";
				}
				$("#mytable").append(html);
			},"json");
		}
		//编辑
		function toUpd(id){
			$.get("PublisherAction_toUpd?id="+id,null,function(data){
				$("#id").val(data.id);
				$("#name").val(data.name);
				$("#address").val(data.address);
			},"json");
		}
		//删除
		function del(id){
			$.get("PublisherAction_del?id="+id,null,function(data){
				showList();
			});
		}
		
    </script>
    
  </head>
  
  <body>
  <input type="hidden" id="id"/>
	名称:<input type="text" id="name"/><p/>
	地址:<input type="text" id="address"/><p/>
	<button id="btnAdd">添加</button>
	<button id="btnUpd">修改</button>
	<hr/>
    <table id="mytable" border="1" width="50%"></table>
   
  </body>
</html>
  • strurs.xml
<struts>
	<constant name="struts.i18n.encoding" value="utf-8"></constant>
	<package name="books" extends="struts-default">
		<action name="PublisherAction_*" class="action.PublisherAction" method="{1}"></action>
	</package>
</struts>

web.xml

<!-- struts的核心过滤器
	2.1.6之后换成org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
	 -->
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
<!--为了方便过滤所有/*  -->
		<url-pattern>/*</url-pattern>
	</filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

所用到的包

jquery-1.8.3.js

猜你喜欢

转载自blog.csdn.net/zyupupup/article/details/81068075