EasyUIStruts2Hibernatespring 框架整合
Posted 丶疏影横斜
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EasyUIStruts2Hibernatespring 框架整合相关的知识,希望对你有一定的参考价值。
经历了四个月的学习,中间过程曲折离奇,好在坚持下来了,也到了最后框架的整合中间过程也只有自己能体会了。
接下来开始说一下整合中的问题和技巧:
1, jar包导入
c3p0(2个)、jdbc(1个)、spring(15个)、Hibernate(10个)、Struts2(13个)、json(3个)
及EasyUI的jquery包
2, 在src目录下新建一个实体类的包,并新建一个实体类
package com.han.entity; import java.util.Date; public class Student { private String sno ; private String sname ; private String ssex ; private Date sbirthday ; private String sclass ; /*省略set、get方法*/ }
3, 生成hibernate.cfg.xml的文件,并生成实体类的 Student.hbm.xml
值得提的是cfg.xml中并不需要连接数据库的驱动、用户名、用户密码及文件的映射,因为在spring中我们会添加这些配置
4, 这里我们用的是连接池连接数据库
db.properties的配置(放在src下面):
5, 接下来我们在app.xml配置中声明事务及事务的切点
6, 我们建如下包,并分别在对应包中建新的接口和实现类
7, 接下来我们开始Struts2的配置
这里要注意的是Action的name这里要与网页中发送地址对应,class对应的则是aap.xml中的id名,这里整合spring的话class不能写类的限定名,不然会有空指针异常,method就是Action这个类中的方法名
8, 这里整合spring所以我们都定义了接口及其实现类
9, 在service层中我们定义了一个dao接口的实例化作为属性,并设置了set方法
10, 到这里基本的环境搭建就完成了
下面是每个层的具体方法:
dao层接口
package com.hanqi.dao; import java.util.List; import java.util.Map; import com.han.entity.Student; public interface StudentDAO { //获取分页数据集合 List<Student> find(int page, int rows, String sort, Map<String, String> map) ; //获取数据条数 int findTotal(Map<String, String> map) ; //添加数据 void add(Student stu) ; }
dao层接口的实现类impl
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.han.entity.Student; import com.hanqi.dao.StudentDAO; 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> map) { List<Student> list = new ArrayList<>() ;//定义list变量并实例化 String sql = "from Student where 1=1 " ; //创建基础HQL语句 String snames = map.get("snames") ;//接收参数 if(snames != null && !snames.equals(""))//判断参数 { sql += "and sname =:snames " ;// } String sclasss = map.get("sclasss") ; if(sclasss != null && !sclasss.equals("")) { sql += "and sclass =:sclasss " ; } if(sort != null && !sort.equals("")) { sql += "order by " + sort ; } Query qu = sessionFactory.getCurrentSession().createQuery(sql) ; if(snames != null && !snames.equals("")) { qu.setString("snames", snames) ; } if(sclasss != null && !sclasss.equals("")) { qu.setString("sclasss", sclasss) ; } //System.out.println(sql); list = qu.setMaxResults(rows)//每页行数 .setFirstResult((page-1)*rows)//起始页码 .list() ; return list ; } @Override public int findTotal(Map<String, String> map) { int rtn = 0 ;//定义变量并赋值 String sql = "select count(1) from Student where 1=1 " ; String snames = map.get("snames") ;//接收参数 if(snames != null && !snames.equals(""))//判断参数 { sql += "and sname =:snames " ;// } String sclasss = map.get("sclasss") ; if(sclasss != null && !sclasss.equals("")) { sql += "and sclass =:sclasss " ; } Query qu = sessionFactory.getCurrentSession().createQuery(sql) ; //获取Query对象 if(snames != null && !snames.equals("")) { qu.setString("snames", snames) ; } if(sclasss != null && !sclasss.equals("")) { qu.setString("sclasss", sclasss) ; } List<Object> list = qu.list() ;//定义list变量并实例化 if(list != null && list.size() > 0 )//判断获取的集合非空及长度 { rtn = Integer.parseInt(list.get(0).toString()) ;//给变量rtn赋值 } return rtn ;//返回变量值 } @Override public void add(Student stu) { sessionFactory.getCurrentSession().save(stu) ; } }
service层接口
package com.hanqi.service; import java.util.List; import java.util.Map; import com.han.entity.Student; public interface StudentService { //获取分页数据集合 public List<Student> getList(int page, int rows, String sort, Map<String, String> map) ; //获取数据条数 int getTotal(Map<String, String> map) ; //查询分页数据,并返回JSON String getPageJSON(int page, int rows, String sort, Map<String, String> map) ; //添加数据 void insert(Student stu) ; }
service层接口的实现类impl
package com.hanqi.service.impl; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.hanqi.service.PageJSON; import com.han.entity.Student; import com.hanqi.dao.StudentDAO; 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> map) { return studentDAO.find(page, rows, sort, map) ; } @Override public int getTotal(Map<String, String> map) { return studentDAO.findTotal(map) ; } @Override public String getPageJSON(int page, int rows, String sort, Map<String, String> map) { PageJSON<Student> pj = new PageJSON<Student>() ; String rtn = "{\\"total\\":0,\\"rows\\":[ ]}" ;//转义字符 int total = studentDAO.findTotal(map) ; if(total > 0) { List<Student> list = studentDAO.find(page, rows, sort, map) ; //将List集合转为JSON集合 String json_list = JSONArray.toJSONString(list) ; pj.setRows(list); pj.setTotal(total); rtn = JSONObject.toJSONString(pj) ; //转义字符返回复合类型的JSON字符串 //rtn = "{\\"total\\":"+total+",\\"rows\\":"+json_list+"}" ; } return rtn ; } @Override public void insert(Student stu) { studentDAO.add(stu); } }
action类(这里用的域模型来接受从页面传递过来的参数,即直接定义名字相同的属性值,并生成set、get方法)
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.han.entity.Student; import com.hanqi.service.StudentService; public class StudentAction { private StudentService studentService ; public void setStudentService(StudentService studentService) { this.studentService = studentService; } public StudentService getStudentService() { return studentService; } private int page ; private int rows ; private String sort ; private String order ; private String snames ; private String sclasss ; @Override public String toString() { return "StudentAction [page=" + page + ", rows=" + rows + ", sort=" + sort + ", order=" + order + ", snames=" + snames + ", sclasss=" + sclasss + "]"; } 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 getSnames() { return snames; } public void setSnames(String snames) { this.snames = snames; } public String getSclasss() { return sclasss; } public void setSclasss(String sclasss) { this.sclasss = sclasss; } public void getStudentList() { System.out.println(this); try{ //查询参数 if(snames != null) { snames =new String(snames.getBytes("ISO-8859-1"),"UTF-8") ;//转码 } if(sclasss != null) { sclasss =new String(sclasss.getBytes("ISO-8859-1"),"UTF-8") ;//转码 } System.out.println("snames = "+ snames ); System.out.println("sclasss = " + sclasss ); Map<String, String> map = new HashMap<String, String>() ; map.put("snames", snames) ; map.put("sclasss", sclasss) ; // map.put("snames","刘四") ; // map.put("sclasss", "11111") ; String ls = "" ; System.out.println(order +"=" +sort); if(sort != null && order != null) { ls = sort + " " + order ; } String json_list = studentService.getPageJSON(page, rows, ls, map) ; //返回数据 //System.out.println("json = "+json_list); HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json_list) ; }catch(Exception e) { e.printStackTrace(); } } //接收参数 private String sno ; private String sname ; private String ssex ; private String sclass ; private String 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 String getSbirthday() { return sbirthday; } public void setSbirthday(String sbirthday) { this.sbirthday = sbirthday; } public void insert() throws IOException { if(sno != null ) { String msg ; try { Student stu = new Student(); stu.setSclass(sclass); stu.setSname(sname); stu.setSno(sno); stu.setSsex(ssex); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); stu.setSbirthday(sdf.parse(sbirthday)); studentService.insert(stu); msg = "{\'success\':true,\'message\':\'保存成功\'}" ; } catch(Exception e) { msg = "{\'success\':false,\'message\':\'保存失败\'}"; System.out.println("yichanghaha"); } HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("UTF-8"); response.getWriter().write(msg); } else { String msg = "{\'success\':false,\'message\':\'访问异常\'}" ; HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("UTF-8"); response.getWriter().write(msg); } } }
同时在上面的action数据往前台html传送时我们为了返回json格式的字符串更加的方便灵活,我们定义了一个获取json
字符串格式的泛型辅助类,代码如下:
package com.hanqi.service; import java.util.ArrayList; import java.util.List; public class PageJSON<T> { private int total = 0 ; private List<T> rows = new ArrayList<T>() ; public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public List<T> getRows() { return rows; } public void setRows(List<T> rows) { this.rows = rows; } }
Struts.xml
<?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.ognl.allowStaticMethodAccess" value="true"></constant> <constant name="struts.action.extension" value="do,action,,"></constant> <package name="stu" extends="struts-default"> <action name="studentAction" class="studentAction" method="getStudentList"> <!-- name 对应的是网页中的post/get请求 --> <!-- 这里的class来源是spring配置中的id名 --> <!-- method 方法是Action这个类中的方法 --> </action> <action name="addstudentAction" class="studentAction" method="insert"> <!-- name 对应的是网页中的post/get请求 --> <!-- 这里的class来源是spring配置中的id名 --> <!-- method 方法是Action这个类中的方法 --> </action> </package> </struts>
app.xml
<?xml version="1.0" encoding="UTF-8"?> <beans 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:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd 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-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd"> <!-- 基于c3p0连接池的数据源 --> <!-- 加载外部配置文件 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver_class}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean> <!-- Hibernate 的 SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!-- 加载Hibernate的配置文件 --> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <!-- 映射文件, 可以使用*作为通配符--> <property name="mappingLocations" value="classpath:com/han/entity/*.hbm.xml" ></property> </bean> <!-- bean --> <!-- DAO --> <bean id="studentDAOImpl" class="com.hanqi.dao.impl.StudentDAOImpl" p:sessionFactory-ref="sessionFactory"></bean> <!-- Service --> <bean id="studentServiceImpl" class="com.hanqi.service.impl.StudentServiceImpl" p:studentDAO-ref="studentDAOImpl"></bean> <!-- 配置Action --> <!-- Action 的实例不能是单例的 --> <bean id="studentAction" class="com.hanqi.action.StudentAction" scope="prototype" p:studentService-ref="studentServiceImpl"></bean> <!-- 声明式事务 --> <!-- 1.事务管理器 和sessionFactory关联 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 事务通知 --> <tx:advice id="adv" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*"/><!-- 使用事务的方法 --> <tx:method name="get" read-only="true"/> <!-- get开头的只读方法,不使用事务 --> <tx:method name="find" read-only="true"/> <!-- find开头的只读方法,不使用事务 --> </tx:attributes> </tx:advice> <!-- 事务切点 --> <aop:config>