1.前期准备:jar包(c3p0、jdbc ,各个框架)
web.xml文件:spring的 转码的,和Struts2的过滤器
<?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>L1219_SSHE</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 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:app.xml</param-value> </context-param> <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>
Hibernate.cfg.xml的文件,并生成实体类的映射文件,
注意:现在用spring来生成映射文件。
spring的app.xml的配置,用的连接池来连接数据库
Hibernate的各种配置,sessionFactory声明当前session,通过sessionFactory.getCurrentSession()来获取,(DAO层)
声明事务
然后见如下图所示的各种包,在包中实现各接口以及实现类(impl)实现类中主要是个方法(增删改查)
Struts2的配置,主要是Action的方法的配置,(增删改查的action)
注意:name是页面发送的get或post请求的URL地址,class是spring中对应的id, method是Action类中的方法名
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); void insert(Student stu);//添加 void update(Student stu);//修改 void delete(String sno);//删除 }
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 { 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) { //创建基础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 = sessionFactory.getCurrentSession().createQuery(sql); if(sname != null && !sname.equals("")) { q.setString("sname",sname); } if(sclass != null && !sclass.equals("")) { q.setString("sclass",sclass); } List<Student> rtn = new ArrayList<Student>(); rtn = q.setMaxResults(rows)//每页行数 .setFirstResult((page-1)*rows).list();//起始页码 return rtn; } @Override public int getTotal(Map<String, String> where) { int rtn= 0; //创建基础HQL语句 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";//and前面加空格 } String sclass = where.get("sclass_s"); if(sclass != null && !sclass.equals("")) { sql += " and sclass = :sclass"; } //得到HQL Query q = sessionFactory.getCurrentSession().createQuery(sql); if(sname != null && !sname.equals("")) { q.setString("sname",sname); } if(sclass != null && !sclass.equals("")) { q.setString("sclass",sclass); } //获取Query对对象,定义集合并实例化 List<Object> lo = q.list(); if(lo != null && lo.size() > 0) { rtn = Integer.parseInt(lo.get(0).toString());//转换成int并赋值 } return rtn; } //添加数据 @Override public void insert(Student stu) { sessionFactory.getCurrentSession().save(stu); } //修改数据 @Override public void update(Student stu) { sessionFactory.getCurrentSession().update(stu); } //删除 @Override public void delete(String sno) { //Student st = (Student)se.get(Student.class, sno); //se.delete(st); //HQL方式执行删除 sessionFactory.getCurrentSession().createQuery("delete Student where sno =?") .setString(0, sno) .executeUpdate(); } }
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); // void insert(Student stu); // void update(Student stu); // void delete(String sno); //service的添加 void addStudent(Student stu); //修改 void editStudent(Student stu); //删除 void deleteStudent(String sno); }
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) { // TODO 自动生成的方法存根 return studentDAO.find(page, rows, sort, where); } @Override public int getTotal(Map<String, String> where) { // TODO 自动生成的方法存根 return studentDAO.getTotal(where); } @Override public String getPageJSON(int page, int rows, String sort, Map<String, String> where) { PageJSON<Student> pj = new PageJSON<Student>();//引用泛型类 String rtn = JSONObject.toJSONString(pj); //"{total:0,rows:[]}";//空的JSON对象 int total = studentDAO.getTotal(where);//符合查询条件的总条数 if(total>0) { List<Student> ls = studentDAO.find(page, rows,sort,where); //String ls_json = JSONArray.toJSONString(ls);//转成JSON格式 pj.setTotal(total); pj.setRows(ls); rtn = JSONObject.toJSONString(pj); //转义字符,转成JSON读取的格式 //rtn = "{\"total\":"+total+",\"rows\":"+ls_json+"}" ; } return rtn; } // @Override // public void insert(Student stu) { // // TODO 自动生成的方法存根 // studentDAO.insert(stu); // } // // // @Override // public void update(Student stu) { // // TODO 自动生成的方法存根 // studentDAO.update(stu); // // } // // // @Override // public void delete(String sno) { // // TODO 自动生成的方法存根 // studentDAO.delete(sno); // } @Override public void addStudent(Student stu) { // TODO 自动生成的方法存根 studentDAO.insert(stu); } @Override public void editStudent(Student stu) { // TODO 自动生成的方法存根 studentDAO.update(stu); } @Override public void deleteStudent(String sno) { // TODO 自动生成的方法存根 studentDAO.delete(sno); } }
Action
package com.hanqi.action; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.hanqi.entity.Student; import com.hanqi.service.StudentService; public class StudentAction { private StudentService studentService; HttpServletResponse response = ServletActionContext.getResponse(); 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; //添加的参数 private String sno ; private String sname ; private String ssex; private String sbirthday; private String sclass; //接受参数表示添加或修改 private String type ; public String getType() { return type; } public void setType(String type) { this.type = type; } 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 getSbirthday() { return sbirthday; } public void setSbirthday(String sbirthday) { this.sbirthday = sbirthday; } public String getSclass() { return sclass; } public void setSclass(String sclass) { this.sclass = sclass; } public StudentService getStudentService() { return studentService; } 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() { System.out.println("this="+this); //调用serIve 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"); } System.out.println("sname_s="+sname_s+"sclass_s="+sclass_s); //对条件进行打包 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;//注意加空格 } //System.out.println("ls="+ls); String json = studentService.getPageJSON(page, rows,ls,where); System.out.println("json="+json); //返回数据 HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("UTF-8"); response.setContentType("text/json"); response.getWriter().println(json); } catch(Exception e) { e.printStackTrace(); } } //添加 public void getSave() { HttpServletResponse response = ServletActionContext.getResponse(); String msg = "{‘success‘:true,‘message‘:‘保存成功‘}"; if(sno != null && type != null) { try { Student stu = new Student(); stu.setSno(sno); stu.setSclass(sclass); stu.setSname(sname); stu.setSsex(ssex); if(sbirthday !=null && !sbirthday.trim().equals("")) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); stu.setSbirthday(sdf.parse(sbirthday)); } if(type.equals("add"))//根据type判断按钮调用方法 { studentService.addStudent(stu); } else { studentService.editStudent(stu); } } catch(Exception e) { msg = "{‘success‘:false,‘message‘:‘访问失败‘}"; } try { response.getWriter().print(msg); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } else { msg = "{‘success‘:false,‘message‘:‘访问异常‘}"; try { response.getWriter().print(msg); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } }
删除的action
package com.hanqi.action; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.hanqi.service.StudentService; public class DeleteStudentAction { private StudentService studentService; HttpServletResponse response = ServletActionContext.getResponse(); public void setStudentService(StudentService studentService) { this.studentService = studentService; } //接受删除的参数 private String snos; public String getSnos() { return snos; } public void setSnos(String snos) { this.snos = snos; } //删除 public void getDelete() { String msg = "{‘success‘:true,‘message‘:‘删除成功‘}"; if(snos != null ) { System.out.println("snos=="+snos); try { String [] sno = snos.split(",");//分割 for(String s : sno) { studentService.deleteStudent(s); } } catch(Exception e) { msg = "{‘success‘:false,‘message‘:‘访问异常‘}"; } } else { msg = "{‘success‘:false,‘message‘:‘删除失败‘}"; } try { response.getWriter().print(msg); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } }
页面显示层
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <!-- 顺序不可以乱 --> <!-- 1.jQuery的js包 --> <script type="text/javascript" src="jquery-easyui-1.4.4/jquery.min.js"></script> <!-- 2.css资源 --> <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"> <!-- 4.easyui的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(){ $("#hh").datagrid({ url:‘studentAction.action‘,//Struts.xml的name //冻结列 frozenColumns:[[ {field:‘id‘,checkbox:true},//复选框 {field:‘sno‘,title:‘学号‘,width:100} ]], //定义列 列配置对象 columns:[[ {field:‘sname‘,title:‘姓名‘,width:200,align:‘center‘}, {field:‘ssex‘,title:‘性别‘,width:200,align:‘center‘, formatter: function(value,row,index){ if(value == ‘男‘||value == ‘f‘) { return ‘男‘; } else { return ‘女‘; } }, styler:function(value,row,index){ if(value==‘男‘|| value==‘f‘) { return ‘background-color:#ccccff;color:red;‘; } } }, {field:‘sbirthday‘,title:‘生日‘,width:200,align:‘right‘, formatter:function(value, row, index){ if(value && value !="") { return getDate(value); } else { return ‘无‘; } } }, {field:‘sclass‘,title:‘班级‘,width:200,align:‘center‘} ]] , fitColumns:true, //列自适应宽度,不能和冻结列同时设置为true striped:true, //斑马线 idField:‘sno‘, //主键列 rownumbers:true, //显示行号 singleSelect:false, //是否单选 pagination:true, //分页栏 pageList:[8,16,24,32] , //每页行数选择列表 pageSize:8 , //初始每页行数 remoteSort:true , //是否服务器端排序,设成false才能客户端排序 sortName:‘sno‘,//排序字段,基于服务器端排序 sortOrder:‘desc‘,//排序顺序 //顶部工具栏 toolbar:[ { iconCls:‘icon-search‘, text:‘查询‘, handler:function(){ //序列化查询表单 var f = $("#form2").serialize(); //alert(f); $("#hh").datagrid({url:"studentAction.action?"+f})},//把查询条件带给servlet }, { iconCls:‘icon-add‘, text:‘添加‘, handler:function(){ type ="add"; //$("#sno").textbox({readonly:false}); //清除表单旧数据 $("#form1").form("reset");//重置表单数据 $("#saveStu").dialog(‘open‘); } }, { iconCls:‘icon-edit‘, text:‘修改‘, handler:function(){ type ="edit"; //判断是否选中一条数据 var data = $("#hh").datagrid(‘getSelected‘); if(data) { //alert(date); //设置主键字段只读 $("#sno").textbox({readonly:true}); $("#form1").form("reset");//重置表单数据 $(‘#form1‘).form(‘load‘,{sno:data.sno, sname:data.sname, ssex:data.ssex, sbirthday:getDate(data.sbirthday), sclass:data.sclass }); //$("#form1").form() $("#saveStu").dialog({title:‘修改学生‘}).dialog(‘open‘); } else { $.messager.show({ title:‘提示‘, msg:‘请选中一条记录‘ }); } } }, { iconCls:‘icon-delete‘, text:‘删除‘, handler:function(){ //getSelections返回所有被选中的行,当没有记录被选中的时候将返回一个空数组。 var data = $("#hh").datagrid(‘getSelections‘); if(data.length > 0) { //alert("条数="+data.length); $.messager.confirm( ‘确认‘,‘您确认要删除吗?‘,function(r){ if(r) { //alert("fff="+data[0].sno); //使用数组保存选中数据的记录主键 var snos=[]; for(var i = 0 ; i<data.length;i++) { snos [i]= data[i].sno; } //把要删除的主键传递给Servlet $.get("deleteStudent.action?snos="+snos, function(rtn){ //alert(rtn); //解析 var ms = eval("("+ rtn +")"); if(ms.success) { //若删除成功刷新页面 $("#hh").datagrid(‘reload‘); } $.messager.show({ title:‘提示‘, msg:ms.message }); }); } } ); } else { $.messager.show({ title:‘提示‘, msg:‘请选择一条要删除的数据‘ }) } } } ], }); }) </script> <div id="search" class="easyui-panel" title="查询条件" style="height:80px;width:100%" data-options="{ iconCls:‘icon-search‘, collapsible:true}"> <form id="form2"><br> <table border="0" style="margin-left:30px"> <tr> <td>姓名:<input class="easyui-textbox" id="sname_s" name="sname_s"></td> <td>班级:<input class="easyui-textbox" id="sclass_s" name="sclass_s"></td> </tr> </table> </form> </div> <table id="hh"></table> <div class="easyui-dialog" id="saveStu" style="width:400px; height:300px" title="添加学生" data-options="{ closed:true, modal:true, buttons:[{ text:‘保存‘, iconCls:‘icon-save‘, handler:function(){ $(‘#form1‘).form(‘submit‘,{ url:‘saveStudent.action?type=‘+ type, // onSubmit:function(){ var isValid = $(this).form(‘validate‘); if(!isValid) { $.messager.show({ title:‘消息‘, msg:‘数据验证未通过‘ }); } return isValid; // 返回false终止表单提交 }, success:function(data){ var msg = eval(‘(‘+ data +‘)‘);//eval是js的方法 if(!msg.success) { alert(msg.message); } else { $(‘#hh‘).datagrid(‘load‘); $.messager.show({ title:‘消息‘, msg:‘数据验证通过,保存成功‘ }); $(‘#saveStu‘).dialog(‘close‘); } } }); } }, { text:‘取消‘, iconCls:‘icon-cancel‘, handler:function(){$(‘#saveStu‘).dialog(‘close‘)}, }] }"> <form action="" id="form1" method="post"><br><br> <table border="0" width=100%> <tr> <td align="right" width="30%">学号:</td> <td> <input class="easyui-textbox" id="sno" name="sno" data-options="required:true,validType:‘length[3,8]‘"> </td> </tr> <tr> <td align="right" width="30%">姓名:</td> <td> <input class="easyui-textbox" id="sname" name="sname" data-options="required:true,validType:‘length[2,3]‘"> </td> </tr> <tr> <td align="right" width="30%">性别:</td> <td> <input type="radio" name="ssex" value="男" checked>男 <input type="radio" name="ssex" value="女">女 </td> </tr> <tr> <td align="right" >生日:</td> <td> <input class="easyui-datebox" id="sbirthday" name="sbirthday" data-options="required:false,"> </td> </tr> <tr> <td align="right" >班级:</td> <td> <input class="easyui-textbox" id="sclass" name="sclass" data-options="required:true,validType:‘length[5,5]‘"> </td> </tr> </table> </form> </div> </body> </html>
时间: 2024-10-13 16:02:44