hibernate、easyui、struts2整合

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生表</title>
<!-- 1jQuery的js包 -->
<script type="text/javascript" src="jquery-easyui-1.4.4/jquery.min.js"></script>
<!-- 2css资源 -->
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.4.4/themes/default/easyui.css">   
<!-- 3图标资源 -->
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.4.4/themes/icon.css">   
<!-- 4easyui的js包 -->
<script type="text/javascript" src="jquery-easyui-1.4.4/jquery.easyui.min.js"></script>   
  <!-- 5本地语言包 -->
<script type="text/javascript" src="jquery-easyui-1.4.4/locale/easyui-lang-zh_CN.js"></script>

</head>
<body>

<script type="text/javascript">
//把long型的日期改成yyyy-MM-dd
function getDate(date)

{
	
	//得到日期对象
	var d=new Date(date)
	
	//得到年月日
	var year=d.getFullYear();
	var month=(d.getMonth()+1);
	var day=d.getDate();
	var rtn=year +"-"+(month<10 ? "0"+month:month)+"-"+(day<10 ? "0"+day:day)
	return rtn;
}
	var type="add";
	
$(function(){

	//创建DataGrid
	$("#dg").datagrid({    
	    url:'getStudentlist.action', //数据来源
	    //冻结列
	    frozenColumns:[[{field:'id',checkbox:true},
	                    {field:'sno',title:'学生编号',width:100}]],
	    
	    //列的定义
	    columns:[[    
	        {field:'sname',title:'学生名',width:100},    
	        {field:'ssex',title:'性别',width:100},    
	        {field:'sclass',title:'班级',width:100,align:'right'},
	        {field:'sbirthday',title:'生日',width:200,align:'center',
	        	formatter: function(value,row,index){
	        		var valuee = new Date(value).toLocaleDateString();
	        		if(valuee == 'Invalid Date')
	    			{
	    				return '无' ;
	    			}
	    		else
	    			{
	    				//return valuee;
	    				return getDate(valuee);
	    			}
				}
		}
	       
	    ]],
	  
	    remoteSort:true,//是否服务器端排序	
	    sortOrder:'desc',//排序方式
	    sortName:'sno',//排序字段
	    fitColumns:false,//列自适应宽度 ,不能和冻结列同时设置为true
	    striped:true,//斑马线效果
	    idField:'sno',//主键列
	    rownumbers:true,//显示行号
	    singleSelect:false,//是否单选
	    pagination:true,//显示分页栏
	    pageList:[10,20,30,40],//每页行数选择列表
	    pageSize:10,//初始每页行数
	       
	    
	    multiSort:true,//是否允许多列排序
	    
	    toolbar:[{iconCls:'icon-search',text:'查询',
	    	handler:function(){
	    		
	    		//序列化表单查询
	    		var f=$("#form2").serialize();
	    		
	    		$("#dg").datagrid({url:"getStudentlist.action?"+f});
	    		
	    		
	    		}
		},{iconCls:'icon-add',text:'添加',
	    	handler:function(){
	    		$("#sno").textbox({readonly:false});
	    		type="add";
	    		//清除表单旧数据
	    		$("#form1").form("reset");
	    		$("#saveStu").dialog({title:'添加学生'}).dialog('open');}
		},{iconCls:'icon-edit',text:'修改',
	    	handler:function(){
	    		type="edit";
	    		//判断是否选中一条数据
	    		var data =$('#dg').datagrid('getSelected');
	    		if(data)
	    			{
	    			//alert(data);
	    			
	    			//设置字段只读
	    			$("#sno").textbox({readonly:true});
	    			
	    			$("#form1").form('reset');
	    			$("#form1").form("load",{sno:data.sno,
	    			ssex:data.ssex,sclass:data.sclass,		
	    				sname:data.sname,sbirthday:getDate(data.sbirthday)});
	    			//$('form').('load',data);
	    			$("#saveStu").dialog({title:'修改学生'}).dialog('open');
	    			}
	    		else
	    			{
	    			$.messager.show({
	    				title:'提示',
	    				msg:'请选中一条记录'			
	    			});
	    			}
	    	}
		},{iconCls:'icon-remove',text:'删除',
		    handler:function(){
		    	//判断是否选中一条数据
	    		var data =$('#dg').datagrid('getSelections');

		    	if(data.length>0)
    			{
		    	
    			$.messager.confirm("确认","确实删除吗?",function(r){
    				
    				if(r){
    					//alert("执行删除");
    					//用数组保存选中记录的主键
    					var snos=[];
    					for(var i=0;i<data.length;i++)
    						{
    						snos[i]=data[i].sno;
    						}
    					$.get("deleteStudentServlet?sno="+snos,function(rtn){
    					
    						//alert(rtn);
    						
    						var msg= eval("("+rtn+")");
    						if(msg.success)
    							{
    							$("#dg").datagrid('reload');
    							}
    						$.messager.show({title:"提示",msg:msg.message});
    						});
    					
    					}
    				else{
    					
    					}
    				
    				}
    					
    			
    			)
    			
    			}
    		else
    			{
    			$.messager.show({
    				title:'提示',
    				msg:'请选中一条记录'			
    			});
    			}
		    
		    
		    
		    
		    }
		
		}]
	}); 
	

})

</script>
<div id="search" class="easyui-panel" title="查询条件" style="heiget:100px"
data-options="{iconCls:'icon-search',collapsible:true}">
<form id="form2">

名称:<input class="easyui-textbox" id="sname_s" name="sname_s">
班级:<input class="easyui-textbox" id="sclass_s" name="sclass_s">

</form>



</div>



<table id="dg" >       
</table>

<div class="easyui-dialog" id="saveStu" style="width:400px;height:300px;top:50px;"
title="添加学生" data-options="{closed:true,modal:true,
buttons:[{text:'保存',iconCls:'icon-save',handler:function(){

$('#form1').form('submit',{
url:'SaveStudentServlet?type='+type,
onSubmit:function(){

var isValid =$(this).form('validate');					
					if(!isValid){
						$.messager.show({
							title:'消息',
							msg:'数据验证未通过'
						});
					}
					return isValid;
},
success:function(data){
				var msg=eval('('+data+')');
				if(!msg.success)
					{
						alert(msg.message);
					}
				else
				{	
					//
					$('#dg').datagrid('reload');
					$.messager.show({title:'提示',msg:msg.message});
					$('#saveStu').dialog('close');
				}
}
});
	

}},
{text:'取消',iconCls:'icon-cancel',handler:function(){
$('#saveStu').dialog('close');
}}]}">

<form action="" id="form1" method="post">
<br><br>
<table>
<tr>
<td align="right" width=30%>学号:</td>
<td><input class="easyui-textbox" id="sno" name="sno" data-options=
"{required:true,validType:'length[3,5]'}"></td>
</tr>
<tr>
<td align="right" width=30%>名称:</td>
<td><input class="easyui-textbox"  name="sname" data-options=
"{required:true,validType:'length[2,4]'}"></td>
</tr>
<tr>
<td align="right" width=30%>性别:</td>
<td><input type="radio"  name="ssex" checked
value="男">男
<input type="radio"  name="ssex" 
value="女">女</td>
</tr>
<tr>
<td align="right" width=30%>班级:</td>
<td><input class="easyui-textbox"  name="sclass" data-options=
"{required:true,validType:'length[2,4]'}"></td>
</tr>
<tr>
<td align="right" width=30%>生日:</td>
<td><input class="easyui-datebox"  name="sbirthday" ></td>
</tr>

</table>



</form>
</div>


</body>
</html>

  

package com.hanqi.dao;

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

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import com.hanqi.entity.Student;

public class StudentDAO {

	Configuration cfg=null;
	ServiceRegistry sr=null;
	SessionFactory sf=null;
	Session se=null;
	Transaction tr=null;
	public StudentDAO(){

	
	//加载配置文件
	 cfg=new Configuration().configure();
	
	//注册服务
	 sr=new StandardServiceRegistryBuilder()
			.applySettings(cfg.getProperties()).build();
	}
	//初始化
	private void init()
	{
		sf=cfg.buildSessionFactory(sr);
		se=sf.openSession();
		tr=se.beginTransaction();
	}
	//提交和释放资源
	private void destory()
	{
		tr.commit();
		se.close();
		sf.close();	
	}
	
	//添加数据
	public void insert(Student stu)
	{
		init();
		
		se.save(stu);
		destory();
		
		
	}
	//修改 数据
		public void update(Student stu)
		{
			init();
			
			se.update(stu);
			destory();
			
			
		}
	//删除
		
		public void delete(String sno)
		{
			init();
			//Student st=(Student)se.get(Student.class, sno);
			
			//se.delete(st);
			
			//SQL方式执行删除
			se.createQuery("delete from Student where sno=?")
			.setString(0, sno).executeUpdate();	
			destory();
		}
	
	//获取分页的数据集合
	public List<Student> getPageList(int page,int rows,Map<String, String> where,String sort)
	{
		System.out.println(sort+ "dao");
		List<Student> rtn=new ArrayList<Student>();
		init();
		//创建基础HQL语句
		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;
		}
		//得到HQL
		Query q=se.createQuery(sql);
		if(sname!=null&&!sname.equals(""))
		{
			q.setString("sname", sname);
		}
		if(sclass!=null&&!sclass.equals(""))
		{
			q.setString("sclass",sclass);
		}
		
		
		rtn=q.setFirstResult((page-1)*rows).
				setMaxResults(rows).list();
		
		destory();
		
		return rtn;
	}
	
	
	
	//获取数据条数
	public int getTotal(Map<String, String> where){
		int rtn=0;
		init();
		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";
		}
		
		
		
		//得到HQL
		Query q=se.createQuery(sql);
		if(sname!=null&&!sname.equals(""))
		{
			q.setString("sname", sname);
		}
		if(sclass!=null&&!sclass.equals(""))
		{
			q.setString("sclass",sclass);
		}
	
		
	
		
		//List<Object> lo=se.createQuery("select count(1)from Student").list();
		List<Object> lo=q.list();
		if(lo!=null&&lo.size()>0)
		{
			rtn=Integer.parseInt(lo.get(0).toString());
		}
		destory();
		
		return rtn;
	}
	
	
	
}

  

package com.hanqi.entity;

import java.util.Date;

public class Student {
	private String sno,sname,ssex,sclass;
	private Date sbirthday;
	public String getSno() {
		return sno;
	}
	public void setSno(String sno) {
		this.sno = sno;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public String getSsex() {
		return ssex;
	}
	public void setSsex(String ssex) {
		this.ssex = ssex;
	}
	public String getSclass() {
		return sclass;
	}
	public void setSclass(String sclass) {
		this.sclass = sclass;
	}
	public Date getSbirthday() {
		return sbirthday;
	}
	public void setSbirthday(Date sbirthday) {
		this.sbirthday = sbirthday;
	}

}

  

package com.hanqi.Service;

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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hanqi.dao.StudentDAO;
import com.hanqi.entity.Student;

public class StudentService {
	
	public void addStudeng(Student stu)
	{
		new StudentDAO().insert(stu);
	}
	
	//查询分页数据
	//返回JSON
	
	public String getPageJSON(int page,int rows,Map<String, String> where,String sort)
	{ 
		PageJson<Student>pj=new PageJson<>();
		String rtn="{'total':0,'rows':[]}";
		
		int total=new StudentDAO().getTotal(where);
		if(total>0)
		{
			System.out.println(sort+ "service");
			List<Student> ls=new StudentDAO().getPageList(page, rows,where,sort);
			
			//String ls_json=JSONArray.toJSONString(ls);
			
			//rtn="{\"total\":"+total+",\"rows\":"+ls_json+"}";
			
			pj.setTotal(total);
			pj.setRows(ls);
			rtn=JSONObject.toJSONString(pj);
			
		}
		return rtn;
	}
	public void editStu(Student stu)
	{
		new StudentDAO().update(stu);
		
	}
	
	public void delete(String sno)
	{
		new StudentDAO().delete(sno);
		
	}

}

  

package com.hanqi.action;

public class TestAction {
	
	
	private String msg;
	private String name;
	
	public String testGet()
	{
		
		System.out.println("处理get请求");
		msg="{\"success\":true,\"message\":\"666\"}";
		name="tom";
		return "success";
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getName() {
		return name;
	}

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

}

  struts2

 

 

<?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>


<package name="test" extends="json-default">

<action name="TestGet"
class="com.hanqi.action.TestAction"
method="testGet">


<!-- 返回了JSON格式的Action对象  -->
<result type="json">
	<param name="root">msg</param>


</result>

</action>


</package>
   
   <package name="stu" extends="json-default">
   <action name="getStudentlist"
   class="com.hanqi.action.StudentAction"
   method="getStudentlis-t"></action>
  
   </package>
</struts>

  

posted @ 2016-12-17 16:30  削肾客  阅读(790)  评论(0编辑  收藏  举报