diff --git a/Hibernate/README.md b/Hibernate/README.md new file mode 100644 index 0000000..ff1a382 --- /dev/null +++ b/Hibernate/README.md @@ -0,0 +1,21 @@ +Hibernate的一些知识点与实例: + +myHibWebDemo:[Hibernate]构架知识点详细解析 +知识点详解,加上一个测试实例! + + + + + + + + + + + + + + + + + diff --git a/Hibernate/myHibWeb/.classpath b/Hibernate/myHibWeb/.classpath new file mode 100644 index 0000000..96c5a3c --- /dev/null +++ b/Hibernate/myHibWeb/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Hibernate/myHibWeb/.mymetadata b/Hibernate/myHibWeb/.mymetadata new file mode 100644 index 0000000..2618529 --- /dev/null +++ b/Hibernate/myHibWeb/.mymetadata @@ -0,0 +1,13 @@ + + + + + + + diff --git a/Hibernate/myHibWeb/.project b/Hibernate/myHibWeb/.project new file mode 100644 index 0000000..092d7d2 --- /dev/null +++ b/Hibernate/myHibWeb/.project @@ -0,0 +1,58 @@ + + + myHibWeb + + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + com.genuitec.eclipse.j2eedt.core.WebClasspathBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + com.genuitec.eclipse.j2eedt.core.J2EEProjectValidator + + + + + com.genuitec.eclipse.j2eedt.core.DeploymentDescriptorValidator + + + + + org.eclipse.wst.validation.validationbuilder + + + + + com.genuitec.eclipse.ast.deploy.core.DeploymentBuilder + + + + + + com.genuitec.eclipse.ast.deploy.core.deploymentnature + org.eclipse.jem.workbench.JavaEMFNature + com.genuitec.eclipse.j2eedt.core.webnature + org.eclipse.jdt.core.javanature + org.eclipse.wst.jsdt.core.jsNature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.common.modulecore.ModuleCoreNature + + diff --git a/Hibernate/myHibWeb/.settings/.jsdtscope b/Hibernate/myHibWeb/.settings/.jsdtscope new file mode 100644 index 0000000..252e54f --- /dev/null +++ b/Hibernate/myHibWeb/.settings/.jsdtscope @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/Hibernate/myHibWeb/.settings/org.eclipse.jdt.core.prefs b/Hibernate/myHibWeb/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..dc1a260 --- /dev/null +++ b/Hibernate/myHibWeb/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Mon Aug 29 14:58:21 CST 2016 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/Hibernate/myHibWeb/.settings/org.eclipse.wst.common.component b/Hibernate/myHibWeb/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..5b80a0b --- /dev/null +++ b/Hibernate/myHibWeb/.settings/org.eclipse.wst.common.component @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Hibernate/myHibWeb/.settings/org.eclipse.wst.common.project.facet.core.xml b/Hibernate/myHibWeb/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..5a88726 --- /dev/null +++ b/Hibernate/myHibWeb/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Hibernate/myHibWeb/.settings/org.eclipse.wst.jsdt.ui.superType.container b/Hibernate/myHibWeb/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/Hibernate/myHibWeb/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/Hibernate/myHibWeb/.settings/org.eclipse.wst.jsdt.ui.superType.name b/Hibernate/myHibWeb/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/Hibernate/myHibWeb/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/Hibernate/myHibWeb/README.md b/Hibernate/myHibWeb/README.md new file mode 100644 index 0000000..5183239 --- /dev/null +++ b/Hibernate/myHibWeb/README.md @@ -0,0 +1 @@ +利用Hibernate进行单表的增删改查 \ No newline at end of file diff --git a/Hibernate/myHibWeb/WebRoot/META-INF/MANIFEST.MF b/Hibernate/myHibWeb/WebRoot/META-INF/MANIFEST.MF new file mode 100644 index 0000000..254272e --- /dev/null +++ b/Hibernate/myHibWeb/WebRoot/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/demo/DemoServlet.class b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/demo/DemoServlet.class new file mode 100644 index 0000000..87642ce Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/demo/DemoServlet.class differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/demo/dao/DemoJdbcDao.class b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/demo/dao/DemoJdbcDao.class new file mode 100644 index 0000000..a56f322 Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/demo/dao/DemoJdbcDao.class differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/demo/service/DemoServiceImpl.class b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/demo/service/DemoServiceImpl.class new file mode 100644 index 0000000..9f16217 Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/demo/service/DemoServiceImpl.class differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.class b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.class new file mode 100644 index 0000000..3b4a02e Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.class differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.hbm.xml b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.hbm.xml new file mode 100644 index 0000000..baca9dc --- /dev/null +++ b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.hbm.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/hib/HibernateSessionFactory.class b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/hib/HibernateSessionFactory.class new file mode 100644 index 0000000..5c5aa2b Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/hib/HibernateSessionFactory.class differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/utils/BaseServlet.class b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/utils/BaseServlet.class new file mode 100644 index 0000000..777de43 Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/cn/hncu/utils/BaseServlet.class differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/hibernate.cfg.xml b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/hibernate.cfg.xml new file mode 100644 index 0000000..b3d2b8d --- /dev/null +++ b/Hibernate/myHibWeb/WebRoot/WEB-INF/classes/hibernate.cfg.xml @@ -0,0 +1,46 @@ + + + + + + + com.mysql.jdbc.Driver + + + jdbc:mysql://127.0.0.1:3306/hib + + root + 1234 + + + org.hibernate.dialect.MySQLDialect + + + + true + + + 50 + + + 23 + + + false + + + true + + utf-8 + + + + + \ No newline at end of file diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/antlr-2.7.7.jar b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/antlr-2.7.7.jar new file mode 100644 index 0000000..5e5f14b Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/antlr-2.7.7.jar differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/classmate-1.3.0.jar b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/classmate-1.3.0.jar new file mode 100644 index 0000000..049b63f Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/classmate-1.3.0.jar differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/dom4j-1.6.1.jar b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/dom4j-1.6.1.jar new file mode 100644 index 0000000..c8c4dbb Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/dom4j-1.6.1.jar differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/geronimo-jta_1.1_spec-1.1.1.jar b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/geronimo-jta_1.1_spec-1.1.1.jar new file mode 100644 index 0000000..ee9963d Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/geronimo-jta_1.1_spec-1.1.1.jar differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/hibernate-commons-annotations-5.0.1.Final.jar b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/hibernate-commons-annotations-5.0.1.Final.jar new file mode 100644 index 0000000..82e425d Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/hibernate-commons-annotations-5.0.1.Final.jar differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/hibernate-core-5.1.1.Final.jar b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/hibernate-core-5.1.1.Final.jar new file mode 100644 index 0000000..bbd38a3 Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/hibernate-core-5.1.1.Final.jar differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/hibernate-jpa-2.1-api-1.0.0.Final.jar b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/hibernate-jpa-2.1-api-1.0.0.Final.jar new file mode 100644 index 0000000..e2f2c59 Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/hibernate-jpa-2.1-api-1.0.0.Final.jar differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/jandex-2.0.0.Final.jar b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/jandex-2.0.0.Final.jar new file mode 100644 index 0000000..d24086a Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/jandex-2.0.0.Final.jar differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/javassist-3.20.0-GA.jar b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/javassist-3.20.0-GA.jar new file mode 100644 index 0000000..0f1ff72 Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/javassist-3.20.0-GA.jar differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/jboss-logging-3.3.0.Final.jar b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/jboss-logging-3.3.0.Final.jar new file mode 100644 index 0000000..ea45d4d Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/jboss-logging-3.3.0.Final.jar differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.39-bin.jar b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.39-bin.jar new file mode 100644 index 0000000..dac6e14 Binary files /dev/null and b/Hibernate/myHibWeb/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.39-bin.jar differ diff --git a/Hibernate/myHibWeb/WebRoot/WEB-INF/web.xml b/Hibernate/myHibWeb/WebRoot/WEB-INF/web.xml new file mode 100644 index 0000000..34c4d5d --- /dev/null +++ b/Hibernate/myHibWeb/WebRoot/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + + + DemoServlet + cn.hncu.demo.DemoServlet + + + DemoServlet + /DemoServlet + + + + index.jsp + + diff --git a/Hibernate/myHibWeb/WebRoot/index.jsp b/Hibernate/myHibWeb/WebRoot/index.jsp new file mode 100644 index 0000000..d461c86 --- /dev/null +++ b/Hibernate/myHibWeb/WebRoot/index.jsp @@ -0,0 +1,13 @@ +<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> +<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + + + + + 利用Hibernate进行单表的增删改查 + + + + + + diff --git a/Hibernate/myHibWeb/WebRoot/js/ajax.js b/Hibernate/myHibWeb/WebRoot/js/ajax.js new file mode 100644 index 0000000..26bb44a --- /dev/null +++ b/Hibernate/myHibWeb/WebRoot/js/ajax.js @@ -0,0 +1,65 @@ +String.prototype.trim=function(){ + var p = /^\s*/; + //\s 匹配任何空白字符,包括空格、制表符、换页符等等 + var str = this.replace(p, ""); + p=/\s*$/; + str = str.replace(p, ""); + return str; +}; + +function Ajax(){ + var xmlhttp; + //1 创建一个ajax对象 + if(window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari + xmlhttp = new XMLHttpRequest(); + }else{// code for IE6, IE5 + xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); + } + //url为请求的链接或文件。 + //succ是status返回为200后运行的函数。 + //failure是status返回不为200后运行的函数。 + + this.get=function(url,succ,failure){ + //2 设置通讯方式和地址 + xmlhttp.open("GET", url, true);//异步--多线程 + //3 设置访问成功后的 js对象(回调函数) + xmlhttp.onreadystatechange=function(){ + if(xmlhttp.readyState==4){//服务器的响应消息接收完毕 + if(xmlhttp.status==200){//服务器正常响应 + var txt = xmlhttp.responseText;//后台的响应信息 + succ(txt); + }else{ + if(failure){ + failure(xmlhttp.status); + } + } + } + }; + //4发送---Get方式,没有参数(请求体) ---数据在请求地址中 + xmlhttp.send(); + }; + + this.post= function(url,data,succ, failure){ + //2 设置通讯方式和地址 + xmlhttp.open("POST",url,true);//异步--多线程 + //3 设置访问成功后的 js对象(回调函数) + xmlhttp.onreadystatechange=function(){ + if(xmlhttp.readyState==4){//服务器的响应消息接收完毕 + if(xmlhttp.status==200){//服务器正常响应 + var txt = xmlhttp.responseText;//后台的响应信息 + succ(txt); + }else{ + if(failure){ + failure(xmlhttp.status); + } + } + } + }; + //4设置请求头 + xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); + + //5发送---Post方式,有参数(请求体) <---数据 ※ + xmlhttp.send(data); + }; + +} \ No newline at end of file diff --git a/Hibernate/myHibWeb/WebRoot/jsps/demo.jsp b/Hibernate/myHibWeb/WebRoot/jsps/demo.jsp new file mode 100644 index 0000000..c2d3726 --- /dev/null +++ b/Hibernate/myHibWeb/WebRoot/jsps/demo.jsp @@ -0,0 +1,156 @@ +<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> +<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> + + + + +利用Hibernate进行单表的增删改查 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
学号姓名年龄学院编号操作
${stud.sId}${stud.sName}${stud.sAge}${stud.deptId}删除 +
+ +

添加一个学生信息

+
+ + + + + + + + + + + + + + + + + + + + +
学号* +
姓名* +
年龄* +
学院编号* +
+
+ + +
+

学生查询

+ + + + + + + + + + + + + + + + +
学号
姓名
学院编号
+ + +

查询结果

+ + + + + + + + + + + + + + + + + +
学号姓名年龄学院编号操作
${stud.sId}${stud.sName}${stud.sAge}${stud.deptId} + 删除 +
+
+ + + + diff --git a/Hibernate/myHibWeb/myHibWeb.zip b/Hibernate/myHibWeb/myHibWeb.zip new file mode 100644 index 0000000..ec46c07 Binary files /dev/null and b/Hibernate/myHibWeb/myHibWeb.zip differ diff --git a/Hibernate/myHibWeb/src/cn/hncu/demo/DemoServlet.java b/Hibernate/myHibWeb/src/cn/hncu/demo/DemoServlet.java new file mode 100644 index 0000000..2615208 --- /dev/null +++ b/Hibernate/myHibWeb/src/cn/hncu/demo/DemoServlet.java @@ -0,0 +1,75 @@ +package cn.hncu.demo; + + +import java.io.PrintWriter; +import java.util.Date; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import cn.hncu.demo.service.DemoServiceImpl; +import cn.hncu.domain.Student; +import cn.hncu.utils.BaseServlet; + +public class DemoServlet extends BaseServlet { + DemoServiceImpl service = new DemoServiceImpl(); + @Override + public void execute(HttpServletRequest req, HttpServletResponse resp) + throws Exception { + List list = service.queryAllStudents(); + req.getSession().setAttribute("list", list); + + req.getRequestDispatcher("/jsps/demo.jsp").forward(req, resp); + } + + public void delStudent(HttpServletRequest req, HttpServletResponse resp) + throws Exception { + String studId = req.getParameter("studId"); + Student stud = new Student(); + + stud.setsId(studId); + + service.delStudent(stud); + + resp.sendRedirect(getServletContext().getContextPath()+"?time="+(new Date().getTime())); + } + + public void addStudent(HttpServletRequest req, HttpServletResponse resp) + throws Exception { + String studId = req.getParameter("studId"); + String studName = req.getParameter("studName"); + String strAge = req.getParameter("age"); + Integer age = Integer.valueOf(strAge); + String deptId = req.getParameter("deptId"); + Student stud = new Student(); + stud.setsId(studId); + + //System.out.println(studName);//正常汉字 + + stud.setsName(studName); + stud.setsAge(age); + stud.setDeptId(deptId); + + service.addStudent(stud); + + resp.sendRedirect(getServletContext().getContextPath()); + } + + public void queryStudents(HttpServletRequest req, HttpServletResponse resp) + throws Exception { + String studId = req.getParameter("studId"); + String studName = req.getParameter("studName"); + String deptId = req.getParameter("deptId"); + Student stud = new Student(); + stud.setsId(studId); + stud.setsName(studName); + stud.setDeptId(deptId); + + List qlist = service.queryStudents(stud); + req.getSession().setAttribute("qlist", qlist); + PrintWriter out = resp.getWriter(); + out.print("1"); //坑:不能使用out.println("1") + } + +} diff --git a/Hibernate/myHibWeb/src/cn/hncu/demo/dao/DemoJdbcDao.java b/Hibernate/myHibWeb/src/cn/hncu/demo/dao/DemoJdbcDao.java new file mode 100644 index 0000000..07634cf --- /dev/null +++ b/Hibernate/myHibWeb/src/cn/hncu/demo/dao/DemoJdbcDao.java @@ -0,0 +1,80 @@ +package cn.hncu.demo.dao; + +import java.util.List; + +import org.hibernate.HibernateException; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.Transaction; + +import cn.hncu.domain.Student; +import cn.hncu.hib.HibernateSessionFactory; + +public class DemoJdbcDao { + public List queryAllStudents() { + Session s = HibernateSessionFactory.getSession(); + Query query = s.createQuery("from Student"); + List list = query.list(); + return list; + } + + public void delStudent(Student stud) { + Session s = HibernateSessionFactory.getSession(); + try { + Transaction tran = s.beginTransaction(); + System.out.println("stud:"+stud); + s.delete(stud); +// Student stud2 = new Student(); +// stud2.setStudId("S001"); +// s.save(stud2); + tran.commit(); + } catch (HibernateException e) { + //tran.rollback();//可以不写,内部会进行回滚 + System.out.println("抓到异常..."); + } + + } + + public void addStudent(Student stud) { + Session s = HibernateSessionFactory.getSession(); + Transaction tran = s.beginTransaction(); + try { + s.saveOrUpdate(stud); + tran.commit(); + } catch (HibernateException e) { + } + } + + public List queryStudents(Student stud) { + System.out.println(stud); + boolean f1=false,f2=false,f3=false; + Session s = HibernateSessionFactory.getSession(); + String hql = "from Student s where 1=1"; + + if(stud.getsId()!=null && stud.getsId().trim().length()>0){ + hql = hql + " and s.sId=:sId"; + f1=true; + } + if(stud.getsName()!=null && stud.getsName().trim().length()>0){ + hql = hql + " and s.sName like :sName"; + f2=true; + } + if(stud.getDeptId()!=null && stud.getDeptId().trim().length()>0){ + hql = hql + " and s.deptId=:deptId"; + f3=true; + } + + Query query = s.createQuery(hql); + if(f1){ + query.setParameter("sId", stud.getsId().trim()); + } + if(f2){ + query.setParameter("sName", "%"+stud.getsName().trim()+"%"); + } + if(f3){ + query.setParameter("deptId", stud.getDeptId().trim()); + } + return query.list(); + } + +} diff --git a/Hibernate/myHibWeb/src/cn/hncu/demo/service/DemoServiceImpl.java b/Hibernate/myHibWeb/src/cn/hncu/demo/service/DemoServiceImpl.java new file mode 100644 index 0000000..505d8cb --- /dev/null +++ b/Hibernate/myHibWeb/src/cn/hncu/demo/service/DemoServiceImpl.java @@ -0,0 +1,27 @@ +package cn.hncu.demo.service; + +import java.util.List; + +import cn.hncu.demo.dao.DemoJdbcDao; +import cn.hncu.domain.Student; + +public class DemoServiceImpl { + private DemoJdbcDao dao = new DemoJdbcDao(); + + public List queryAllStudents() { + return dao.queryAllStudents(); + } + + public void delStudent(Student stud) { + dao.delStudent(stud); + } + + public void addStudent(Student stud) { + dao.addStudent(stud); + } + + public List queryStudents(Student stud) { + return dao.queryStudents(stud); + } + +} diff --git a/Hibernate/myHibWeb/src/cn/hncu/domain/Student.hbm.xml b/Hibernate/myHibWeb/src/cn/hncu/domain/Student.hbm.xml new file mode 100644 index 0000000..baca9dc --- /dev/null +++ b/Hibernate/myHibWeb/src/cn/hncu/domain/Student.hbm.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Hibernate/myHibWeb/src/cn/hncu/domain/Student.java b/Hibernate/myHibWeb/src/cn/hncu/domain/Student.java new file mode 100644 index 0000000..6771cc2 --- /dev/null +++ b/Hibernate/myHibWeb/src/cn/hncu/domain/Student.java @@ -0,0 +1,42 @@ +package cn.hncu.domain; + +public class Student { + private String sId; + private String sName; + private Integer sAge; + + private String deptId; + + public String getDeptId() { + return deptId; + } + public void setDeptId(String deptId) { + this.deptId = deptId; + } + public Student() { + super(); + } + public String getsId() { + return sId; + } + public void setsId(String sId) { + this.sId = sId; + } + public String getsName() { + return sName; + } + public void setsName(String sName) { + this.sName = sName; + } + public Integer getsAge() { + return sAge; + } + public void setsAge(Integer sAge) { + this.sAge = sAge; + } + @Override + public String toString() { + return "Student [sId=" + sId + ", sName=" + sName + ", sAge=" + sAge + + ", deptId=" + deptId + "]"; + } +} diff --git a/Hibernate/myHibWeb/src/cn/hncu/hib/HibernateSessionFactory.java b/Hibernate/myHibWeb/src/cn/hncu/hib/HibernateSessionFactory.java new file mode 100644 index 0000000..003e351 --- /dev/null +++ b/Hibernate/myHibWeb/src/cn/hncu/hib/HibernateSessionFactory.java @@ -0,0 +1,55 @@ +package cn.hncu.hib; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class HibernateSessionFactory { + private static String configFile = "/hibernate.cfg.xml"; + private static Configuration config = new Configuration(); + private static SessionFactory sessionFactory =null; + + private static final ThreadLocal t = new ThreadLocal(); + + static{ + try { + config.configure(configFile); + sessionFactory = config.buildSessionFactory(); + } catch (HibernateException e) { + e.printStackTrace(); + } + } + + public static Session getSession() throws HibernateException{ + Session session = t.get(); + if(session == null || !session.isOpen()){ + if(sessionFactory==null){ + rebuildSessionFactory(); + } + session = (sessionFactory!=null) ? sessionFactory.openSession() : null; + t.set(session); + } + return session; + } + + private static void rebuildSessionFactory() { + try { + config.configure(configFile); + sessionFactory = config.buildSessionFactory(); + } catch (HibernateException e) { + e.printStackTrace(); + } + } + + //关闭与数据库的会话 + public static void closeSession() throws HibernateException{ + Session session = t.get(); + t.set(null); + if(session!=null){ + session.close(); + } + } + + +} diff --git a/Hibernate/myHibWeb/src/cn/hncu/utils/BaseServlet.java b/Hibernate/myHibWeb/src/cn/hncu/utils/BaseServlet.java new file mode 100644 index 0000000..81b4712 --- /dev/null +++ b/Hibernate/myHibWeb/src/cn/hncu/utils/BaseServlet.java @@ -0,0 +1,43 @@ +package cn.hncu.utils; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public abstract class BaseServlet extends HttpServlet { + private static final long serialVersionUID = 1L; + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + doPost(req, resp); + } + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + req.setCharacterEncoding("utf-8"); + resp.setCharacterEncoding("utf-8"); + resp.setContentType("text/html;charset=utf-8"); + String cmd = req.getParameter("cmd"); + if (null == cmd || cmd.trim().equals("")) { + cmd = "execute"; + } + try { + Method method = this.getClass().getMethod(cmd, + HttpServletRequest.class, HttpServletResponse.class); + method.invoke(this, req, resp); + } catch (NoSuchMethodException e) { + throw new RuntimeException("没有此方法:" + e.getMessage(), e); + }catch(InvocationTargetException e){ + throw new RuntimeException("目标方法执行失败:" + e.getMessage(), e); + }catch(IllegalAccessException e){ + throw new RuntimeException("你可能访问了一个私有的方法:" + e.getMessage(), e); + }catch(Exception e){ + throw new RuntimeException(e.getMessage(), e); + } + } + public abstract void execute(HttpServletRequest req, + HttpServletResponse resp) throws Exception; +} diff --git a/Hibernate/myHibWeb/src/hibernate.cfg.xml b/Hibernate/myHibWeb/src/hibernate.cfg.xml new file mode 100644 index 0000000..b3d2b8d --- /dev/null +++ b/Hibernate/myHibWeb/src/hibernate.cfg.xml @@ -0,0 +1,46 @@ + + + + + + + com.mysql.jdbc.Driver + + + jdbc:mysql://127.0.0.1:3306/hib + + root + 1234 + + + org.hibernate.dialect.MySQLDialect + + + + true + + + 50 + + + 23 + + + false + + + true + + utf-8 + + + + + \ No newline at end of file diff --git a/Hibernate/myHibWeb2/.classpath b/Hibernate/myHibWeb2/.classpath new file mode 100644 index 0000000..96c5a3c --- /dev/null +++ b/Hibernate/myHibWeb2/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Hibernate/myHibWeb2/.mymetadata b/Hibernate/myHibWeb2/.mymetadata new file mode 100644 index 0000000..d610b5c --- /dev/null +++ b/Hibernate/myHibWeb2/.mymetadata @@ -0,0 +1,13 @@ + + + + + + + diff --git a/Hibernate/myHibWeb2/.project b/Hibernate/myHibWeb2/.project new file mode 100644 index 0000000..7329315 --- /dev/null +++ b/Hibernate/myHibWeb2/.project @@ -0,0 +1,58 @@ + + + myHibWeb2 + + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + com.genuitec.eclipse.j2eedt.core.WebClasspathBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + com.genuitec.eclipse.j2eedt.core.J2EEProjectValidator + + + + + com.genuitec.eclipse.j2eedt.core.DeploymentDescriptorValidator + + + + + org.eclipse.wst.validation.validationbuilder + + + + + com.genuitec.eclipse.ast.deploy.core.DeploymentBuilder + + + + + + com.genuitec.eclipse.ast.deploy.core.deploymentnature + org.eclipse.jem.workbench.JavaEMFNature + com.genuitec.eclipse.j2eedt.core.webnature + org.eclipse.jdt.core.javanature + org.eclipse.wst.jsdt.core.jsNature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.common.modulecore.ModuleCoreNature + + diff --git a/Hibernate/myHibWeb2/.settings/.jsdtscope b/Hibernate/myHibWeb2/.settings/.jsdtscope new file mode 100644 index 0000000..252e54f --- /dev/null +++ b/Hibernate/myHibWeb2/.settings/.jsdtscope @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/Hibernate/myHibWeb2/.settings/org.eclipse.jdt.core.prefs b/Hibernate/myHibWeb2/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..dc1a260 --- /dev/null +++ b/Hibernate/myHibWeb2/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Mon Aug 29 14:58:21 CST 2016 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/Hibernate/myHibWeb2/.settings/org.eclipse.wst.common.component b/Hibernate/myHibWeb2/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..5b80a0b --- /dev/null +++ b/Hibernate/myHibWeb2/.settings/org.eclipse.wst.common.component @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Hibernate/myHibWeb2/.settings/org.eclipse.wst.common.project.facet.core.xml b/Hibernate/myHibWeb2/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..5a88726 --- /dev/null +++ b/Hibernate/myHibWeb2/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Hibernate/myHibWeb2/.settings/org.eclipse.wst.jsdt.ui.superType.container b/Hibernate/myHibWeb2/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/Hibernate/myHibWeb2/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/Hibernate/myHibWeb2/.settings/org.eclipse.wst.jsdt.ui.superType.name b/Hibernate/myHibWeb2/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/Hibernate/myHibWeb2/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/Hibernate/myHibWeb2/README.md b/Hibernate/myHibWeb2/README.md new file mode 100644 index 0000000..9fecc64 --- /dev/null +++ b/Hibernate/myHibWeb2/README.md @@ -0,0 +1,337 @@ + + + + + +【框架】[Hibernate]利用Hibernate进行一对多的级联操作-Web实例 + + + +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ +

准备两个表,学生表,和学院表,它们的关系是一对多,一个学生对应一个学院,一个学院可以对应多个学生。
+在此:
+1、演示利用一对多关系进行级联查询,也就是,只查询某个学院,同时将学院中的所有学生查询出来。
+2、演示利用一对多关系进行级联存储,也就是说,只存储学院,但是同时将学生信息存储进学生表。

+ + + +

准备的数据库数据:

+ +
create database hib charset=utf8;
+use hib;
+create table students(
+    sId varchar(8) primary key,
+    sName varchar(40),
+    sAge int,
+    deptId varchar(8)
+);
+
+create table depts(
+  dId varchar(8) primary key,
+  dName varchar(40)
+);
+
+alter table students add(constraint fk_stu_dept foreign key(deptId) references dept(dId));
+
+insert into depts(dId,dName) values('D001','信息科学与工程学院');
+insert into depts(dId,dName) values('D002','土木工程学院');
+insert into depts(dId,dName) values('D003','数学与计算机学院');
+insert into depts(dId,dName) values('D004','通信学院');
+
+insert into students(sId,sName,sAge,deptId) values('S001','Jack',23,'D001');
+insert into students(sId,sName,sAge,deptId) values('S002','Tom',25,'D001');
+insert into students(sId,sName,sAge,deptId) values('S003','张三',43,'D001');
+insert into students(sId,sName,sAge,deptId) values('S004','李四',55,'D001');
+insert into students(sId,sName,sAge,deptId) values('S005','Jack',23,'D002');
+insert into students(sId,sName,sAge,deptId) values('S006','Tom',25,'D003');
+insert into students(sId,sName,sAge,deptId) values('S007','张三',43,'D002');
+insert into students(sId,sName,sAge,deptId) values('S008','李四',55,'D002');
+ +

students表数据如下:

+ +

+ +

depts表数据如下:

+ +

+ +

因为代码比较多,只演示部分代码,完整代码在后面会给出链接。
+需要的JAR包,也全部在项目中,下载完整项目即可。

+ + + +

index.jsp:

+ + + +
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
+<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>Hibernate中表之间的一对多关系</title>
+<style type="text/css">
+table {
+    border: 1px solid gray;
+    border-collapse: collapse;
+    width: 60%;
+}
+
+td {
+    border: 1px solid gray;
+    padding: 5px;
+}
+</style>
+</head>
+
+<body>
+    <h3>通过学院id查询学院表,把该学院的学生信息也同时输出来</h3>
+    <form action="<c:url value='/DemoServlet?cmd=queryDeptById'/>"
+        method="post">
+        <table>
+            <tr>
+                <td>学院编号<font color="red">*</font>
+                </td>
+                <td><input type="text" name="deptId"></td>
+            </tr>
+            <tr>
+                <td colspan="2" align="center"><input type="submit" value="查询">
+                </td>
+            </tr>
+        </table>
+    </form>
+
+    <c:if test="${!empty sessionScope.map }">
+        <h3>查询结果</h3>
+          学院名称:${map.deptName}
+          <table>
+            <tr>
+                <td>学号</td>
+                <td>姓名</td>
+                <td>年龄</td>
+                <td>学院编号</td>
+            </tr>
+            <c:forEach items="${map.qlist}" var="stud">
+                <tr>
+                    <td>${stud.sId}</td>
+                    <td>${stud.sName}</td>
+                    <td>${stud.sAge}</td>
+                    <td>${stud.dept.dId}</td>
+                </tr>
+            </c:forEach>
+        </table>
+        <c:remove var="map"/>
+    </c:if>
+
+    <h3>添加学生/学院</h3>
+    <form action="<c:url value='/DemoServlet?cmd=addDept'/>" method="post">
+        <table>
+            <tr>
+                <td>学院编号<font color="red">*</font>
+                </td>
+                <td><input type="text" name="deptId"></td>
+            </tr>
+            <tr>
+                <td>学院名称
+                </td>
+                <td><input type="text" name="deptName"></td>
+            </tr>
+            <tr>
+                <td align="center">学生学号<font color="red">*</font>
+                </td>
+                <td align="center"><input type="text" name="studId"></td>
+            </tr>
+            <tr>
+                <td align="center">学生姓名<font color="red">*</font>
+                </td>
+                <td align="center"><input type="text" name="studName"></td>
+            </tr>
+            <tr>
+                <td align="center">学生年龄<font color="red">*</font>
+                </td>
+                <td align="center"><input type="text" name="studAge"></td>
+            </tr>
+            <tr>
+                <td colspan="2" align="center"><input type="submit" value="存储"></td>
+            </tr>
+        </table>
+    </form>
+
+</body>
+</html>
+
+ + + +

DemoJdbcDao.java

+ +

数据层。

+ + + +
package cn.hncu.demo.dao;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+
+import cn.hncu.domain.Dept;
+import cn.hncu.domain.Student;
+import cn.hncu.hib.HibernateSessionFactory;
+
+public class DemoJdbcDao {
+    public Dept queryDeptById(Dept dept) {
+        Session s = HibernateSessionFactory.getSession();
+        String hql = "from Dept d where d.dId=?";
+        //String hql = "from Dept";
+        Query query = s.createQuery(hql);
+        query.setParameter(0, dept.getdId());
+        //根据部门ID去查的,只会有一个查询结果
+        Dept resDept = (Dept) query.list().get(0);
+        return resDept;
+    }
+
+    public void addDept(Dept dept) {
+        Session s = HibernateSessionFactory.getSession();
+        if(dept.getdName()==null){
+            Query query = s.createQuery("from Dept d where d.dId=?");
+            query.setParameter(0, dept.getdId());
+            //对于学院存在的,如果没有填写学院名称,为其补上
+            dept.setdName( ((Dept) query.list().get(0)).getdName() );
+        }
+        s.clear();//把之前的session信息清空,因为不允许一个session对象进行几个操作
+        Transaction tx = s.beginTransaction();
+        s.saveOrUpdate(dept);
+        tx.commit();
+    }
+
+}
+
+ + + +

DemoServlet

+ +

servlet层

+ + + +
package cn.hncu.demo;
+
+
+import java.io.PrintWriter;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import cn.hncu.demo.service.DemoServiceImpl;
+import cn.hncu.domain.Dept;
+import cn.hncu.domain.Student;
+import cn.hncu.utils.BaseServlet;
+
+public class DemoServlet extends BaseServlet {
+    DemoServiceImpl service = new DemoServiceImpl();
+    @Override
+    public void execute(HttpServletRequest req, HttpServletResponse resp)
+            throws Exception {
+
+    }
+
+    public void queryDeptById(HttpServletRequest req, HttpServletResponse resp)
+            throws Exception {
+        String deptId = req.getParameter("deptId");
+        if(deptId==null||deptId.trim().length()==0){
+            resp.sendRedirect(getServletContext().getContextPath());
+            return;
+        }
+        Dept dept = new Dept();
+        dept.setdId(deptId);
+        dept = service.queryDeptById(dept);
+        Map<String, Object> map = new HashMap<String, Object>();
+
+        map.put("deptName", dept.getdName());
+        map.put("qlist", dept.getStudents());
+
+        req.getSession().setAttribute("map", map);
+        resp.sendRedirect(getServletContext().getContextPath());
+    }
+
+    public void addDept(HttpServletRequest req, HttpServletResponse resp)
+            throws Exception {
+        String deptId = req.getParameter("deptId");
+        String deptName = req.getParameter("deptName");
+        if(deptName==null||deptName.trim().equals("")){
+            deptName=null;
+        }
+        String studId = req.getParameter("studId");
+        String studName = req.getParameter("studName");
+        String studAge = req.getParameter("studAge");
+        int age = Integer.parseInt(studAge);
+
+        Dept dept = new Dept();
+        dept.setdId(deptId);
+        dept.setdName(deptName);
+
+        Student s1 = new Student();
+        s1.setsId(studId);
+        s1.setsName(studName);
+        s1.setsAge(age);
+        s1.setDept(dept);//多方进行设置外键
+
+        //把多方添加到一方的集合中
+        dept.getStudents().add(s1);
+
+        service.addDept(dept);
+
+        resp.sendRedirect(getServletContext().getContextPath());
+    }
+
+}
+
+ +

演示结果:

+ +

开始显示页面:

+ +

+ +

查询D002学院:

+ +

+ +

为D002学院添加学生:

+ +

+ +

结果:
+

+ +

添加D005学院-科技学院

+ +

+ +

结果

+ +

+ + + +

完整的项目链接:

+ +

小小的总结:

+ +

此项目,我写的时候比较急,因为马上要学Spring框架了,有些方面没考虑到,有兴趣的可以自己取完善一下。例如,在增加学院和学生的时候,增加一个按钮,添加学生。再比如,把service,DAO层完善一下,写好接口,最好再写个过滤器,全站压缩,编码啥的。哈哈,自己可以加功能的。

+ +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ \ No newline at end of file diff --git a/Hibernate/myHibWeb2/WebRoot/META-INF/MANIFEST.MF b/Hibernate/myHibWeb2/WebRoot/META-INF/MANIFEST.MF new file mode 100644 index 0000000..254272e --- /dev/null +++ b/Hibernate/myHibWeb2/WebRoot/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/demo/DemoServlet.class b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/demo/DemoServlet.class new file mode 100644 index 0000000..33c0bf2 Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/demo/DemoServlet.class differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/demo/dao/DemoJdbcDao.class b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/demo/dao/DemoJdbcDao.class new file mode 100644 index 0000000..f8e2785 Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/demo/dao/DemoJdbcDao.class differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/demo/service/DemoServiceImpl.class b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/demo/service/DemoServiceImpl.class new file mode 100644 index 0000000..faa4a18 Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/demo/service/DemoServiceImpl.class differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/domain/Dept.class b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/domain/Dept.class new file mode 100644 index 0000000..f5856f9 Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/domain/Dept.class differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.class b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.class new file mode 100644 index 0000000..de27c42 Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.class differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.hbm.xml b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.hbm.xml new file mode 100644 index 0000000..81421cc --- /dev/null +++ b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.hbm.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/hib/HibernateSessionFactory.class b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/hib/HibernateSessionFactory.class new file mode 100644 index 0000000..5c5aa2b Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/hib/HibernateSessionFactory.class differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/utils/BaseServlet.class b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/utils/BaseServlet.class new file mode 100644 index 0000000..777de43 Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/cn/hncu/utils/BaseServlet.class differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/hibernate.cfg.xml b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/hibernate.cfg.xml new file mode 100644 index 0000000..1b15e9e --- /dev/null +++ b/Hibernate/myHibWeb2/WebRoot/WEB-INF/classes/hibernate.cfg.xml @@ -0,0 +1,29 @@ + + + + + + + com.mysql.jdbc.Driver + + + jdbc:mysql://127.0.0.1:3306/hib + + root + 1234 + + + org.hibernate.dialect.MySQLDialect + + + + true + + utf-8 + + + + + \ No newline at end of file diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/antlr-2.7.7.jar b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/antlr-2.7.7.jar new file mode 100644 index 0000000..5e5f14b Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/antlr-2.7.7.jar differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/classmate-1.3.0.jar b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/classmate-1.3.0.jar new file mode 100644 index 0000000..049b63f Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/classmate-1.3.0.jar differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/dom4j-1.6.1.jar b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/dom4j-1.6.1.jar new file mode 100644 index 0000000..c8c4dbb Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/dom4j-1.6.1.jar differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/geronimo-jta_1.1_spec-1.1.1.jar b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/geronimo-jta_1.1_spec-1.1.1.jar new file mode 100644 index 0000000..ee9963d Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/geronimo-jta_1.1_spec-1.1.1.jar differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/hibernate-commons-annotations-5.0.1.Final.jar b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/hibernate-commons-annotations-5.0.1.Final.jar new file mode 100644 index 0000000..82e425d Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/hibernate-commons-annotations-5.0.1.Final.jar differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/hibernate-core-5.1.1.Final.jar b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/hibernate-core-5.1.1.Final.jar new file mode 100644 index 0000000..bbd38a3 Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/hibernate-core-5.1.1.Final.jar differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/hibernate-jpa-2.1-api-1.0.0.Final.jar b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/hibernate-jpa-2.1-api-1.0.0.Final.jar new file mode 100644 index 0000000..e2f2c59 Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/hibernate-jpa-2.1-api-1.0.0.Final.jar differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/jandex-2.0.0.Final.jar b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/jandex-2.0.0.Final.jar new file mode 100644 index 0000000..d24086a Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/jandex-2.0.0.Final.jar differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/javassist-3.20.0-GA.jar b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/javassist-3.20.0-GA.jar new file mode 100644 index 0000000..0f1ff72 Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/javassist-3.20.0-GA.jar differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/jboss-logging-3.3.0.Final.jar b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/jboss-logging-3.3.0.Final.jar new file mode 100644 index 0000000..ea45d4d Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/jboss-logging-3.3.0.Final.jar differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.39-bin.jar b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.39-bin.jar new file mode 100644 index 0000000..dac6e14 Binary files /dev/null and b/Hibernate/myHibWeb2/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.39-bin.jar differ diff --git a/Hibernate/myHibWeb2/WebRoot/WEB-INF/web.xml b/Hibernate/myHibWeb2/WebRoot/WEB-INF/web.xml new file mode 100644 index 0000000..34c4d5d --- /dev/null +++ b/Hibernate/myHibWeb2/WebRoot/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + + + DemoServlet + cn.hncu.demo.DemoServlet + + + DemoServlet + /DemoServlet + + + + index.jsp + + diff --git a/Hibernate/myHibWeb2/WebRoot/index.jsp b/Hibernate/myHibWeb2/WebRoot/index.jsp new file mode 100644 index 0000000..a7c1152 --- /dev/null +++ b/Hibernate/myHibWeb2/WebRoot/index.jsp @@ -0,0 +1,96 @@ +<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> +<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> + + + + +Hibernate中表之间的一对多关系 + + + + +

通过学院id查询学院表,把该学院的学生信息也同时输出来

+
+ + + + + + + + +
学院编号* +
+
+
+ + +

查询结果

+ 学院名称:${map.deptName} + + + + + + + + + + + + + + + +
学号姓名年龄学院编号
${stud.sId}${stud.sName}${stud.sAge}${stud.dept.dId}
+ +
+ +

添加学生/学院

+
+ + + + + + + + + + + + + + + + + + + + + + + + +
学院编号* +
学院名称 +
学生学号* +
学生姓名* +
学生年龄* +
+
+ + + diff --git a/Hibernate/myHibWeb2/myHibWeb2.zip b/Hibernate/myHibWeb2/myHibWeb2.zip new file mode 100644 index 0000000..2cc52b7 Binary files /dev/null and b/Hibernate/myHibWeb2/myHibWeb2.zip differ diff --git a/Hibernate/myHibWeb2/src/cn/hncu/demo/DemoServlet.java b/Hibernate/myHibWeb2/src/cn/hncu/demo/DemoServlet.java new file mode 100644 index 0000000..0c4255c --- /dev/null +++ b/Hibernate/myHibWeb2/src/cn/hncu/demo/DemoServlet.java @@ -0,0 +1,74 @@ +package cn.hncu.demo; + + +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import cn.hncu.demo.service.DemoServiceImpl; +import cn.hncu.domain.Dept; +import cn.hncu.domain.Student; +import cn.hncu.utils.BaseServlet; + +public class DemoServlet extends BaseServlet { + DemoServiceImpl service = new DemoServiceImpl(); + @Override + public void execute(HttpServletRequest req, HttpServletResponse resp) + throws Exception { + + } + + public void queryDeptById(HttpServletRequest req, HttpServletResponse resp) + throws Exception { + String deptId = req.getParameter("deptId"); + if(deptId==null||deptId.trim().length()==0){ + resp.sendRedirect(getServletContext().getContextPath()); + return; + } + Dept dept = new Dept(); + dept.setdId(deptId); + dept = service.queryDeptById(dept); + Map map = new HashMap(); + + map.put("deptName", dept.getdName()); + map.put("qlist", dept.getStudents()); + + req.getSession().setAttribute("map", map); + resp.sendRedirect(getServletContext().getContextPath()); + } + + public void addDept(HttpServletRequest req, HttpServletResponse resp) + throws Exception { + String deptId = req.getParameter("deptId"); + String deptName = req.getParameter("deptName"); + if(deptName==null||deptName.trim().equals("")){ + deptName=null; + } + String studId = req.getParameter("studId"); + String studName = req.getParameter("studName"); + String studAge = req.getParameter("studAge"); + int age = Integer.parseInt(studAge); + + Dept dept = new Dept(); + dept.setdId(deptId); + dept.setdName(deptName); + + Student s1 = new Student(); + s1.setsId(studId); + s1.setsName(studName); + s1.setsAge(age); + s1.setDept(dept);//多方进行设置外键 + + //把多方添加到一方的集合中 + dept.getStudents().add(s1); + + service.addDept(dept); + + resp.sendRedirect(getServletContext().getContextPath()); + } + +} diff --git a/Hibernate/myHibWeb2/src/cn/hncu/demo/dao/DemoJdbcDao.java b/Hibernate/myHibWeb2/src/cn/hncu/demo/dao/DemoJdbcDao.java new file mode 100644 index 0000000..6f25847 --- /dev/null +++ b/Hibernate/myHibWeb2/src/cn/hncu/demo/dao/DemoJdbcDao.java @@ -0,0 +1,37 @@ +package cn.hncu.demo.dao; + +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.Transaction; + +import cn.hncu.domain.Dept; +import cn.hncu.domain.Student; +import cn.hncu.hib.HibernateSessionFactory; + +public class DemoJdbcDao { + public Dept queryDeptById(Dept dept) { + Session s = HibernateSessionFactory.getSession(); + String hql = "from Dept d where d.dId=?"; + //String hql = "from Dept"; + Query query = s.createQuery(hql); + query.setParameter(0, dept.getdId()); + //根据部门ID去查的,只会有一个查询结果 + Dept resDept = (Dept) query.list().get(0); + return resDept; + } + + public void addDept(Dept dept) { + Session s = HibernateSessionFactory.getSession(); + if(dept.getdName()==null){ + Query query = s.createQuery("from Dept d where d.dId=?"); + query.setParameter(0, dept.getdId()); + //对于学院存在的,如果没有填写学院名称,为其补上 + dept.setdName( ((Dept) query.list().get(0)).getdName() ); + } + s.clear();//把之前的session信息清空,因为不允许一个session对象进行几个操作 + Transaction tx = s.beginTransaction(); + s.saveOrUpdate(dept); + tx.commit(); + } + +} diff --git a/Hibernate/myHibWeb2/src/cn/hncu/demo/service/DemoServiceImpl.java b/Hibernate/myHibWeb2/src/cn/hncu/demo/service/DemoServiceImpl.java new file mode 100644 index 0000000..255cc38 --- /dev/null +++ b/Hibernate/myHibWeb2/src/cn/hncu/demo/service/DemoServiceImpl.java @@ -0,0 +1,15 @@ +package cn.hncu.demo.service; + +import cn.hncu.demo.dao.DemoJdbcDao; +import cn.hncu.domain.Dept; + +public class DemoServiceImpl { + private DemoJdbcDao dao = new DemoJdbcDao(); + public Dept queryDeptById(Dept dept) { + return dao.queryDeptById(dept); + } + public void addDept(Dept dept) { + dao.addDept(dept); + } + +} diff --git a/Hibernate/myHibWeb2/src/cn/hncu/domain/Dept.java b/Hibernate/myHibWeb2/src/cn/hncu/domain/Dept.java new file mode 100644 index 0000000..1b1d39d --- /dev/null +++ b/Hibernate/myHibWeb2/src/cn/hncu/domain/Dept.java @@ -0,0 +1,31 @@ +package cn.hncu.domain; + +import java.util.HashSet; +import java.util.Set; + +public class Dept { + private String dId; + private String dName; + + //※声明一个专用于存储多方的一个集合及setter-getter + private Set students= new HashSet(); + + public Set getStudents() { + return students; + } + public void setStudents(Set students) { + this.students = students; + } + public String getdId() { + return dId; + } + public void setdId(String dId) { + this.dId = dId; + } + public String getdName() { + return dName; + } + public void setdName(String dName) { + this.dName = dName; + } +} diff --git a/Hibernate/myHibWeb2/src/cn/hncu/domain/Student.hbm.xml b/Hibernate/myHibWeb2/src/cn/hncu/domain/Student.hbm.xml new file mode 100644 index 0000000..81421cc --- /dev/null +++ b/Hibernate/myHibWeb2/src/cn/hncu/domain/Student.hbm.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Hibernate/myHibWeb2/src/cn/hncu/domain/Student.java b/Hibernate/myHibWeb2/src/cn/hncu/domain/Student.java new file mode 100644 index 0000000..a5f6472 --- /dev/null +++ b/Hibernate/myHibWeb2/src/cn/hncu/domain/Student.java @@ -0,0 +1,47 @@ +package cn.hncu.domain; + +public class Student { + private String sId; + private String sName; + private Integer sAge; + + // ※专为一方声明一个值对象属性及setter-getter + private Dept dept; + + public Dept getDept() { + return dept; + } + + public void setDept(Dept dept) { + this.dept = dept; + } + + public Student() { + super(); + } + + public String getsId() { + return sId; + } + + public void setsId(String sId) { + this.sId = sId; + } + + public String getsName() { + return sName; + } + + public void setsName(String sName) { + this.sName = sName; + } + + public Integer getsAge() { + return sAge; + } + + public void setsAge(Integer sAge) { + this.sAge = sAge; + } + +} diff --git a/Hibernate/myHibWeb2/src/cn/hncu/hib/HibernateSessionFactory.java b/Hibernate/myHibWeb2/src/cn/hncu/hib/HibernateSessionFactory.java new file mode 100644 index 0000000..003e351 --- /dev/null +++ b/Hibernate/myHibWeb2/src/cn/hncu/hib/HibernateSessionFactory.java @@ -0,0 +1,55 @@ +package cn.hncu.hib; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class HibernateSessionFactory { + private static String configFile = "/hibernate.cfg.xml"; + private static Configuration config = new Configuration(); + private static SessionFactory sessionFactory =null; + + private static final ThreadLocal t = new ThreadLocal(); + + static{ + try { + config.configure(configFile); + sessionFactory = config.buildSessionFactory(); + } catch (HibernateException e) { + e.printStackTrace(); + } + } + + public static Session getSession() throws HibernateException{ + Session session = t.get(); + if(session == null || !session.isOpen()){ + if(sessionFactory==null){ + rebuildSessionFactory(); + } + session = (sessionFactory!=null) ? sessionFactory.openSession() : null; + t.set(session); + } + return session; + } + + private static void rebuildSessionFactory() { + try { + config.configure(configFile); + sessionFactory = config.buildSessionFactory(); + } catch (HibernateException e) { + e.printStackTrace(); + } + } + + //关闭与数据库的会话 + public static void closeSession() throws HibernateException{ + Session session = t.get(); + t.set(null); + if(session!=null){ + session.close(); + } + } + + +} diff --git a/Hibernate/myHibWeb2/src/cn/hncu/utils/BaseServlet.java b/Hibernate/myHibWeb2/src/cn/hncu/utils/BaseServlet.java new file mode 100644 index 0000000..81b4712 --- /dev/null +++ b/Hibernate/myHibWeb2/src/cn/hncu/utils/BaseServlet.java @@ -0,0 +1,43 @@ +package cn.hncu.utils; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public abstract class BaseServlet extends HttpServlet { + private static final long serialVersionUID = 1L; + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + doPost(req, resp); + } + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + req.setCharacterEncoding("utf-8"); + resp.setCharacterEncoding("utf-8"); + resp.setContentType("text/html;charset=utf-8"); + String cmd = req.getParameter("cmd"); + if (null == cmd || cmd.trim().equals("")) { + cmd = "execute"; + } + try { + Method method = this.getClass().getMethod(cmd, + HttpServletRequest.class, HttpServletResponse.class); + method.invoke(this, req, resp); + } catch (NoSuchMethodException e) { + throw new RuntimeException("没有此方法:" + e.getMessage(), e); + }catch(InvocationTargetException e){ + throw new RuntimeException("目标方法执行失败:" + e.getMessage(), e); + }catch(IllegalAccessException e){ + throw new RuntimeException("你可能访问了一个私有的方法:" + e.getMessage(), e); + }catch(Exception e){ + throw new RuntimeException(e.getMessage(), e); + } + } + public abstract void execute(HttpServletRequest req, + HttpServletResponse resp) throws Exception; +} diff --git a/Hibernate/myHibWeb2/src/hibernate.cfg.xml b/Hibernate/myHibWeb2/src/hibernate.cfg.xml new file mode 100644 index 0000000..1b15e9e --- /dev/null +++ b/Hibernate/myHibWeb2/src/hibernate.cfg.xml @@ -0,0 +1,29 @@ + + + + + + + com.mysql.jdbc.Driver + + + jdbc:mysql://127.0.0.1:3306/hib + + root + 1234 + + + org.hibernate.dialect.MySQLDialect + + + + true + + utf-8 + + + + + \ No newline at end of file diff --git "a/Hibernate/myHibWeb2/\343\200\220\346\241\206\346\236\266\343\200\221[Hibernate]\345\210\251\347\224\250Hibernate\350\277\233\350\241\214\344\270\200\345\257\271\345\244\232\347\232\204\347\272\247\350\201\224\346\223\215\344\275\234-Web\345\256\236\344\276\213.html" "b/Hibernate/myHibWeb2/\343\200\220\346\241\206\346\236\266\343\200\221[Hibernate]\345\210\251\347\224\250Hibernate\350\277\233\350\241\214\344\270\200\345\257\271\345\244\232\347\232\204\347\272\247\350\201\224\346\223\215\344\275\234-Web\345\256\236\344\276\213.html" new file mode 100644 index 0000000..2843fe2 --- /dev/null +++ "b/Hibernate/myHibWeb2/\343\200\220\346\241\206\346\236\266\343\200\221[Hibernate]\345\210\251\347\224\250Hibernate\350\277\233\350\241\214\344\270\200\345\257\271\345\244\232\347\232\204\347\272\247\350\201\224\346\223\215\344\275\234-Web\345\256\236\344\276\213.html" @@ -0,0 +1,337 @@ + + + + + +【框架】[Hibernate]利用Hibernate进行一对多的级联操作-Web实例 + + + +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ +

准备两个表,学生表,和学院表,它们的关系是一对多,一个学生对应一个学院,一个学院可以对应多个学生。
+在此:
+1、演示利用一对多关系进行级联查询,也就是,只查询某个学院,同时将学院中的所有学生查询出来。
+2、演示利用一对多关系进行级联存储,也就是说,只存储学院,但是同时将学生信息存储进学生表。

+ + + +

准备的数据库数据:

+ +
create database hib charset=utf8;
+use hib;
+create table students(
+    sId varchar(8) primary key,
+    sName varchar(40),
+    sAge int,
+    deptId varchar(8)
+);
+
+create table depts(
+  dId varchar(8) primary key,
+  dName varchar(40)
+);
+
+alter table students add(constraint fk_stu_dept foreign key(deptId) references dept(dId));
+
+insert into depts(dId,dName) values('D001','信息科学与工程学院');
+insert into depts(dId,dName) values('D002','土木工程学院');
+insert into depts(dId,dName) values('D003','数学与计算机学院');
+insert into depts(dId,dName) values('D004','通信学院');
+
+insert into students(sId,sName,sAge,deptId) values('S001','Jack',23,'D001');
+insert into students(sId,sName,sAge,deptId) values('S002','Tom',25,'D001');
+insert into students(sId,sName,sAge,deptId) values('S003','张三',43,'D001');
+insert into students(sId,sName,sAge,deptId) values('S004','李四',55,'D001');
+insert into students(sId,sName,sAge,deptId) values('S005','Jack',23,'D002');
+insert into students(sId,sName,sAge,deptId) values('S006','Tom',25,'D003');
+insert into students(sId,sName,sAge,deptId) values('S007','张三',43,'D002');
+insert into students(sId,sName,sAge,deptId) values('S008','李四',55,'D002');
+ +

students表数据如下:

+ +

+ +

depts表数据如下:

+ +

+ +

因为代码比较多,只演示部分代码,完整代码在后面会给出链接。
+需要的JAR包,也全部在项目中,下载完整项目即可。

+ + + +

index.jsp:

+ + + +
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
+<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html>
+<head>
+<title>Hibernate中表之间的一对多关系</title>
+<style type="text/css">
+table {
+    border: 1px solid gray;
+    border-collapse: collapse;
+    width: 60%;
+}
+
+td {
+    border: 1px solid gray;
+    padding: 5px;
+}
+</style>
+</head>
+
+<body>
+    <h3>通过学院id查询学院表,把该学院的学生信息也同时输出来</h3>
+    <form action="<c:url value='/DemoServlet?cmd=queryDeptById'/>"
+        method="post">
+        <table>
+            <tr>
+                <td>学院编号<font color="red">*</font>
+                </td>
+                <td><input type="text" name="deptId"></td>
+            </tr>
+            <tr>
+                <td colspan="2" align="center"><input type="submit" value="查询">
+                </td>
+            </tr>
+        </table>
+    </form>
+
+    <c:if test="${!empty sessionScope.map }">
+        <h3>查询结果</h3>
+          学院名称:${map.deptName}
+          <table>
+            <tr>
+                <td>学号</td>
+                <td>姓名</td>
+                <td>年龄</td>
+                <td>学院编号</td>
+            </tr>
+            <c:forEach items="${map.qlist}" var="stud">
+                <tr>
+                    <td>${stud.sId}</td>
+                    <td>${stud.sName}</td>
+                    <td>${stud.sAge}</td>
+                    <td>${stud.dept.dId}</td>
+                </tr>
+            </c:forEach>
+        </table>
+        <c:remove var="map"/>
+    </c:if>
+
+    <h3>添加学生/学院</h3>
+    <form action="<c:url value='/DemoServlet?cmd=addDept'/>" method="post">
+        <table>
+            <tr>
+                <td>学院编号<font color="red">*</font>
+                </td>
+                <td><input type="text" name="deptId"></td>
+            </tr>
+            <tr>
+                <td>学院名称
+                </td>
+                <td><input type="text" name="deptName"></td>
+            </tr>
+            <tr>
+                <td align="center">学生学号<font color="red">*</font>
+                </td>
+                <td align="center"><input type="text" name="studId"></td>
+            </tr>
+            <tr>
+                <td align="center">学生姓名<font color="red">*</font>
+                </td>
+                <td align="center"><input type="text" name="studName"></td>
+            </tr>
+            <tr>
+                <td align="center">学生年龄<font color="red">*</font>
+                </td>
+                <td align="center"><input type="text" name="studAge"></td>
+            </tr>
+            <tr>
+                <td colspan="2" align="center"><input type="submit" value="存储"></td>
+            </tr>
+        </table>
+    </form>
+
+</body>
+</html>
+
+ + + +

DemoJdbcDao.java

+ +

数据层。

+ + + +
package cn.hncu.demo.dao;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+
+import cn.hncu.domain.Dept;
+import cn.hncu.domain.Student;
+import cn.hncu.hib.HibernateSessionFactory;
+
+public class DemoJdbcDao {
+    public Dept queryDeptById(Dept dept) {
+        Session s = HibernateSessionFactory.getSession();
+        String hql = "from Dept d where d.dId=?";
+        //String hql = "from Dept";
+        Query query = s.createQuery(hql);
+        query.setParameter(0, dept.getdId());
+        //根据部门ID去查的,只会有一个查询结果
+        Dept resDept = (Dept) query.list().get(0);
+        return resDept;
+    }
+
+    public void addDept(Dept dept) {
+        Session s = HibernateSessionFactory.getSession();
+        if(dept.getdName()==null){
+            Query query = s.createQuery("from Dept d where d.dId=?");
+            query.setParameter(0, dept.getdId());
+            //对于学院存在的,如果没有填写学院名称,为其补上
+            dept.setdName( ((Dept) query.list().get(0)).getdName() );
+        }
+        s.clear();//把之前的session信息清空,因为不允许一个session对象进行几个操作
+        Transaction tx = s.beginTransaction();
+        s.saveOrUpdate(dept);
+        tx.commit();
+    }
+
+}
+
+ + + +

DemoServlet

+ +

servlet层

+ + + +
package cn.hncu.demo;
+
+
+import java.io.PrintWriter;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import cn.hncu.demo.service.DemoServiceImpl;
+import cn.hncu.domain.Dept;
+import cn.hncu.domain.Student;
+import cn.hncu.utils.BaseServlet;
+
+public class DemoServlet extends BaseServlet {
+    DemoServiceImpl service = new DemoServiceImpl();
+    @Override
+    public void execute(HttpServletRequest req, HttpServletResponse resp)
+            throws Exception {
+
+    }
+
+    public void queryDeptById(HttpServletRequest req, HttpServletResponse resp)
+            throws Exception {
+        String deptId = req.getParameter("deptId");
+        if(deptId==null||deptId.trim().length()==0){
+            resp.sendRedirect(getServletContext().getContextPath());
+            return;
+        }
+        Dept dept = new Dept();
+        dept.setdId(deptId);
+        dept = service.queryDeptById(dept);
+        Map<String, Object> map = new HashMap<String, Object>();
+
+        map.put("deptName", dept.getdName());
+        map.put("qlist", dept.getStudents());
+
+        req.getSession().setAttribute("map", map);
+        resp.sendRedirect(getServletContext().getContextPath());
+    }
+
+    public void addDept(HttpServletRequest req, HttpServletResponse resp)
+            throws Exception {
+        String deptId = req.getParameter("deptId");
+        String deptName = req.getParameter("deptName");
+        if(deptName==null||deptName.trim().equals("")){
+            deptName=null;
+        }
+        String studId = req.getParameter("studId");
+        String studName = req.getParameter("studName");
+        String studAge = req.getParameter("studAge");
+        int age = Integer.parseInt(studAge);
+
+        Dept dept = new Dept();
+        dept.setdId(deptId);
+        dept.setdName(deptName);
+
+        Student s1 = new Student();
+        s1.setsId(studId);
+        s1.setsName(studName);
+        s1.setsAge(age);
+        s1.setDept(dept);//多方进行设置外键
+
+        //把多方添加到一方的集合中
+        dept.getStudents().add(s1);
+
+        service.addDept(dept);
+
+        resp.sendRedirect(getServletContext().getContextPath());
+    }
+
+}
+
+ +

演示结果:

+ +

开始显示页面:

+ +

+ +

查询D002学院:

+ +

+ +

为D002学院添加学生:

+ +

+ +

结果:
+

+ +

添加D005学院-科技学院

+ +

+ +

结果

+ +

+ + + +

完整的项目链接:

+ +

小小的总结:

+ +

此项目,我写的时候比较急,因为马上要学Spring框架了,有些方面没考虑到,有兴趣的可以自己取完善一下。例如,在增加学院和学生的时候,增加一个按钮,添加学生。再比如,把service,DAO层完善一下,写好接口,最好再写个过滤器,全站压缩,编码啥的。哈哈,自己可以加功能的。

+ +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ \ No newline at end of file diff --git a/Hibernate/myHibWebDemo/.classpath b/Hibernate/myHibWebDemo/.classpath new file mode 100644 index 0000000..96c5a3c --- /dev/null +++ b/Hibernate/myHibWebDemo/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Hibernate/myHibWebDemo/.mymetadata b/Hibernate/myHibWebDemo/.mymetadata new file mode 100644 index 0000000..f246854 --- /dev/null +++ b/Hibernate/myHibWebDemo/.mymetadata @@ -0,0 +1,13 @@ + + + + + + + diff --git a/Hibernate/myHibWebDemo/.project b/Hibernate/myHibWebDemo/.project new file mode 100644 index 0000000..65d4152 --- /dev/null +++ b/Hibernate/myHibWebDemo/.project @@ -0,0 +1,52 @@ + + + myHibWebDemo + + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + com.genuitec.eclipse.j2eedt.core.WebClasspathBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + com.genuitec.eclipse.j2eedt.core.J2EEProjectValidator + + + + + com.genuitec.eclipse.j2eedt.core.DeploymentDescriptorValidator + + + + + org.eclipse.wst.validation.validationbuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + com.genuitec.eclipse.j2eedt.core.webnature + org.eclipse.jdt.core.javanature + org.eclipse.wst.jsdt.core.jsNature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.common.modulecore.ModuleCoreNature + + diff --git a/Hibernate/myHibWebDemo/.settings/.jsdtscope b/Hibernate/myHibWebDemo/.settings/.jsdtscope new file mode 100644 index 0000000..252e54f --- /dev/null +++ b/Hibernate/myHibWebDemo/.settings/.jsdtscope @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/Hibernate/myHibWebDemo/.settings/org.eclipse.jdt.core.prefs b/Hibernate/myHibWebDemo/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..086a563 --- /dev/null +++ b/Hibernate/myHibWebDemo/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Sun Aug 28 00:34:55 CST 2016 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/Hibernate/myHibWebDemo/.settings/org.eclipse.wst.common.component b/Hibernate/myHibWebDemo/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..7804d6c --- /dev/null +++ b/Hibernate/myHibWebDemo/.settings/org.eclipse.wst.common.component @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Hibernate/myHibWebDemo/.settings/org.eclipse.wst.common.project.facet.core.xml b/Hibernate/myHibWebDemo/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..5a88726 --- /dev/null +++ b/Hibernate/myHibWebDemo/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Hibernate/myHibWebDemo/.settings/org.eclipse.wst.jsdt.ui.superType.container b/Hibernate/myHibWebDemo/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/Hibernate/myHibWebDemo/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/Hibernate/myHibWebDemo/.settings/org.eclipse.wst.jsdt.ui.superType.name b/Hibernate/myHibWebDemo/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/Hibernate/myHibWebDemo/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/Hibernate/myHibWebDemo/README.md b/Hibernate/myHibWebDemo/README.md new file mode 100644 index 0000000..cbc6287 --- /dev/null +++ b/Hibernate/myHibWebDemo/README.md @@ -0,0 +1,454 @@ + + + + + +【框架】[Hibernate]构架知识点详细解析 + + + +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ + + +

Hibernate介绍:

+ +

Hibernate是一个开放源码的、非常优秀、成熟的O/R Mapping框架。它提供了强大、高性能的Java对象和关系数据的持久化和查询功能。

+ +

O/R Mapping
+对象关系映射(Object Relational Mapping,简称ORM)技术,是通过使用描述对象和数据库之间映射的元数据,将Java程序中的对象自动持久化到关系数据库中。
+对象和关系数据是业务实体的两种表现形式,业务实体在内存中表现为对象,在数据库中表现为关系数据。内存中的对象之间存在关联和继承关系,而在数据库中,关系数据无法直接表达多对多关联和继承关系。因此,对象-关系映射(ORM)系统一般以中间件的形式存在,主要实现程序对象到关系数据库数据的映射。

+ +

Hibernate 只是一个将持久化类与数据库表相映射的工具,每个持久化类实例均对应于数据库表中的一条数据行。可以使用面向对象的方法操作此持久化类实例,完成对数据库表的插入、删除、修改等操作。

+ +

利用Hibernate操作数据库,我们通过应用程序经过Hibernate持久层来访问数据库,其实Hibernate完成了以前JDBC的功能,不过Hibernate使用面向对象的方法操作数据库。

+ + + +

Hibernate体系结构图:

+ +

+ + + +

Hibernate构架入门步骤

+ +

第1步: 先建一个Java工程导入使用Hibernate最小必要包。
+一般在解压后的lib目录下的
+
+required目录下。
+可以到官方网站 http://hibernate.org/orm/downloads/ 下载Hibernate最新的zip压缩包。
+如果访问数据库,则还需要导入数据库的驱动包。
+mysql-connector-java-5.1.39 .zip下载地址:

+ +
+

–>点击下载数据库5.1.39驱动包–
+

+ +

第2步:在src创建配置文件hibernate.cfg.xml,放置在src目录下。

+ +

第3步:编写一个会话工厂类。通过会话工厂类产生一个会话Session对象。Session对象是Hibernate的核心。任何对数据库操作都在会话中进行的。

+ +

对于熟悉C3P0的朋友,可以按下面的理解:
+(配置文件hibernate.cfg.xml可以类比c3p0.properties的配置文件,HibernateSessionFactory可以类比C3p0Pool,SessionFactory可以类比C3p0中的DataSource,Session可以类比Connection去理解)

+ +

第4步:编写POJO类以及映射文件。
+POJO(POJO(Plain Ordinary Java Object)简单的Java对象,实际就是普通JavaBeans)

+ +

第5步:编写测试文件

+ +

hibernate.cfg.xml配置文件详解

+ +

hibernate.cfg.xml其实这个名字自己可以随便取的,但是大家都这么取名,于是形成了一个习惯了!!!

+ +
<?xml version='1.0' encoding='UTF-8'?>
+<!--标准的XML文件的起始行,version='1.0'表明XML的版本,encoding='UTF-8'表明XML文件的编码方式 -->
+
+<!--表明解析本XML文件的DTD文档位置,DTD是Document Type Definition 的缩写,即文档类型的定义,
+XML解析器使用DTD文档来检查XML文件的合法性。
+hibernate.sourceforge.net/hibernate-configuration-3.0dtd可以在Hibernate3.1.3软件包中的
+src\org\hibernate目录中找到此文件-->   
+<!DOCTYPE hibernate-configuration PUBLIC
+          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
+          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
+
+<!--声明Hibernate配置文件的开始 -->
+<hibernate-configuration>
+
+    <!--表明以下的配置是针对session-factory配置的,SessionFactory是Hibernate中的一个类,
+    这个类主要负责保存HIbernate的配置信息,以及对Session的操作-->   
+    <session-factory>
+        <!--配置数据库的驱动程序,Hibernate在连接数据库时,需要用到数据库的驱动程序-必须 -->
+        <property name="connection.driver_class">
+            com.mysql.jdbc.Driver
+        </property>
+        <!--设置数据库的连接url:jdbc:mysql://127.0.0.1:3306/hib,其中127.0.0.1表示mysql服务器名称,
+        3306是连接端口,此处为本机,hib是数据库名-必须 -->
+        <property name="connection.url">
+            jdbc:mysql://127.0.0.1:3306/hib
+        </property>
+        <!-- 设置数据库的用户名 -必须 -->
+        <property name="connection.username">root</property>
+        <!-- 设置数据库的密码 -必须 -->
+        <property name="connection.password">1234</property>
+        <!--数据库连接池的大小 -->
+        <!-- <property name="connection.pool.size">20 </property> 与下句是一样的 -->
+        <property name="hibernate.connection.pool.size">20 </property>
+
+        <!--是否在后台显示Hibernate用到的SQL语句,开发时设置为true,便于查错,
+        程序运行时可以在Eclipse的控制台显示Hibernate的执行Sql语句。
+        项目部署后可以设置为false,提高运行效率-->   
+        <property name="hibernate.show_sql">true </property>   
+
+        <!--jdbc.fetch_size是指Hibernate每次从数据库中取出并放到JDBC的Statement中的记录条数。
+        Fetch Size设的越大,读数据库的次数越少,速度越快,Fetch Size越小,读数据库的次数越多,速度越慢-->   
+        <property name="jdbc.fetch_size">50 </property> 
+
+        <!--jdbc.batch_size是指Hibernate批量插入,删除和更新时每次操作的记录数。
+        Batch Size越大,批量操作的向数据库发送Sql的次数越少,速度就越快,同样耗用内存就越大-->   
+        <property name="jdbc.batch_size">23 </property>  
+
+        <!--jdbc.use_scrollable_resultset是否允许Hibernate用JDBC的可滚动的结果集。
+        对分页的结果集。对分页时的设置非常有帮助-->   
+        <property name="jdbc.use_scrollable_resultset">false </property> 
+
+        <!--connection.useUnicode连接数据库时是否使用Unicode编码-->   
+        <property name="connection.useUnicode">true</property>   
+        <!--connection.characterEncoding连接数据库时数据的传输字符集编码方式-->   
+        <property name="connection.characterEncoding">utf-8</property> 
+
+
+<!--hibernate.dialect 只是Hibernate使用的数据库方言,就是要用Hibernate连接那种类型的数据库服务器。-->   
+        <!--这句不用管,照写就是 -必须 -->
+        <property name="dialect">
+            org.hibernate.dialect.MySQLDialect
+        </property>
+
+        <!-- 指定映射文件为“cn/hncu/domain/Student.hbm.xml”,可以有多个 -用到了就必须 -->
+        <mapping resource="cn/hncu/domain/Student.hbm.xml" />
+    </session-factory>
+
+</hibernate-configuration>
+ +

简单配置版:

+ + + +
<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE hibernate-configuration PUBLIC
+          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
+          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
+<hibernate-configuration>
+<!-- 这是最简单的配置版!!! -->
+<session-factory>
+    <property name="connection.driver_class">
+        com.mysql.jdbc.Driver
+    </property>
+    <property name="connection.url">
+        jdbc:mysql://127.0.0.1:3306/hib
+    </property>
+    <property name="connection.username">root</property>
+    <property name="connection.password">1234</property>
+
+    <property name="dialect">
+        org.hibernate.dialect.MySQLDialect
+    </property>
+
+    <mapping resource="cn/hncu/domain/Student.hbm.xml"/>
+</session-factory>
+
+</hibernate-configuration>
+ +

Hibernate核心接口

+ +

(1) Configuration接口

+ +

Configuration 接口负责管理Hibernate 的配置信息。为了能够连上数据库必须配置一些属性,这些属性包括:
+数据库URL
+数据库用户
+数据库用户密码
+数据库JDBC驱动类
+数据库dialect,用于对特定数据库提供支持,其中包含了针对特定数据库特性的实现。

+ + + +
 /*创建一个配置对象,读取配置文件*/
+ Configuration config = new Configuration();
+ config.configure("/hibernate.cfg.xml");
+
+ + + +

(2) SessionFactory接口

+ +

应用程序从SessionFactory(会话工厂)里获得Session(会话)实例。
+这里用到了一个设计模式即工厂模式,用户程序从工厂类SessionFactory中取得Session的实例。
+SessionFactory不是轻量级的。它占的资源比较多,所以它应该能在整个应用中共享。
+一个项目通常只需要一个SessionFactory就够了,但是当项目要操作多个数据库时,必须为每个数据库指定一个SessionFactory。
+会话工厂缓存了生成的SQL语句和Hibernate在运行时使用的映射元数据。它也保存了在一个工作单元中读入的数据并且可能在以后的工作单元中被重用(只有类和集合映射指定了使用这种二级缓存时才会如此)Session类。

+ +
/*通过配置对象产生一个会话工厂*/
+    SessionFactory factory=config.buildSessionFactory();
+
+ + + +

(3) Session接口

+ +

该接口是Hibernate使用最多的接口。Session不是线程安全的,它代表与数据库之间的一次操作。
+Session是持久层操作的基础,相当于JDBC中的Connection。然而在Hibernate中,实例化的Session是一个轻量级的类,创建和销毁它都不会占用很多资源。
+Session通过SessionFactory打开,在所有的工作完成后,需要关闭。但如果在程序中,不断地创建以及销毁Session对象,则会给系统带来不良影响。所以有时需要考虑session的管理合理的创建合理的销毁。

+ + + +
/*通过工厂产生一个会话*/
+     Session session=factory.openSession();
+
+ + + +

(4) Query类

+ +

Query类可以很方便地对数据库及持久对象进行查询,它可以有两种表达方式:查询语句使用HQL(面向”值对象”,HQL语言) (HQL是Hibernate Query Lanaguage简称是Hibernate配备了一种非常强大的查询语言,类似于SQL)或者本地数据库的SQL语句(面向”数据表”,SQL语言)编写。

+ + + +
/*通过会话产生一个查询对象*/
+        Query query = session.createQuery("from Student");//Student是POJO类,需要在配置文件中设置好映射
+        /*通过查询对象查询数据库,返回集合*/
+        List list = query.list();
+        for (int i = 0; i < list.size(); i++) {
+            Student student= (Student) list.get(i);
+            System.out.println(Student.getDname());
+        }
+ + + +

(5) Transaction接口

+ +

如果你向数据库中增加数据或修改数据时,需要使用事务处理,这时你需要Transaction接口。
+ Transaction接口是对实际事务实现的一个抽象,该接口可以实现JDBC的事务、JTA中的UserTransaction、甚至可以是CORBA事务等跨容器的事务。
+ 之所以这样设计是能让开发者能够使用一个统一事务的操作界面,使得自己的项目可以在不同的环境和容器之间方便地移值。

+ + + +

一个完整示例,显示了Hibernate编程基本思路

+ + + +

首先,准备好实例数据库:

+ +
create database hib charset=utf8;
+use hib;
+create table students(
+    sId varchar(8) primary key,
+    sName varchar(40),
+    sAge int
+);
+insert into students(sId,sName,sAge) values('S001','Jack',23);
+insert into students(sId,sName,sAge) values('S002','Tom',25);
+insert into students(sId,sName,sAge) values('S003','张三',43);
+insert into students(sId,sName,sAge) values('S004','李四',55);
+ +

准备好必要的jar包。

+ +

接下来配置好hibernate.cfg.xml文件:

+ +

前面有的,就不重复了,配个图好了。
+

+ + + +

POJO类:

+ + + +
package cn.hncu.domain;
+
+public class Student {
+    private String sId;
+    private String sName;
+    private Integer sAge;
+
+    public Student() {
+        super();
+    }
+    public String getsId() {
+        return sId;
+    }
+    public void setsId(String sId) {
+        this.sId = sId;
+    }
+    public String getsName() {
+        return sName;
+    }
+    public void setsName(String sName) {
+        this.sName = sName;
+    }
+    public Integer getsAge() {
+        return sAge;
+    }
+    public void setsAge(Integer sAge) {
+        this.sAge = sAge;
+    }
+    @Override
+    public String toString() {
+        return "Student [sId=" + sId + ", sName=" + sName + ", sAge=" + sAge
+                + "]";
+    }
+}
+
+ + + +

cn/hncu/domain/Student.hbm.xml映射文件

+ + + +
<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<hibernate-mapping package="cn.hncu.domain">
+
+    <!--name指的是POJO类的类名,table是数据库的表名,catalog是数据库的名称  -->
+    <class name="Student" table="students" catalog="hib">
+        <!--id表示此字段为数据库的主键,这里也可以用property来写,name为Student类的成员变量名,type为类型的包全名  -->
+        <id name="sId" type="java.lang.String">
+            <!--column表示映射的数据库的字段,name表示数据库中字段名,length表示varchar/char型的长度  -->
+            <column name="sId" length="8"></column>
+        </id>
+        <property name="sName" type="java.lang.String">
+            <column name="sName" length="40" />
+        </property>
+        <property name="sAge" type="java.lang.Integer">
+            <column name="sAge" />
+        </property>
+    </class>
+
+</hibernate-mapping>
+ + + +

HibernateSessionFactory

+ + + +
package cn.hncu.hib;
+
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.cfg.Configuration;
+
+public class HibernateSessionFactory {
+   private static String configFile = "/hibernate.cfg.xml";
+   private static Configuration config = new Configuration();
+   private static SessionFactory sessionFactory =null;
+
+   private static final ThreadLocal<Session> t = new ThreadLocal<Session>();
+
+   static{
+       try {
+           /*创建一个配置对象,读取配置文件*/
+           config.configure(configFile);
+           /*通过配置对象产生一个会话工厂类*/
+           sessionFactory = config.buildSessionFactory();
+        } catch (HibernateException e) {
+            e.printStackTrace();
+        }
+   }
+
+   public static Session getSession() throws HibernateException{
+       Session session = t.get();
+       if(session == null || !session.isOpen()){
+           if(sessionFactory==null){
+               rebuildSessionFactory();
+           }
+           /*通过会话工厂类产生一个会话实例*/
+           session = (sessionFactory!=null) ? sessionFactory.openSession() : null;
+           t.set(session);
+       }
+       return session;
+   }
+
+   private static void rebuildSessionFactory() {
+       try {
+           config.configure(configFile);
+           sessionFactory = config.buildSessionFactory();
+        } catch (HibernateException e) {
+            e.printStackTrace();
+        }
+   }
+
+   //关闭与数据库的会话
+   public static void closeSession() throws HibernateException{
+       Session session = t.get();
+       t.set(null);
+       if(session!=null){
+           session.close();
+       }
+   }
+}
+ + + +

TestHib

+ + + +
package cn.hncu;
+
+import java.util.List;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.cfg.Configuration;
+
+import cn.hncu.domain.Student;
+import cn.hncu.hib.HibernateSessionFactory;
+
+public class TestHib {
+
+    public static void main(String[] args) {
+        /*创建一个配置对象,读取配置文件*/
+        String configfile="/hibernate.cfg.xml";
+        Configuration config=new Configuration();
+        config.configure(configfile);
+        /*通过配置对象产生一个会话工厂类*/
+        SessionFactory sessionfactory=config.buildSessionFactory();
+        /*通过会话工厂类产生一个会话实例*/
+        Session session=sessionfactory.openSession();
+        /*通过会话产生一个查询对象Query*/
+        Query query=session.createQuery("from Student");
+        /*进行查询返回一个集合List*/
+        List<Student> studs=query.list();
+        for(Student s:studs){
+           System.out.println(s);
+        }
+
+        session = HibernateSessionFactory.getSession();
+        query = session.createQuery("from Student");
+        List<Student> students = query.list();
+        for(Student s: students){
+            System.out.println(s);
+        }
+    }
+}
+
+ + + +

测试结果:

+ +

+ +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ \ No newline at end of file diff --git a/Hibernate/myHibWebDemo/WebRoot/META-INF/MANIFEST.MF b/Hibernate/myHibWebDemo/WebRoot/META-INF/MANIFEST.MF new file mode 100644 index 0000000..254272e --- /dev/null +++ b/Hibernate/myHibWebDemo/WebRoot/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/cn/hncu/TestHib.class b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/cn/hncu/TestHib.class new file mode 100644 index 0000000..2317d1d Binary files /dev/null and b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/cn/hncu/TestHib.class differ diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.class b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.class new file mode 100644 index 0000000..ebc5b4b Binary files /dev/null and b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.class differ diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.hbm.xml b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.hbm.xml new file mode 100644 index 0000000..70c4621 --- /dev/null +++ b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/cn/hncu/domain/Student.hbm.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/cn/hncu/hib/HibernateSessionFactory.class b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/cn/hncu/hib/HibernateSessionFactory.class new file mode 100644 index 0000000..5efc31a Binary files /dev/null and b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/cn/hncu/hib/HibernateSessionFactory.class differ diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/hibernate.cfg.xml b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/hibernate.cfg.xml new file mode 100644 index 0000000..3217ef7 --- /dev/null +++ b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/hibernate.cfg.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + com.mysql.jdbc.Driver + + + + jdbc:mysql://127.0.0.1:3306/hib + + + root + + 1234 + + + 20 + + + true + + + 50 + + + 23 + + + false + + + true + + utf-8 + + + + + + org.hibernate.dialect.MySQLDialect + + + + + + + \ No newline at end of file diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/hibernate1.cfg.xml b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/hibernate1.cfg.xml new file mode 100644 index 0000000..5ff1d2c --- /dev/null +++ b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/classes/hibernate1.cfg.xml @@ -0,0 +1,24 @@ + + + + + + + com.mysql.jdbc.Driver + + + jdbc:mysql://127.0.0.1:3306/hib + + root + 1234 + + + org.hibernate.dialect.MySQLDialect + + + + + + \ No newline at end of file diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/antlr-2.7.7.jar b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/antlr-2.7.7.jar new file mode 100644 index 0000000..5e5f14b Binary files /dev/null and b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/antlr-2.7.7.jar differ diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/classmate-1.3.0.jar b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/classmate-1.3.0.jar new file mode 100644 index 0000000..049b63f Binary files /dev/null and b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/classmate-1.3.0.jar differ diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/dom4j-1.6.1.jar b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/dom4j-1.6.1.jar new file mode 100644 index 0000000..c8c4dbb Binary files /dev/null and b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/dom4j-1.6.1.jar differ diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/geronimo-jta_1.1_spec-1.1.1.jar b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/geronimo-jta_1.1_spec-1.1.1.jar new file mode 100644 index 0000000..ee9963d Binary files /dev/null and b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/geronimo-jta_1.1_spec-1.1.1.jar differ diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/hibernate-commons-annotations-5.0.1.Final.jar b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/hibernate-commons-annotations-5.0.1.Final.jar new file mode 100644 index 0000000..82e425d Binary files /dev/null and b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/hibernate-commons-annotations-5.0.1.Final.jar differ diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/hibernate-core-5.1.1.Final.jar b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/hibernate-core-5.1.1.Final.jar new file mode 100644 index 0000000..bbd38a3 Binary files /dev/null and b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/hibernate-core-5.1.1.Final.jar differ diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/hibernate-jpa-2.1-api-1.0.0.Final.jar b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/hibernate-jpa-2.1-api-1.0.0.Final.jar new file mode 100644 index 0000000..e2f2c59 Binary files /dev/null and b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/hibernate-jpa-2.1-api-1.0.0.Final.jar differ diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/jandex-2.0.0.Final.jar b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/jandex-2.0.0.Final.jar new file mode 100644 index 0000000..d24086a Binary files /dev/null and b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/jandex-2.0.0.Final.jar differ diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/javassist-3.20.0-GA.jar b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/javassist-3.20.0-GA.jar new file mode 100644 index 0000000..0f1ff72 Binary files /dev/null and b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/javassist-3.20.0-GA.jar differ diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/jboss-logging-3.3.0.Final.jar b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/jboss-logging-3.3.0.Final.jar new file mode 100644 index 0000000..ea45d4d Binary files /dev/null and b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/jboss-logging-3.3.0.Final.jar differ diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.39-bin.jar b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.39-bin.jar new file mode 100644 index 0000000..dac6e14 Binary files /dev/null and b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.39-bin.jar differ diff --git a/Hibernate/myHibWebDemo/WebRoot/WEB-INF/web.xml b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/web.xml new file mode 100644 index 0000000..16d4d82 --- /dev/null +++ b/Hibernate/myHibWebDemo/WebRoot/WEB-INF/web.xml @@ -0,0 +1,11 @@ + + + + + index.jsp + + diff --git a/Hibernate/myHibWebDemo/WebRoot/index.jsp b/Hibernate/myHibWebDemo/WebRoot/index.jsp new file mode 100644 index 0000000..19ce291 --- /dev/null +++ b/Hibernate/myHibWebDemo/WebRoot/index.jsp @@ -0,0 +1,26 @@ +<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> +<% +String path = request.getContextPath(); +String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; +%> + + + + + + + My JSP 'index.jsp' starting page + + + + + + + + + + This is my JSP page.
+ + diff --git a/Hibernate/myHibWebDemo/myHibWebDemo.zip b/Hibernate/myHibWebDemo/myHibWebDemo.zip new file mode 100644 index 0000000..b2648f2 Binary files /dev/null and b/Hibernate/myHibWebDemo/myHibWebDemo.zip differ diff --git a/Hibernate/myHibWebDemo/src/cn/hncu/TestHib.java b/Hibernate/myHibWebDemo/src/cn/hncu/TestHib.java new file mode 100644 index 0000000..04327db --- /dev/null +++ b/Hibernate/myHibWebDemo/src/cn/hncu/TestHib.java @@ -0,0 +1,39 @@ +package cn.hncu; + +import java.util.List; + +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +import cn.hncu.domain.Student; +import cn.hncu.hib.HibernateSessionFactory; + +public class TestHib { + + public static void main(String[] args) { + /*创建一个配置对象,读取配置文件*/ + String configfile="/hibernate.cfg.xml"; + Configuration config=new Configuration(); + config.configure(configfile); + /*通过配置对象产生一个会话工厂类*/ + SessionFactory sessionfactory=config.buildSessionFactory(); + /*通过会话工厂类产生一个会话实例*/ + Session session=sessionfactory.openSession(); + /*通过会话产生一个查询对象Query*/ + Query query=session.createQuery("from Student"); + /*进行查询返回一个集合List*/ + List studs=query.list(); + for(Student s:studs){ + System.out.println(s); + } + + session = HibernateSessionFactory.getSession(); + query = session.createQuery("from Student"); + List students = query.list(); + for(Student s: students){ + System.out.println(s); + } + } +} diff --git a/Hibernate/myHibWebDemo/src/cn/hncu/domain/Student.hbm.xml b/Hibernate/myHibWebDemo/src/cn/hncu/domain/Student.hbm.xml new file mode 100644 index 0000000..70c4621 --- /dev/null +++ b/Hibernate/myHibWebDemo/src/cn/hncu/domain/Student.hbm.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Hibernate/myHibWebDemo/src/cn/hncu/domain/Student.java b/Hibernate/myHibWebDemo/src/cn/hncu/domain/Student.java new file mode 100644 index 0000000..98e967c --- /dev/null +++ b/Hibernate/myHibWebDemo/src/cn/hncu/domain/Student.java @@ -0,0 +1,34 @@ +package cn.hncu.domain; + +public class Student { + private String sId; + private String sName; + private Integer sAge; + + public Student() { + super(); + } + public String getsId() { + return sId; + } + public void setsId(String sId) { + this.sId = sId; + } + public String getsName() { + return sName; + } + public void setsName(String sName) { + this.sName = sName; + } + public Integer getsAge() { + return sAge; + } + public void setsAge(Integer sAge) { + this.sAge = sAge; + } + @Override + public String toString() { + return "Student [sId=" + sId + ", sName=" + sName + ", sAge=" + sAge + + "]"; + } +} diff --git a/Hibernate/myHibWebDemo/src/cn/hncu/hib/HibernateSessionFactory.java b/Hibernate/myHibWebDemo/src/cn/hncu/hib/HibernateSessionFactory.java new file mode 100644 index 0000000..0b4652c --- /dev/null +++ b/Hibernate/myHibWebDemo/src/cn/hncu/hib/HibernateSessionFactory.java @@ -0,0 +1,58 @@ +package cn.hncu.hib; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class HibernateSessionFactory { + private static String configFile = "/hibernate.cfg.xml"; + private static Configuration config = new Configuration(); + private static SessionFactory sessionFactory =null; + + private static final ThreadLocal t = new ThreadLocal(); + + static{ + try { + /*创建一个配置对象,读取配置文件*/ + config.configure(configFile); + /*通过配置对象产生一个会话工厂类*/ + sessionFactory = config.buildSessionFactory(); + } catch (HibernateException e) { + e.printStackTrace(); + } + } + + public static Session getSession() throws HibernateException{ + Session session = t.get(); + if(session == null || !session.isOpen()){ + if(sessionFactory==null){ + rebuildSessionFactory(); + } + /*通过会话工厂类产生一个会话实例*/ + session = (sessionFactory!=null) ? sessionFactory.openSession() : null; + t.set(session); + } + return session; + } + + private static void rebuildSessionFactory() { + try { + config.configure(configFile); + sessionFactory = config.buildSessionFactory(); + } catch (HibernateException e) { + e.printStackTrace(); + } + } + + //关闭与数据库的会话 + public static void closeSession() throws HibernateException{ + Session session = t.get(); + t.set(null); + if(session!=null){ + session.close(); + } + } + + +} diff --git a/Hibernate/myHibWebDemo/src/hibernate.cfg.xml b/Hibernate/myHibWebDemo/src/hibernate.cfg.xml new file mode 100644 index 0000000..3217ef7 --- /dev/null +++ b/Hibernate/myHibWebDemo/src/hibernate.cfg.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + com.mysql.jdbc.Driver + + + + jdbc:mysql://127.0.0.1:3306/hib + + + root + + 1234 + + + 20 + + + true + + + 50 + + + 23 + + + false + + + true + + utf-8 + + + + + + org.hibernate.dialect.MySQLDialect + + + + + + + \ No newline at end of file diff --git a/Hibernate/myHibWebDemo/src/hibernate1.cfg.xml b/Hibernate/myHibWebDemo/src/hibernate1.cfg.xml new file mode 100644 index 0000000..5ff1d2c --- /dev/null +++ b/Hibernate/myHibWebDemo/src/hibernate1.cfg.xml @@ -0,0 +1,24 @@ + + + + + + + com.mysql.jdbc.Driver + + + jdbc:mysql://127.0.0.1:3306/hib + + root + 1234 + + + org.hibernate.dialect.MySQLDialect + + + + + + \ No newline at end of file diff --git "a/Hibernate/myHibWebDemo/\343\200\220\346\241\206\346\236\266\343\200\221[Hibernate]\346\236\204\346\236\266\347\237\245\350\257\206\347\202\271\350\257\246\347\273\206\350\247\243\346\236\220.html" "b/Hibernate/myHibWebDemo/\343\200\220\346\241\206\346\236\266\343\200\221[Hibernate]\346\236\204\346\236\266\347\237\245\350\257\206\347\202\271\350\257\246\347\273\206\350\247\243\346\236\220.html" new file mode 100644 index 0000000..c2e1e8c --- /dev/null +++ "b/Hibernate/myHibWebDemo/\343\200\220\346\241\206\346\236\266\343\200\221[Hibernate]\346\236\204\346\236\266\347\237\245\350\257\206\347\202\271\350\257\246\347\273\206\350\247\243\346\236\220.html" @@ -0,0 +1,454 @@ + + + + + +【框架】[Hibernate]构架知识点详细解析 + + + +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ + + +

Hibernate介绍:

+ +

Hibernate是一个开放源码的、非常优秀、成熟的O/R Mapping框架。它提供了强大、高性能的Java对象和关系数据的持久化和查询功能。

+ +

O/R Mapping
+对象关系映射(Object Relational Mapping,简称ORM)技术,是通过使用描述对象和数据库之间映射的元数据,将Java程序中的对象自动持久化到关系数据库中。
+对象和关系数据是业务实体的两种表现形式,业务实体在内存中表现为对象,在数据库中表现为关系数据。内存中的对象之间存在关联和继承关系,而在数据库中,关系数据无法直接表达多对多关联和继承关系。因此,对象-关系映射(ORM)系统一般以中间件的形式存在,主要实现程序对象到关系数据库数据的映射。

+ +

Hibernate 只是一个将持久化类与数据库表相映射的工具,每个持久化类实例均对应于数据库表中的一条数据行。可以使用面向对象的方法操作此持久化类实例,完成对数据库表的插入、删除、修改等操作。

+ +

利用Hibernate操作数据库,我们通过应用程序经过Hibernate持久层来访问数据库,其实Hibernate完成了以前JDBC的功能,不过Hibernate使用面向对象的方法操作数据库。

+ + + +

Hibernate体系结构图:

+ +

+ + + +

Hibernate构架入门步骤

+ +

第1步: 先建一个Java工程导入使用Hibernate最小必要包。
+一般在解压后的lib目录下的
+
+required目录下。
+可以到官方网站 http://hibernate.org/orm/downloads/ 下载Hibernate最新的zip压缩包。
+如果访问数据库,则还需要导入数据库的驱动包。
+mysql-connector-java-5.1.39 .zip下载地址:

+ +
+

–>点击下载数据库5.1.39驱动包–
+

+ +

第2步:在src创建配置文件hibernate.cfg.xml,放置在src目录下。

+ +

第3步:编写一个会话工厂类。通过会话工厂类产生一个会话Session对象。Session对象是Hibernate的核心。任何对数据库操作都在会话中进行的。

+ +

对于熟悉C3P0的朋友,可以按下面的理解:
+(配置文件hibernate.cfg.xml可以类比c3p0.properties的配置文件,HibernateSessionFactory可以类比C3p0Pool,SessionFactory可以类比C3p0中的DataSource,Session可以类比Connection去理解)

+ +

第4步:编写POJO类以及映射文件。
+POJO(POJO(Plain Ordinary Java Object)简单的Java对象,实际就是普通JavaBeans)

+ +

第5步:编写测试文件

+ +

hibernate.cfg.xml配置文件详解

+ +

hibernate.cfg.xml其实这个名字自己可以随便取的,但是大家都这么取名,于是形成了一个习惯了!!!

+ +
<?xml version='1.0' encoding='UTF-8'?>
+<!--标准的XML文件的起始行,version='1.0'表明XML的版本,encoding='UTF-8'表明XML文件的编码方式 -->
+
+<!--表明解析本XML文件的DTD文档位置,DTD是Document Type Definition 的缩写,即文档类型的定义,
+XML解析器使用DTD文档来检查XML文件的合法性。
+hibernate.sourceforge.net/hibernate-configuration-3.0dtd可以在Hibernate3.1.3软件包中的
+src\org\hibernate目录中找到此文件-->   
+<!DOCTYPE hibernate-configuration PUBLIC
+          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
+          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
+
+<!--声明Hibernate配置文件的开始 -->
+<hibernate-configuration>
+
+    <!--表明以下的配置是针对session-factory配置的,SessionFactory是Hibernate中的一个类,
+    这个类主要负责保存HIbernate的配置信息,以及对Session的操作-->   
+    <session-factory>
+        <!--配置数据库的驱动程序,Hibernate在连接数据库时,需要用到数据库的驱动程序-必须 -->
+        <property name="connection.driver_class">
+            com.mysql.jdbc.Driver
+        </property>
+        <!--设置数据库的连接url:jdbc:mysql://127.0.0.1:3306/hib,其中127.0.0.1表示mysql服务器名称,
+        3306是连接端口,此处为本机,hib是数据库名-必须 -->
+        <property name="connection.url">
+            jdbc:mysql://127.0.0.1:3306/hib
+        </property>
+        <!-- 设置数据库的用户名 -必须 -->
+        <property name="connection.username">root</property>
+        <!-- 设置数据库的密码 -必须 -->
+        <property name="connection.password">1234</property>
+        <!--数据库连接池的大小 -->
+        <!-- <property name="connection.pool.size">20 </property> 与下句是一样的 -->
+        <property name="hibernate.connection.pool.size">20 </property>
+
+        <!--是否在后台显示Hibernate用到的SQL语句,开发时设置为true,便于查错,
+        程序运行时可以在Eclipse的控制台显示Hibernate的执行Sql语句。
+        项目部署后可以设置为false,提高运行效率-->   
+        <property name="hibernate.show_sql">true </property>   
+
+        <!--jdbc.fetch_size是指Hibernate每次从数据库中取出并放到JDBC的Statement中的记录条数。
+        Fetch Size设的越大,读数据库的次数越少,速度越快,Fetch Size越小,读数据库的次数越多,速度越慢-->   
+        <property name="jdbc.fetch_size">50 </property> 
+
+        <!--jdbc.batch_size是指Hibernate批量插入,删除和更新时每次操作的记录数。
+        Batch Size越大,批量操作的向数据库发送Sql的次数越少,速度就越快,同样耗用内存就越大-->   
+        <property name="jdbc.batch_size">23 </property>  
+
+        <!--jdbc.use_scrollable_resultset是否允许Hibernate用JDBC的可滚动的结果集。
+        对分页的结果集。对分页时的设置非常有帮助-->   
+        <property name="jdbc.use_scrollable_resultset">false </property> 
+
+        <!--connection.useUnicode连接数据库时是否使用Unicode编码-->   
+        <property name="connection.useUnicode">true</property>   
+        <!--connection.characterEncoding连接数据库时数据的传输字符集编码方式-->   
+        <property name="connection.characterEncoding">utf-8</property> 
+
+
+<!--hibernate.dialect 只是Hibernate使用的数据库方言,就是要用Hibernate连接那种类型的数据库服务器。-->   
+        <!--这句不用管,照写就是 -必须 -->
+        <property name="dialect">
+            org.hibernate.dialect.MySQLDialect
+        </property>
+
+        <!-- 指定映射文件为“cn/hncu/domain/Student.hbm.xml”,可以有多个 -用到了就必须 -->
+        <mapping resource="cn/hncu/domain/Student.hbm.xml" />
+    </session-factory>
+
+</hibernate-configuration>
+ +

简单配置版:

+ + + +
<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE hibernate-configuration PUBLIC
+          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
+          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
+<hibernate-configuration>
+<!-- 这是最简单的配置版!!! -->
+<session-factory>
+    <property name="connection.driver_class">
+        com.mysql.jdbc.Driver
+    </property>
+    <property name="connection.url">
+        jdbc:mysql://127.0.0.1:3306/hib
+    </property>
+    <property name="connection.username">root</property>
+    <property name="connection.password">1234</property>
+
+    <property name="dialect">
+        org.hibernate.dialect.MySQLDialect
+    </property>
+
+    <mapping resource="cn/hncu/domain/Student.hbm.xml"/>
+</session-factory>
+
+</hibernate-configuration>
+ +

Hibernate核心接口

+ +

(1) Configuration接口

+ +

Configuration 接口负责管理Hibernate 的配置信息。为了能够连上数据库必须配置一些属性,这些属性包括:
+数据库URL
+数据库用户
+数据库用户密码
+数据库JDBC驱动类
+数据库dialect,用于对特定数据库提供支持,其中包含了针对特定数据库特性的实现。

+ + + +
 /*创建一个配置对象,读取配置文件*/
+ Configuration config = new Configuration();
+ config.configure("/hibernate.cfg.xml");
+
+ + + +

(2) SessionFactory接口

+ +

应用程序从SessionFactory(会话工厂)里获得Session(会话)实例。
+这里用到了一个设计模式即工厂模式,用户程序从工厂类SessionFactory中取得Session的实例。
+SessionFactory不是轻量级的。它占的资源比较多,所以它应该能在整个应用中共享。
+一个项目通常只需要一个SessionFactory就够了,但是当项目要操作多个数据库时,必须为每个数据库指定一个SessionFactory。
+会话工厂缓存了生成的SQL语句和Hibernate在运行时使用的映射元数据。它也保存了在一个工作单元中读入的数据并且可能在以后的工作单元中被重用(只有类和集合映射指定了使用这种二级缓存时才会如此)Session类。

+ +
/*通过配置对象产生一个会话工厂*/
+    SessionFactory factory=config.buildSessionFactory();
+
+ + + +

(3) Session接口

+ +

该接口是Hibernate使用最多的接口。Session不是线程安全的,它代表与数据库之间的一次操作。
+Session是持久层操作的基础,相当于JDBC中的Connection。然而在Hibernate中,实例化的Session是一个轻量级的类,创建和销毁它都不会占用很多资源。
+Session通过SessionFactory打开,在所有的工作完成后,需要关闭。但如果在程序中,不断地创建以及销毁Session对象,则会给系统带来不良影响。所以有时需要考虑session的管理合理的创建合理的销毁。

+ + + +
/*通过工厂产生一个会话*/
+     Session session=factory.openSession();
+
+ + + +

(4) Query类

+ +

Query类可以很方便地对数据库及持久对象进行查询,它可以有两种表达方式:查询语句使用HQL(面向”值对象”,HQL语言) (HQL是Hibernate Query Lanaguage简称是Hibernate配备了一种非常强大的查询语言,类似于SQL)或者本地数据库的SQL语句(面向”数据表”,SQL语言)编写。

+ + + +
/*通过会话产生一个查询对象*/
+        Query query = session.createQuery("from Student");//Student是POJO类,需要在配置文件中设置好映射
+        /*通过查询对象查询数据库,返回集合*/
+        List list = query.list();
+        for (int i = 0; i < list.size(); i++) {
+            Student student= (Student) list.get(i);
+            System.out.println(Student.getDname());
+        }
+ + + +

(5) Transaction接口

+ +

如果你向数据库中增加数据或修改数据时,需要使用事务处理,这时你需要Transaction接口。
+ Transaction接口是对实际事务实现的一个抽象,该接口可以实现JDBC的事务、JTA中的UserTransaction、甚至可以是CORBA事务等跨容器的事务。
+ 之所以这样设计是能让开发者能够使用一个统一事务的操作界面,使得自己的项目可以在不同的环境和容器之间方便地移值。

+ + + +

一个完整示例,显示了Hibernate编程基本思路

+ + + +

首先,准备好实例数据库:

+ +
create database hib charset=utf8;
+use hib;
+create table students(
+    sId varchar(8) primary key,
+    sName varchar(40),
+    sAge int
+);
+insert into students(sId,sName,sAge) values('S001','Jack',23);
+insert into students(sId,sName,sAge) values('S002','Tom',25);
+insert into students(sId,sName,sAge) values('S003','张三',43);
+insert into students(sId,sName,sAge) values('S004','李四',55);
+ +

准备好必要的jar包。

+ +

接下来配置好hibernate.cfg.xml文件:

+ +

前面有的,就不重复了,配个图好了。
+

+ + + +

POJO类:

+ + + +
package cn.hncu.domain;
+
+public class Student {
+    private String sId;
+    private String sName;
+    private Integer sAge;
+
+    public Student() {
+        super();
+    }
+    public String getsId() {
+        return sId;
+    }
+    public void setsId(String sId) {
+        this.sId = sId;
+    }
+    public String getsName() {
+        return sName;
+    }
+    public void setsName(String sName) {
+        this.sName = sName;
+    }
+    public Integer getsAge() {
+        return sAge;
+    }
+    public void setsAge(Integer sAge) {
+        this.sAge = sAge;
+    }
+    @Override
+    public String toString() {
+        return "Student [sId=" + sId + ", sName=" + sName + ", sAge=" + sAge
+                + "]";
+    }
+}
+
+ + + +

cn/hncu/domain/Student.hbm.xml映射文件

+ + + +
<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<hibernate-mapping package="cn.hncu.domain">
+
+    <!--name指的是POJO类的类名,table是数据库的表名,catalog是数据库的名称  -->
+    <class name="Student" table="students" catalog="hib">
+        <!--id表示此字段为数据库的主键,这里也可以用property来写,name为Student类的成员变量名,type为类型的包全名  -->
+        <id name="sId" type="java.lang.String">
+            <!--column表示映射的数据库的字段,name表示数据库中字段名,length表示varchar/char型的长度  -->
+            <column name="sId" length="8"></column>
+        </id>
+        <property name="sName" type="java.lang.String">
+            <column name="sName" length="40" />
+        </property>
+        <property name="sAge" type="java.lang.Integer">
+            <column name="sAge" />
+        </property>
+    </class>
+
+</hibernate-mapping>
+ + + +

HibernateSessionFactory

+ + + +
package cn.hncu.hib;
+
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.cfg.Configuration;
+
+public class HibernateSessionFactory {
+   private static String configFile = "/hibernate.cfg.xml";
+   private static Configuration config = new Configuration();
+   private static SessionFactory sessionFactory =null;
+
+   private static final ThreadLocal<Session> t = new ThreadLocal<Session>();
+
+   static{
+       try {
+           /*创建一个配置对象,读取配置文件*/
+           config.configure(configFile);
+           /*通过配置对象产生一个会话工厂类*/
+           sessionFactory = config.buildSessionFactory();
+        } catch (HibernateException e) {
+            e.printStackTrace();
+        }
+   }
+
+   public static Session getSession() throws HibernateException{
+       Session session = t.get();
+       if(session == null || !session.isOpen()){
+           if(sessionFactory==null){
+               rebuildSessionFactory();
+           }
+           /*通过会话工厂类产生一个会话实例*/
+           session = (sessionFactory!=null) ? sessionFactory.openSession() : null;
+           t.set(session);
+       }
+       return session;
+   }
+
+   private static void rebuildSessionFactory() {
+       try {
+           config.configure(configFile);
+           sessionFactory = config.buildSessionFactory();
+        } catch (HibernateException e) {
+            e.printStackTrace();
+        }
+   }
+
+   //关闭与数据库的会话
+   public static void closeSession() throws HibernateException{
+       Session session = t.get();
+       t.set(null);
+       if(session!=null){
+           session.close();
+       }
+   }
+}
+ + + +

TestHib

+ + + +
package cn.hncu;
+
+import java.util.List;
+
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.cfg.Configuration;
+
+import cn.hncu.domain.Student;
+import cn.hncu.hib.HibernateSessionFactory;
+
+public class TestHib {
+
+    public static void main(String[] args) {
+        /*创建一个配置对象,读取配置文件*/
+        String configfile="/hibernate.cfg.xml";
+        Configuration config=new Configuration();
+        config.configure(configfile);
+        /*通过配置对象产生一个会话工厂类*/
+        SessionFactory sessionfactory=config.buildSessionFactory();
+        /*通过会话工厂类产生一个会话实例*/
+        Session session=sessionfactory.openSession();
+        /*通过会话产生一个查询对象Query*/
+        Query query=session.createQuery("from Student");
+        /*进行查询返回一个集合List*/
+        List<Student> studs=query.list();
+        for(Student s:studs){
+           System.out.println(s);
+        }
+
+        session = HibernateSessionFactory.getSession();
+        query = session.createQuery("from Student");
+        List<Student> students = query.list();
+        for(Student s: students){
+            System.out.println(s);
+        }
+    }
+}
+
+ + + +

测试结果:

+ +

+ +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ \ No newline at end of file diff --git a/README.md b/README.md index 0ea7ed1..3f222ee 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,62 @@ -Java项目与知识点相关 +文件名与介绍: + +[Database-support-package]-数据库需要用到的-c3p0/dbcp/dbUtils工具支持包 + +[Hibernate]利用Hibernate进行一对多的级联操作-Web实例 + +[Java_MySQL_jar]-数据库连接支持包 + +[JavaMail]-收发邮件支持包 + +[Java_MySQL_jar]Java访问数据库需要的包 + +[Spring]基于Spring框架的Web应用演示(附带cglib工具进行动态代理) + +[Tomcat7.0]Tomcat7版本安装包 + +[UltraISO]制作U盘启动盘需要的 + +[log4j_jar]log4j的支持包 + +[myAutoLoginWeb]过滤器Filter学习-实现用户的自动登录与IP黑名单过滤 + +[myBookStore]单机版的书店管理系统 + +[myDbPoolUse]C3P0连接池配置/DBCP连接池配置/Apache的DBUtils框架使用 + +[myFilterDemoWeb]过滤器Filter学习-设置全站编码与设置页面缓存 + +[myGzipWeb]全站压缩 + +[myJavaMainDemo]Java-QQ邮箱发送邮件-以及带附件 + +[myLog4jTest]log4j使用实例-----记录日志 + +[myMailWeb]网站注册-QQ邮箱发送激活邮箱,点击注册-实例 + +[myOnlinesWeb]网站在线用户信息,网站访问量... + +[myOnlinesWeb2]网站在线用户信息,网站访问量以及管理员踢出用户实例 + +[myWordsFilterWeb]过滤器-敏感词过滤 + +[springBoot]看《Spring Boot》时的同步笔记与实例代码 + +[sqlTableToExcel]将数据库表格导入excel表格需要的包 + +[druid_spring_config] 【Druid】Druid监控SSM项目性能-配置与实例 + + + + + + + + + + + + + -Database-support-package: -c3p0工具支持包 -dbcp工具支持包 -dbUtils工具支持包 -数据库连接支持包 -JavaMail -JavaMail-收发邮件支持包 \ No newline at end of file diff --git a/Spring/README.md b/Spring/README.md new file mode 100644 index 0000000..5227c09 --- /dev/null +++ b/Spring/README.md @@ -0,0 +1,19 @@ +这里是Spring框架的相关文档、项目、JAR包等 + + + + + + + + + + + + + + + + + + diff --git a/Spring/mySpring3Demo/.classpath b/Spring/mySpring3Demo/.classpath new file mode 100644 index 0000000..ce5835b --- /dev/null +++ b/Spring/mySpring3Demo/.classpath @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/Spring/mySpring3Demo/.project b/Spring/mySpring3Demo/.project new file mode 100644 index 0000000..348e56e --- /dev/null +++ b/Spring/mySpring3Demo/.project @@ -0,0 +1,17 @@ + + + mySpring3Demo + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/Spring/mySpring3Demo/.settings/org.eclipse.jdt.core.prefs b/Spring/mySpring3Demo/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..9d08b89 --- /dev/null +++ b/Spring/mySpring3Demo/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +#Wed Aug 31 13:07:54 CST 2016 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/Spring/mySpring3Demo/README.md b/Spring/mySpring3Demo/README.md new file mode 100644 index 0000000..ee133b3 --- /dev/null +++ b/Spring/mySpring3Demo/README.md @@ -0,0 +1,728 @@ + + + + + +【框架】[Spring3]下载安装、开源框架与IoC控制反转详解 + + + +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ +

昨天刚刚初学Spring3,也许Spring3有点老了哈,不过还是先把3学了再去学习4吧,首先先介绍一下如何去下载Spring的必须包吧。
+(本篇博客适用于初学Spring的朋友)

+ +

java spring4现在不推荐使用xml配置文件…
+当然啦,这些知识点在Spring4还是可以用的。

+ +

不过我在这里详解的还是Spring3哈,见谅~

+ +

下载SpringJAR包/文档:

+ +

Spring官网:http://spring.io/

+ +

Spring3.2版本以后(JAR/文档)的下载地址:http://repo.springsource.org/libs-release-local/org/springframework/spring/
+(如果无法访问,请准备梯子)

+ +

+ +

选择一个需要下载的版本进去:
+我选择的是最新的4.3.2版本.

+ +

+ +

spring-framework-*(版本号).RELEASE-dist.zip 包含了Spring必须的JAR包、DOC文档以及源代码等。

+ +

下载完之后解压我们就可以在spring-framework-4.3.2.RELEASE\libs找到需要包和DOC文档以及源代码了。

+ +

+ +

由于最新版本的已经提倡基于Java Config和注解的配置,不采用xml配置了,所以,我在这里准备的是Spring3.1.1版本的:
+下载链接:
+https://github.com/chenhaoxiang/Java/blob/master/Spring/spring-framework-3.1.1.RELEASE.zip

+ +

Spring开源框架

+ + + +

Spring框架的起始:

+ +

Spring在英语中含义就是”春天”.
+对于Java EE开发者来说,Spring框架出现确实带来了一股全新的春天的气息。
+早在2002年,Rod Johson在其编著的《Expert one to one J2EE design and development》书中,对Java EE框架臃肿、低效、脱离现实的种种现状提出了很多质疑,并积极寻求探索革新之道。
+由他主导编写了interface21框架,从实际需求出发,着眼于轻便、灵巧,易于开发、测试和部署的轻量级开发框架。以interface21框架为基础,并集成了其它许多开源成果,于2004年3月24日,发布了1.0正式版取名为Spring。

+ + + +

Spring框架模块:

+ +

Spring的核心是个轻量级容器,实现了IoC(控制翻转)模式的容器,基于此核心容器所建立的应用程序,可以达到程序组件的松散耦合。这些特性都使得整个应用程序维护简化。 Spring框架核心由下图所示的七个模块组成。

+ +

+ +

现在来分别介绍一下这七个模块:

+ + + +

1、核心容器(Core)

+ +

这是Spring框架最基础的部分,它提供了依赖注入(Dependency Injection)特征来实现容器对Bean的管理。这里最基本的概念是BeanFactory,它是任何Spring应用的核心。BeanFactory是工厂模式的一个实现,它使用IoC将应用配置和依赖说明从实际的应用代码中分离出来。

+ + + +

2、AOP模块

+ +

AOP即面向切面编程技术,Spring在它的AOP模块中提供了对面向切面编程的丰富支持。AOP允许通过分离应用的业务逻辑与系统级服务(例如安全和事务管理)进行内聚性的开发。应用对象只实现它们应该做的——完成业务逻辑——仅此而已。它们并不负责其它的系统级关注点,例如日志或事务支持。

+ + + +

3、对象/关系映射集成模块ORM

+ +

Hibernate是成熟的ORM产品,Spring并没有自己实现ORM框架而是集成了几个流行的ORM产品如Hibernate、JDO和iBATIS等。可以利用Spring对这些模块提供事务支持等。

+ + + +

4、JDBC抽象和DAO模块

+ +

Spring虽然集成了几个ORM产品,但也可以不选择这几款产品,因为Spring提供了JDBC和DAO模块。该模块对现有的JDBC技术进行了优化。你可以保持你的数据库访问代码干净简洁,并且可以防止因关闭数据库资源失败而引起的问题。

+ +

[JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构管管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写的异常代码数量(例如打开和关闭连接)。SpringDAO的面向JDBC的异常遵从从通用的DAO异常层次结构]

+ +

5、Spring的Web模块

+ +

Web上下文模块建立于应用上下文模块之上,提供了一个适合于Web应用的上下文。另外,这个模块还提供了一些面向服务支持。例如:实现文件上传的multipart请求,它也提供了Spring和其它Web框架的集成,比如Struts、WebWork。

+ + + +

6、应用上下文(Context)模块

+ +

核心模块的BeanFactory使Spring成为一个容器,而上下文模块使它成为一个框架。Web上下文模块建立于应用上下文模块之上,提供了一个适合于Web应用的上下文。该模块还提供了一些面向服务支持这个模块扩展了BeanFactory的概念,增加了对国际化(I18N)消息、事件传播以及验证的支持。

+ +

另外,这个模块还提供了许多企业服务,例如电子邮件、JNDI访问、EJB集成、远程以及时序调度(scheduling)服务。也包括对模版框架例如Velocity和FreeMarker集成的支持。

+ +

7、Spring的MVC框架

+ +

Spring为构建Web应用提供了一个功能全面的MVC框架。虽然Spring可以很容易地与其它MVC框架集成,例如Struts2,但Spring的MVC框架使用IoC对控制逻辑和业务对象提供了完全的分离。

+ + + +

Spring入门示例

+ +

将需要的Jar包导入项目、

+ +

再准备一个xml配置文件:
+applicationContext.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:tx="http://www.springframework.org/schema/tx"
+        xsi:schemaLocation="http://www.springframework.org/schema/beans%20http://www.springframework.org/schema/beans/spring-beans-3.0.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/context%20http://www.springframework.org/schema/context/spring-context-3.0.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/tx%20http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
+
+</beans>
+
+ +

将Spring的压缩包解压后:你可以在spring-framework-3.1.1.RELEASE\projects\org.springframework.web.portlet\src\test\java\org\springframework\web\portlet\context\WEB-INF目录下找到applicationContext.xml。我们只需要这个部分就可以了。
+将文件建立在src目录下(建在另外的路径也可以)。

+ +

+ +

导入必须的包,和建好applicationContext.xml文件。

+ +

1、编写一个普通的Java类(JavaBean)

+ + + +
package cn.hncu.demo1.domain;
+
+public class Person {
+    private String name;
+    private int age;
+
+    public Person() {
+        System.out.println("执行Person的构造方法....");
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public int getAge() {
+        return age;
+    }
+
+    public void setAge(int age) {
+        this.age = age;
+    }
+
+    @Override
+    public String toString() {
+        return "Person [name=" + name + ", age=" + age + "]";
+    }
+}
+
+ +

2、在Spring配置文件applicationContext.xml。将JavaBean由Spring容器来管理。

+ + + +
<beans ...>
+<!--scope属性值设为:prototype(每次获取都是一个新对象), request(同一个request中获取到的是同一个), session ,不设置,默认是单例 -->
+    <bean id="p" class="cn.hncu.demo1.domain.Person" scope="prototype">
+    </bean>
+</beans>
+ +

测试方法:

+ + + +
    @Test
+    public void demo1(){
+        //此方法已在3.0版本中过时,不建议使用
+        //BeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
+
+        //Spring3.0建议采用下面这种方式使用容器
+        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
+        Person p = (Person) ctx.getBean("p");//通过配置的id获得,需要强转
+        System.out.println(p);
+
+        Person p2 = ctx.getBean(Person.class);//通过Person的Class对象去获得,不需要强转
+        System.out.println(p2);
+    }
+ +

输出结果:

+ +

+ +

显然,Person只构造了一次。
+由于我们没给初值,所以name是null,age因为是int型,所以是0.

+ +

现在我们在applicationContext.xml中来给它配置好初值,然后看:

+ +
    <!--scope属性值设为:prototype(每次获取都是一个新对象), request(同一个request中获取到的是同一个), session ,不设置,默认是单例 -->
+    <bean id="p" class="cn.hncu.demo1.domain.Person">
+        <!-- 配置好初始值 -->
+        <property name="name" value="张三"></property>
+        <property name="age" value="23"></property>
+    </bean>
+ +

再一次的运行结果:

+ +

+ + + +

演示依赖(XML)注入

+ +

在servlet注入servicce,Person,
+在servicce注入dao,

+ + + +

LoginDAO

+ + + +
package cn.hncu.demo1.login.dao;
+
+import cn.hncu.demo1.domain.Person;
+
+public interface LoginDAO {
+    public void login(Person p);
+}
+
+ + + +

LoginDaoJdbc

+ + + +
package cn.hncu.demo1.login.dao;
+
+import cn.hncu.demo1.domain.Person;
+
+public class LoginDaoJdbc implements LoginDAO{
+
+    @Override
+    public void login(Person p) {
+        System.out.println("dao,到数据库中读取用户信息以进行登录....");     
+        System.out.println("dao中获取的用户输入信息:"+p);     
+    }
+
+}
+
+ + + +

ILoginService

+ + + +
package cn.hncu.demo1.login.service;
+
+import cn.hncu.demo1.domain.Person;
+
+public interface ILoginService {
+
+    public void login(Person p);
+
+}
+
+ + + +

LoginServiceImpl

+ + + +
package cn.hncu.demo1.login.service;
+
+import cn.hncu.demo1.domain.Person;
+import cn.hncu.demo1.login.dao.LoginDAO;
+
+
+public class LoginServiceImpl implements ILoginService{
+    private LoginDAO dao = null;
+    //如果要注入,需要注入的成员变量,必须写好set-get方法!
+
+    public LoginDAO getDao() {
+        return dao;
+    }
+    public void setDao(LoginDAO dao) {
+        this.dao = dao;
+    }
+
+    @Override
+    public void login(Person p) {
+        dao.login(p);
+    }
+
+}
+
+ + + +

LoginAction

+ + + +
package cn.hncu.demo1.login;
+
+import cn.hncu.demo1.domain.Person;
+import cn.hncu.demo1.login.service.ILoginService;
+
+public class LoginAction {
+    private ILoginService service = null;
+    private Person p = null;
+    //如果要注入,需要注入的成员变量,必须写好set-get方法!
+    public ILoginService getService() {
+        return service;
+    }
+    public void setService(ILoginService service) {
+        this.service = service;
+    }
+    public Person getP() {
+        return p;
+    }
+    public void setP(Person p) {
+        this.p = p;
+    }
+
+    public void execute(){
+        service.login(p);
+    }
+
+}
+
+ +

需要依赖注入的变量一定要写好setter-getter 方法哦!!!

+ + + +

测试方法:

+ + + +
@Test//演示依赖(XML)注入
+    public void demo2(){
+        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
+        LoginAction action = ctx.getBean(LoginAction.class);
+        //LoginAction action = ctx.getBean("login",LoginAction.class);
+        action.execute();
+    }
+
+ +

配置文件:

+ + + +
<beans ...>
+<!--scope属性值设为:prototype(每次获取都是一个新对象), request(同一个request中获取到的是同一个), session ,不设置,默认是单例 -->
+    <bean id="p" class="cn.hncu.demo1.domain.Person">
+        <!-- 配置好初始值 -->
+        <property name="name" value="张三"></property>
+        <property name="age" value="23"></property>
+    </bean>
+
+    <!-- 注意这里的class是实现类,而不是接口哦 -->
+    <bean id="dao" class="cn.hncu.demo1.login.dao.LoginDaoJdbc">
+    </bean>
+
+    <!-- 注意这里的class也是实现类,而不是接口哦 -->
+    <!-- 如果换实现类了,只需把这里的class变了就可以了 -->
+    <bean id="s" class="cn.hncu.demo1.login.service.LoginServiceImpl">
+        <!-- 实现类中还有变量,ref是另外的bean的id-引用 -->
+        <property name="dao" ref="dao"></property>      
+    </bean>
+
+    <bean id="login" class="cn.hncu.demo1.login.LoginAction">
+        <property name="service" ref="s"></property>
+        <property name="person" ref="p"></property>
+    </bean>
+</beans>
+ + + +

结构图:

+ +

+ +

运行测试方法后的输出结果:

+ +

+ +

现在增加一个DAO的实现类,可以在程序中无需代码改变,就可以注入不同实例.
+我们只需要改applicationContext.xml:

+ +
<!-- 注意这里的class是实现类,而不是接口哦 -->
+    <!-- 如果换实现类了,只需把这里的class变了就可以了,或者不动这里,增加一个bean -->
+    <bean id="dao" class="cn.hncu.demo1.login.dao.LoginDaoJdbc2">
+    </bean>
+ + + +

增加的DAO实现类:

+ + + +
package cn.hncu.demo1.login.dao;
+
+import cn.hncu.demo1.domain.Person;
+
+public class LoginDaoJdbc2 implements LoginDAO{
+
+    @Override
+    public void login(Person p) {
+        System.out.println("dao2,到数据库中读取用户信息以进行登录....");        
+        System.out.println("dao2中获取的用户输入信息:"+p);        
+    }
+
+}
+
+ + + +

改动后的演示结果:

+ +

+ + + +

Spring IOC 控制反转

+ +

IoC(Inversion of Control)中文译为控制反转也可以叫做DI(Dependency Injection,依赖注入)。

+ +

控制反转模式的基本概念是:不直接创建对象,但是在xml配置文件中描述创建它们的方式。
+在工程中使用该Bean时由Spring容器创建Bean的实例。在代码中不直接与对象和服务连接,但在配置文件中描述哪一个组件需要哪一项服务。

+ + + +

1、Spring注入(又称依赖注入DI):

+ +

其目的是为其中bean的属性赋值

+ +

通过Setter方法。(一般属性赋值即基本类型赋值示例)

+ +

第1步:编写JavaBean-必须写set方法

+ +
package cn.hncu.demo2.domain;
+
+public class Cat {
+    private String name;
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    @Override
+    public String toString() {
+        return "Cat [name=" + name + "]";
+    }
+
+}
+
+ +

第2步: 在配置文件中注入属性的初始值

+ + + +
<?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:tx="http://www.springframework.org/schema/tx"
+        xsi:schemaLocation="http://www.springframework.org/schema/beans%20http://www.springframework.org/schema/beans/spring-beans-3.0.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/context%20http://www.springframework.org/schema/context/spring-context-3.0.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/tx%20http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
+
+    <bean id="cat" class="cn.hncu.demo2.domain.Cat">
+    <!-- 初始化name -->
+        <property name="name" value="黑猫"></property>
+    </bean>
+
+</beans>
+
+ +

这样拿到的Cat对象就有初始值了,name的初始值为”黑猫”。

+ + + +

复杂数据类型的初始化:

+ +

例如,含有List,Map,Set,或者其他对象的数据,这样的bean对象如何初始化值呢。

+ +

结构如下:

+ +

+ +

Cat类就是前面那个。

+ + + +

User

+ + + +
package cn.hncu.demo2.domain;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class User {
+    private String name;
+    private Integer age;
+    private List<Object> pets;
+    private Map<String, Object> map;
+    private Set<Object> set;
+    private Object objs[];
+    private Cat cat;
+
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public Integer getAge() {
+        return age;
+    }
+
+    public void setAge(Integer age) {
+        this.age = age;
+    }
+
+
+    public List<Object> getPets() {
+        return pets;
+    }
+
+    public void setPets(List<Object> pets) {
+        this.pets = pets;
+    }
+
+
+    public Map<String, Object> getMap() {
+        return map;
+    }
+
+    public void setMap(Map<String, Object> map) {
+        this.map = map;
+    }
+
+
+
+    public Set<Object> getSet() {
+        return set;
+    }
+
+    public void setSet(Set<Object> set) {
+        this.set = set;
+    }
+
+
+
+    public Object[] getObjs() {
+        return objs;
+    }
+
+    public void setObjs(Object[] objs) {
+        this.objs = objs;
+    }
+
+    public Cat getCat() {
+        return cat;
+    }
+
+    public void setCat(Cat cat) {
+        this.cat = cat;
+    }
+
+    @Override
+    public String toString() {
+        return "User [name=" + name + ", age=" + age + ", pets=" + pets
+                + "\r\n map=" + map + "\r\n set=" + set + "\r\n objs="
+                + Arrays.toString(objs) + ", cat=" + cat + "]";
+    }
+
+}
+
+ + + +

配置文件

+ +

在这里我取名为:applicationContext2.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:tx="http://www.springframework.org/schema/tx"
+        xsi:schemaLocation="http://www.springframework.org/schema/beans%20http://www.springframework.org/schema/beans/spring-beans-3.0.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/context%20http://www.springframework.org/schema/context/spring-context-3.0.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/tx%20http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
+
+
+    <bean id="cat" class="cn.hncu.demo2.domain.Cat">
+    <!-- 初始化name -->
+        <property name="name" value="黑猫"></property>
+    </bean>
+
+    <bean id="user" class="cn.hncu.demo2.domain.User">
+        <property name="name" value="Jack"></property>
+        <property name="age" value="25"></property>
+
+        <property name="pets">
+            <list>
+                <value>cat</value>
+                <value>dog</value>
+                <value>tiger</value>
+            </list>
+        </property>
+
+        <property name="map">
+            <map>
+                <entry key="name" value="中国"></entry>
+                <entry key="age" value="67"></entry>
+                <!-- ref是引用 -->
+                <entry key="cat" value-ref="cat"></entry>
+            </map>
+        </property>
+        <property name="set">
+         <set>
+            <!-- 引用 -->
+             <ref bean="cat"/>
+             <value>aaa</value>
+             <value>bbb</value>
+         </set>
+       </property>
+        <property name="objs">
+            <!-- 数组 -->
+            <array>
+                <value>hrllo</value>
+                <ref bean="cat"/>
+                <list>
+                    <value>obj1</value>
+                    <value>obj2</value>
+                </list>
+                <bean class="cn.hncu.demo2.domain.Cat">
+                    <property name="name" value="白猫"></property>
+                </bean>
+            </array>
+        </property>
+    </bean>
+</beans>
+
+ +

测试类:

+ + + +
package cn.hncu.demo2;
+
+import org.junit.Test;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.support.ClassPathXmlApplicationContext;
+
+import cn.hncu.demo2.domain.User;
+
+public class Demo2 {
+
+    //演示spring中<bean>属性注入的一些细节
+    @Test
+    public void demo(){
+        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext2.xml");
+        User user = ctx.getBean("user",User.class);
+        System.out.println(user);
+    }
+
+
+}
+
+ + + +

测试结果:

+ +

+ +

如果对于这个User的类的赋值搞懂了,我想应该在这块就会很熟练了。

+ + + +

完整的项目源码:

+ +

本文章由[谙忆]编写, 所有权利保留。

+ +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ \ No newline at end of file diff --git a/Spring/mySpring3Demo/bin/applicationContext.xml b/Spring/mySpring3Demo/bin/applicationContext.xml new file mode 100644 index 0000000..1baf0cc --- /dev/null +++ b/Spring/mySpring3Demo/bin/applicationContext.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Spring/mySpring3Demo/bin/applicationContext2.xml b/Spring/mySpring3Demo/bin/applicationContext2.xml new file mode 100644 index 0000000..033d2d2 --- /dev/null +++ b/Spring/mySpring3Demo/bin/applicationContext2.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + cat + dog + tiger + + + + + + + + + + + + + + + + aaa + bbb + + + + + + hrllo + + + obj1 + obj2 + + + + + + + + diff --git a/Spring/mySpring3Demo/bin/cn/hncu/demo1/TestDemo.class b/Spring/mySpring3Demo/bin/cn/hncu/demo1/TestDemo.class new file mode 100644 index 0000000..e66e39f Binary files /dev/null and b/Spring/mySpring3Demo/bin/cn/hncu/demo1/TestDemo.class differ diff --git a/Spring/mySpring3Demo/bin/cn/hncu/demo1/domain/Person.class b/Spring/mySpring3Demo/bin/cn/hncu/demo1/domain/Person.class new file mode 100644 index 0000000..4f9356f Binary files /dev/null and b/Spring/mySpring3Demo/bin/cn/hncu/demo1/domain/Person.class differ diff --git a/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/LoginAction.class b/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/LoginAction.class new file mode 100644 index 0000000..cd03832 Binary files /dev/null and b/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/LoginAction.class differ diff --git a/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/dao/LoginDAO.class b/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/dao/LoginDAO.class new file mode 100644 index 0000000..7490888 Binary files /dev/null and b/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/dao/LoginDAO.class differ diff --git a/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/dao/LoginDaoJdbc.class b/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/dao/LoginDaoJdbc.class new file mode 100644 index 0000000..b3fde5f Binary files /dev/null and b/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/dao/LoginDaoJdbc.class differ diff --git a/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/dao/LoginDaoJdbc2.class b/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/dao/LoginDaoJdbc2.class new file mode 100644 index 0000000..b1cda26 Binary files /dev/null and b/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/dao/LoginDaoJdbc2.class differ diff --git a/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/service/ILoginService.class b/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/service/ILoginService.class new file mode 100644 index 0000000..389f256 Binary files /dev/null and b/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/service/ILoginService.class differ diff --git a/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/service/LoginServiceImpl.class b/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/service/LoginServiceImpl.class new file mode 100644 index 0000000..9a54a7b Binary files /dev/null and b/Spring/mySpring3Demo/bin/cn/hncu/demo1/login/service/LoginServiceImpl.class differ diff --git a/Spring/mySpring3Demo/bin/cn/hncu/demo2/Demo2.class b/Spring/mySpring3Demo/bin/cn/hncu/demo2/Demo2.class new file mode 100644 index 0000000..03815d8 Binary files /dev/null and b/Spring/mySpring3Demo/bin/cn/hncu/demo2/Demo2.class differ diff --git a/Spring/mySpring3Demo/bin/cn/hncu/demo2/domain/Cat.class b/Spring/mySpring3Demo/bin/cn/hncu/demo2/domain/Cat.class new file mode 100644 index 0000000..c29fa5c Binary files /dev/null and b/Spring/mySpring3Demo/bin/cn/hncu/demo2/domain/Cat.class differ diff --git a/Spring/mySpring3Demo/bin/cn/hncu/demo2/domain/User.class b/Spring/mySpring3Demo/bin/cn/hncu/demo2/domain/User.class new file mode 100644 index 0000000..621b950 Binary files /dev/null and b/Spring/mySpring3Demo/bin/cn/hncu/demo2/domain/User.class differ diff --git a/Spring/mySpring3Demo/lib/commons-logging.jar b/Spring/mySpring3Demo/lib/commons-logging.jar new file mode 100644 index 0000000..8758a96 Binary files /dev/null and b/Spring/mySpring3Demo/lib/commons-logging.jar differ diff --git a/Spring/mySpring3Demo/lib/org.springframework.asm-3.1.1.RELEASE.jar b/Spring/mySpring3Demo/lib/org.springframework.asm-3.1.1.RELEASE.jar new file mode 100644 index 0000000..20d7938 Binary files /dev/null and b/Spring/mySpring3Demo/lib/org.springframework.asm-3.1.1.RELEASE.jar differ diff --git a/Spring/mySpring3Demo/lib/org.springframework.beans-3.1.1.RELEASE.jar b/Spring/mySpring3Demo/lib/org.springframework.beans-3.1.1.RELEASE.jar new file mode 100644 index 0000000..a69bcb1 Binary files /dev/null and b/Spring/mySpring3Demo/lib/org.springframework.beans-3.1.1.RELEASE.jar differ diff --git a/Spring/mySpring3Demo/lib/org.springframework.context-3.1.1.RELEASE.jar b/Spring/mySpring3Demo/lib/org.springframework.context-3.1.1.RELEASE.jar new file mode 100644 index 0000000..a35e486 Binary files /dev/null and b/Spring/mySpring3Demo/lib/org.springframework.context-3.1.1.RELEASE.jar differ diff --git a/Spring/mySpring3Demo/lib/org.springframework.context.support-3.1.1.RELEASE.jar b/Spring/mySpring3Demo/lib/org.springframework.context.support-3.1.1.RELEASE.jar new file mode 100644 index 0000000..8e8fff4 Binary files /dev/null and b/Spring/mySpring3Demo/lib/org.springframework.context.support-3.1.1.RELEASE.jar differ diff --git a/Spring/mySpring3Demo/lib/org.springframework.core-3.1.1.RELEASE.jar b/Spring/mySpring3Demo/lib/org.springframework.core-3.1.1.RELEASE.jar new file mode 100644 index 0000000..bdd8944 Binary files /dev/null and b/Spring/mySpring3Demo/lib/org.springframework.core-3.1.1.RELEASE.jar differ diff --git a/Spring/mySpring3Demo/lib/org.springframework.expression-3.1.1.RELEASE.jar b/Spring/mySpring3Demo/lib/org.springframework.expression-3.1.1.RELEASE.jar new file mode 100644 index 0000000..0e445b9 Binary files /dev/null and b/Spring/mySpring3Demo/lib/org.springframework.expression-3.1.1.RELEASE.jar differ diff --git a/Spring/mySpring3Demo/mySpring3Demo.zip b/Spring/mySpring3Demo/mySpring3Demo.zip new file mode 100644 index 0000000..80a551c Binary files /dev/null and b/Spring/mySpring3Demo/mySpring3Demo.zip differ diff --git a/Spring/mySpring3Demo/src/applicationContext.xml b/Spring/mySpring3Demo/src/applicationContext.xml new file mode 100644 index 0000000..1baf0cc --- /dev/null +++ b/Spring/mySpring3Demo/src/applicationContext.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Spring/mySpring3Demo/src/applicationContext2.xml b/Spring/mySpring3Demo/src/applicationContext2.xml new file mode 100644 index 0000000..033d2d2 --- /dev/null +++ b/Spring/mySpring3Demo/src/applicationContext2.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + cat + dog + tiger + + + + + + + + + + + + + + + + aaa + bbb + + + + + + hrllo + + + obj1 + obj2 + + + + + + + + diff --git a/Spring/mySpring3Demo/src/cn/hncu/demo1/TestDemo.java b/Spring/mySpring3Demo/src/cn/hncu/demo1/TestDemo.java new file mode 100644 index 0000000..01bb5ed --- /dev/null +++ b/Spring/mySpring3Demo/src/cn/hncu/demo1/TestDemo.java @@ -0,0 +1,38 @@ +package cn.hncu.demo1; + +import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.xml.XmlBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.core.io.ClassPathResource; + +import cn.hncu.demo1.domain.Person; +import cn.hncu.demo1.login.LoginAction; + +public class TestDemo { + + @Test + public void demo1(){ + //此方法已在3.0版本中过时,不建议使用 + //BeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml")); + + //Spring3.0建议采用下面这种方式使用容器 + ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); + Person p = (Person) ctx.getBean("p");//通过配置的id获得,需要强转 + System.out.println(p); + + Person p2 = ctx.getBean(Person.class);//通过Person的Class对象去获得,不需要强转 + System.out.println(p2); + } + + @Test//演示依赖(XML)注入 + public void demo2(){ + ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); + LoginAction action = ctx.getBean(LoginAction.class); + //LoginAction action = ctx.getBean("login",LoginAction.class); + action.execute(); + } + + +} diff --git a/Spring/mySpring3Demo/src/cn/hncu/demo1/domain/Person.java b/Spring/mySpring3Demo/src/cn/hncu/demo1/domain/Person.java new file mode 100644 index 0000000..7b5e648 --- /dev/null +++ b/Spring/mySpring3Demo/src/cn/hncu/demo1/domain/Person.java @@ -0,0 +1,31 @@ +package cn.hncu.demo1.domain; + +public class Person { + private String name; + private int age; + + public Person() { + System.out.println("执行Person的构造方法...."); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return "Person [name=" + name + ", age=" + age + "]"; + } +} diff --git a/Spring/mySpring3Demo/src/cn/hncu/demo1/login/LoginAction.java b/Spring/mySpring3Demo/src/cn/hncu/demo1/login/LoginAction.java new file mode 100644 index 0000000..74c47c9 --- /dev/null +++ b/Spring/mySpring3Demo/src/cn/hncu/demo1/login/LoginAction.java @@ -0,0 +1,27 @@ +package cn.hncu.demo1.login; + +import cn.hncu.demo1.domain.Person; +import cn.hncu.demo1.login.service.ILoginService; + +public class LoginAction { + private ILoginService service = null; + private Person person = null; + //如果要注入,需要注入的成员变量,必须写好set-get方法! + public ILoginService getService() { + return service; + } + public void setService(ILoginService service) { + this.service = service; + } + + public Person getPerson() { + return person; + } + public void setPerson(Person person) { + this.person = person; + } + public void execute(){ + service.login(person); + } + +} diff --git a/Spring/mySpring3Demo/src/cn/hncu/demo1/login/dao/LoginDAO.java b/Spring/mySpring3Demo/src/cn/hncu/demo1/login/dao/LoginDAO.java new file mode 100644 index 0000000..11b4156 --- /dev/null +++ b/Spring/mySpring3Demo/src/cn/hncu/demo1/login/dao/LoginDAO.java @@ -0,0 +1,7 @@ +package cn.hncu.demo1.login.dao; + +import cn.hncu.demo1.domain.Person; + +public interface LoginDAO { + public void login(Person p); +} diff --git a/Spring/mySpring3Demo/src/cn/hncu/demo1/login/dao/LoginDaoJdbc.java b/Spring/mySpring3Demo/src/cn/hncu/demo1/login/dao/LoginDaoJdbc.java new file mode 100644 index 0000000..c29315f --- /dev/null +++ b/Spring/mySpring3Demo/src/cn/hncu/demo1/login/dao/LoginDaoJdbc.java @@ -0,0 +1,13 @@ +package cn.hncu.demo1.login.dao; + +import cn.hncu.demo1.domain.Person; + +public class LoginDaoJdbc implements LoginDAO{ + + @Override + public void login(Person p) { + System.out.println("dao,到数据库中读取用户信息以进行登录...."); + System.out.println("dao中获取的用户输入信息:"+p); + } + +} diff --git a/Spring/mySpring3Demo/src/cn/hncu/demo1/login/dao/LoginDaoJdbc2.java b/Spring/mySpring3Demo/src/cn/hncu/demo1/login/dao/LoginDaoJdbc2.java new file mode 100644 index 0000000..6e7d3fe --- /dev/null +++ b/Spring/mySpring3Demo/src/cn/hncu/demo1/login/dao/LoginDaoJdbc2.java @@ -0,0 +1,13 @@ +package cn.hncu.demo1.login.dao; + +import cn.hncu.demo1.domain.Person; + +public class LoginDaoJdbc2 implements LoginDAO{ + + @Override + public void login(Person p) { + System.out.println("dao2,到数据库中读取用户信息以进行登录...."); + System.out.println("dao2中获取的用户输入信息:"+p); + } + +} diff --git a/Spring/mySpring3Demo/src/cn/hncu/demo1/login/service/ILoginService.java b/Spring/mySpring3Demo/src/cn/hncu/demo1/login/service/ILoginService.java new file mode 100644 index 0000000..04ad4a3 --- /dev/null +++ b/Spring/mySpring3Demo/src/cn/hncu/demo1/login/service/ILoginService.java @@ -0,0 +1,9 @@ +package cn.hncu.demo1.login.service; + +import cn.hncu.demo1.domain.Person; + +public interface ILoginService { + + public void login(Person p); + +} diff --git a/Spring/mySpring3Demo/src/cn/hncu/demo1/login/service/LoginServiceImpl.java b/Spring/mySpring3Demo/src/cn/hncu/demo1/login/service/LoginServiceImpl.java new file mode 100644 index 0000000..fe112f5 --- /dev/null +++ b/Spring/mySpring3Demo/src/cn/hncu/demo1/login/service/LoginServiceImpl.java @@ -0,0 +1,23 @@ +package cn.hncu.demo1.login.service; + +import cn.hncu.demo1.domain.Person; +import cn.hncu.demo1.login.dao.LoginDAO; + + +public class LoginServiceImpl implements ILoginService{ + private LoginDAO dao = null; + //如果要注入,需要注入的成员变量,必须写好set-get方法! + + public LoginDAO getDao() { + return dao; + } + public void setDao(LoginDAO dao) { + this.dao = dao; + } + + @Override + public void login(Person p) { + dao.login(p); + } + +} diff --git a/Spring/mySpring3Demo/src/cn/hncu/demo2/Demo2.java b/Spring/mySpring3Demo/src/cn/hncu/demo2/Demo2.java new file mode 100644 index 0000000..ded6853 --- /dev/null +++ b/Spring/mySpring3Demo/src/cn/hncu/demo2/Demo2.java @@ -0,0 +1,20 @@ +package cn.hncu.demo2; + +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import cn.hncu.demo2.domain.User; + +public class Demo2 { + + //演示spring中属性注入的一些细节 + @Test + public void demo(){ + ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext2.xml"); + User user = ctx.getBean("user",User.class); + System.out.println(user); + } + + +} diff --git a/Spring/mySpring3Demo/src/cn/hncu/demo2/domain/Cat.java b/Spring/mySpring3Demo/src/cn/hncu/demo2/domain/Cat.java new file mode 100644 index 0000000..8ddbe8c --- /dev/null +++ b/Spring/mySpring3Demo/src/cn/hncu/demo2/domain/Cat.java @@ -0,0 +1,19 @@ +package cn.hncu.demo2.domain; + +public class Cat { + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Cat [name=" + name + "]"; + } + +} diff --git a/Spring/mySpring3Demo/src/cn/hncu/demo2/domain/User.java b/Spring/mySpring3Demo/src/cn/hncu/demo2/domain/User.java new file mode 100644 index 0000000..8b11bb1 --- /dev/null +++ b/Spring/mySpring3Demo/src/cn/hncu/demo2/domain/User.java @@ -0,0 +1,87 @@ +package cn.hncu.demo2.domain; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class User { + private String name; + private Integer age; + private List pets; + private Map map; + private Set set; + private Object objs[]; + private Cat cat; + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + + public List getPets() { + return pets; + } + + public void setPets(List pets) { + this.pets = pets; + } + + + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + + + public Set getSet() { + return set; + } + + public void setSet(Set set) { + this.set = set; + } + + + + public Object[] getObjs() { + return objs; + } + + public void setObjs(Object[] objs) { + this.objs = objs; + } + + public Cat getCat() { + return cat; + } + + public void setCat(Cat cat) { + this.cat = cat; + } + + @Override + public String toString() { + return "User [name=" + name + ", age=" + age + ", pets=" + pets + + "\r\n map=" + map + "\r\n set=" + set + "\r\n objs=" + + Arrays.toString(objs) + ", cat=" + cat + "]"; + } + +} diff --git "a/Spring/mySpring3Demo/\343\200\220\346\241\206\346\236\266\343\200\221[Spring3]\344\270\213\350\275\275\345\256\211\350\243\205\343\200\201\345\274\200\346\272\220\346\241\206\346\236\266\344\270\216IoC\346\216\247\345\210\266\345\217\215\350\275\254\350\257\246\350\247\243.html" "b/Spring/mySpring3Demo/\343\200\220\346\241\206\346\236\266\343\200\221[Spring3]\344\270\213\350\275\275\345\256\211\350\243\205\343\200\201\345\274\200\346\272\220\346\241\206\346\236\266\344\270\216IoC\346\216\247\345\210\266\345\217\215\350\275\254\350\257\246\350\247\243.html" new file mode 100644 index 0000000..1a9fc76 --- /dev/null +++ "b/Spring/mySpring3Demo/\343\200\220\346\241\206\346\236\266\343\200\221[Spring3]\344\270\213\350\275\275\345\256\211\350\243\205\343\200\201\345\274\200\346\272\220\346\241\206\346\236\266\344\270\216IoC\346\216\247\345\210\266\345\217\215\350\275\254\350\257\246\350\247\243.html" @@ -0,0 +1,728 @@ + + + + + +【框架】[Spring3]下载安装、开源框架与IoC控制反转详解 + + + +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ +

昨天刚刚初学Spring3,也许Spring3有点老了哈,不过还是先把3学了再去学习4吧,首先先介绍一下如何去下载Spring的必须包吧。
+(本篇博客适用于初学Spring的朋友)

+ +

java spring4现在不推荐使用xml配置文件…
+当然啦,这些知识点在Spring4还是可以用的。

+ +

不过我在这里详解的还是Spring3哈,见谅~

+ +

下载SpringJAR包/文档:

+ +

Spring官网:http://spring.io/

+ +

Spring3.2版本以后(JAR/文档)的下载地址:http://repo.springsource.org/libs-release-local/org/springframework/spring/
+(如果无法访问,请准备梯子)

+ +

+ +

选择一个需要下载的版本进去:
+我选择的是最新的4.3.2版本.

+ +

+ +

spring-framework-*(版本号).RELEASE-dist.zip 包含了Spring必须的JAR包、DOC文档以及源代码等。

+ +

下载完之后解压我们就可以在spring-framework-4.3.2.RELEASE\libs找到需要包和DOC文档以及源代码了。

+ +

+ +

由于最新版本的已经提倡基于Java Config和注解的配置,不采用xml配置了,所以,我在这里准备的是Spring3.1.1版本的:
+下载链接:
+https://github.com/chenhaoxiang/Java/blob/master/Spring/spring-framework-3.1.1.RELEASE.zip

+ +

Spring开源框架

+ + + +

Spring框架的起始:

+ +

Spring在英语中含义就是”春天”.
+对于Java EE开发者来说,Spring框架出现确实带来了一股全新的春天的气息。
+早在2002年,Rod Johson在其编著的《Expert one to one J2EE design and development》书中,对Java EE框架臃肿、低效、脱离现实的种种现状提出了很多质疑,并积极寻求探索革新之道。
+由他主导编写了interface21框架,从实际需求出发,着眼于轻便、灵巧,易于开发、测试和部署的轻量级开发框架。以interface21框架为基础,并集成了其它许多开源成果,于2004年3月24日,发布了1.0正式版取名为Spring。

+ + + +

Spring框架模块:

+ +

Spring的核心是个轻量级容器,实现了IoC(控制翻转)模式的容器,基于此核心容器所建立的应用程序,可以达到程序组件的松散耦合。这些特性都使得整个应用程序维护简化。 Spring框架核心由下图所示的七个模块组成。

+ +

+ +

现在来分别介绍一下这七个模块:

+ + + +

1、核心容器(Core)

+ +

这是Spring框架最基础的部分,它提供了依赖注入(Dependency Injection)特征来实现容器对Bean的管理。这里最基本的概念是BeanFactory,它是任何Spring应用的核心。BeanFactory是工厂模式的一个实现,它使用IoC将应用配置和依赖说明从实际的应用代码中分离出来。

+ + + +

2、AOP模块

+ +

AOP即面向切面编程技术,Spring在它的AOP模块中提供了对面向切面编程的丰富支持。AOP允许通过分离应用的业务逻辑与系统级服务(例如安全和事务管理)进行内聚性的开发。应用对象只实现它们应该做的——完成业务逻辑——仅此而已。它们并不负责其它的系统级关注点,例如日志或事务支持。

+ + + +

3、对象/关系映射集成模块ORM

+ +

Hibernate是成熟的ORM产品,Spring并没有自己实现ORM框架而是集成了几个流行的ORM产品如Hibernate、JDO和iBATIS等。可以利用Spring对这些模块提供事务支持等。

+ + + +

4、JDBC抽象和DAO模块

+ +

Spring虽然集成了几个ORM产品,但也可以不选择这几款产品,因为Spring提供了JDBC和DAO模块。该模块对现有的JDBC技术进行了优化。你可以保持你的数据库访问代码干净简洁,并且可以防止因关闭数据库资源失败而引起的问题。

+ +

[JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构管管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写的异常代码数量(例如打开和关闭连接)。SpringDAO的面向JDBC的异常遵从从通用的DAO异常层次结构]

+ +

5、Spring的Web模块

+ +

Web上下文模块建立于应用上下文模块之上,提供了一个适合于Web应用的上下文。另外,这个模块还提供了一些面向服务支持。例如:实现文件上传的multipart请求,它也提供了Spring和其它Web框架的集成,比如Struts、WebWork。

+ + + +

6、应用上下文(Context)模块

+ +

核心模块的BeanFactory使Spring成为一个容器,而上下文模块使它成为一个框架。Web上下文模块建立于应用上下文模块之上,提供了一个适合于Web应用的上下文。该模块还提供了一些面向服务支持这个模块扩展了BeanFactory的概念,增加了对国际化(I18N)消息、事件传播以及验证的支持。

+ +

另外,这个模块还提供了许多企业服务,例如电子邮件、JNDI访问、EJB集成、远程以及时序调度(scheduling)服务。也包括对模版框架例如Velocity和FreeMarker集成的支持。

+ +

7、Spring的MVC框架

+ +

Spring为构建Web应用提供了一个功能全面的MVC框架。虽然Spring可以很容易地与其它MVC框架集成,例如Struts2,但Spring的MVC框架使用IoC对控制逻辑和业务对象提供了完全的分离。

+ + + +

Spring入门示例

+ +

将需要的Jar包导入项目、

+ +

再准备一个xml配置文件:
+applicationContext.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:tx="http://www.springframework.org/schema/tx"
+        xsi:schemaLocation="http://www.springframework.org/schema/beans%20http://www.springframework.org/schema/beans/spring-beans-3.0.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/context%20http://www.springframework.org/schema/context/spring-context-3.0.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/tx%20http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
+
+</beans>
+
+ +

将Spring的压缩包解压后:你可以在spring-framework-3.1.1.RELEASE\projects\org.springframework.web.portlet\src\test\java\org\springframework\web\portlet\context\WEB-INF目录下找到applicationContext.xml。我们只需要这个部分就可以了。
+将文件建立在src目录下(建在另外的路径也可以)。

+ +

+ +

导入必须的包,和建好applicationContext.xml文件。

+ +

1、编写一个普通的Java类(JavaBean)

+ + + +
package cn.hncu.demo1.domain;
+
+public class Person {
+    private String name;
+    private int age;
+
+    public Person() {
+        System.out.println("执行Person的构造方法....");
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public int getAge() {
+        return age;
+    }
+
+    public void setAge(int age) {
+        this.age = age;
+    }
+
+    @Override
+    public String toString() {
+        return "Person [name=" + name + ", age=" + age + "]";
+    }
+}
+
+ +

2、在Spring配置文件applicationContext.xml。将JavaBean由Spring容器来管理。

+ + + +
<beans ...>
+<!--scope属性值设为:prototype(每次获取都是一个新对象), request(同一个request中获取到的是同一个), session ,不设置,默认是单例 -->
+    <bean id="p" class="cn.hncu.demo1.domain.Person" scope="prototype">
+    </bean>
+</beans>
+ +

测试方法:

+ + + +
    @Test
+    public void demo1(){
+        //此方法已在3.0版本中过时,不建议使用
+        //BeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
+
+        //Spring3.0建议采用下面这种方式使用容器
+        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
+        Person p = (Person) ctx.getBean("p");//通过配置的id获得,需要强转
+        System.out.println(p);
+
+        Person p2 = ctx.getBean(Person.class);//通过Person的Class对象去获得,不需要强转
+        System.out.println(p2);
+    }
+ +

输出结果:

+ +

+ +

显然,Person只构造了一次。
+由于我们没给初值,所以name是null,age因为是int型,所以是0.

+ +

现在我们在applicationContext.xml中来给它配置好初值,然后看:

+ +
    <!--scope属性值设为:prototype(每次获取都是一个新对象), request(同一个request中获取到的是同一个), session ,不设置,默认是单例 -->
+    <bean id="p" class="cn.hncu.demo1.domain.Person">
+        <!-- 配置好初始值 -->
+        <property name="name" value="张三"></property>
+        <property name="age" value="23"></property>
+    </bean>
+ +

再一次的运行结果:

+ +

+ + + +

演示依赖(XML)注入

+ +

在servlet注入servicce,Person,
+在servicce注入dao,

+ + + +

LoginDAO

+ + + +
package cn.hncu.demo1.login.dao;
+
+import cn.hncu.demo1.domain.Person;
+
+public interface LoginDAO {
+    public void login(Person p);
+}
+
+ + + +

LoginDaoJdbc

+ + + +
package cn.hncu.demo1.login.dao;
+
+import cn.hncu.demo1.domain.Person;
+
+public class LoginDaoJdbc implements LoginDAO{
+
+    @Override
+    public void login(Person p) {
+        System.out.println("dao,到数据库中读取用户信息以进行登录....");     
+        System.out.println("dao中获取的用户输入信息:"+p);     
+    }
+
+}
+
+ + + +

ILoginService

+ + + +
package cn.hncu.demo1.login.service;
+
+import cn.hncu.demo1.domain.Person;
+
+public interface ILoginService {
+
+    public void login(Person p);
+
+}
+
+ + + +

LoginServiceImpl

+ + + +
package cn.hncu.demo1.login.service;
+
+import cn.hncu.demo1.domain.Person;
+import cn.hncu.demo1.login.dao.LoginDAO;
+
+
+public class LoginServiceImpl implements ILoginService{
+    private LoginDAO dao = null;
+    //如果要注入,需要注入的成员变量,必须写好set-get方法!
+
+    public LoginDAO getDao() {
+        return dao;
+    }
+    public void setDao(LoginDAO dao) {
+        this.dao = dao;
+    }
+
+    @Override
+    public void login(Person p) {
+        dao.login(p);
+    }
+
+}
+
+ + + +

LoginAction

+ + + +
package cn.hncu.demo1.login;
+
+import cn.hncu.demo1.domain.Person;
+import cn.hncu.demo1.login.service.ILoginService;
+
+public class LoginAction {
+    private ILoginService service = null;
+    private Person p = null;
+    //如果要注入,需要注入的成员变量,必须写好set-get方法!
+    public ILoginService getService() {
+        return service;
+    }
+    public void setService(ILoginService service) {
+        this.service = service;
+    }
+    public Person getP() {
+        return p;
+    }
+    public void setP(Person p) {
+        this.p = p;
+    }
+
+    public void execute(){
+        service.login(p);
+    }
+
+}
+
+ +

需要依赖注入的变量一定要写好setter-getter 方法哦!!!

+ + + +

测试方法:

+ + + +
@Test//演示依赖(XML)注入
+    public void demo2(){
+        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
+        LoginAction action = ctx.getBean(LoginAction.class);
+        //LoginAction action = ctx.getBean("login",LoginAction.class);
+        action.execute();
+    }
+
+ +

配置文件:

+ + + +
<beans ...>
+<!--scope属性值设为:prototype(每次获取都是一个新对象), request(同一个request中获取到的是同一个), session ,不设置,默认是单例 -->
+    <bean id="p" class="cn.hncu.demo1.domain.Person">
+        <!-- 配置好初始值 -->
+        <property name="name" value="张三"></property>
+        <property name="age" value="23"></property>
+    </bean>
+
+    <!-- 注意这里的class是实现类,而不是接口哦 -->
+    <bean id="dao" class="cn.hncu.demo1.login.dao.LoginDaoJdbc">
+    </bean>
+
+    <!-- 注意这里的class也是实现类,而不是接口哦 -->
+    <!-- 如果换实现类了,只需把这里的class变了就可以了 -->
+    <bean id="s" class="cn.hncu.demo1.login.service.LoginServiceImpl">
+        <!-- 实现类中还有变量,ref是另外的bean的id-引用 -->
+        <property name="dao" ref="dao"></property>      
+    </bean>
+
+    <bean id="login" class="cn.hncu.demo1.login.LoginAction">
+        <property name="service" ref="s"></property>
+        <property name="person" ref="p"></property>
+    </bean>
+</beans>
+ + + +

结构图:

+ +

+ +

运行测试方法后的输出结果:

+ +

+ +

现在增加一个DAO的实现类,可以在程序中无需代码改变,就可以注入不同实例.
+我们只需要改applicationContext.xml:

+ +
<!-- 注意这里的class是实现类,而不是接口哦 -->
+    <!-- 如果换实现类了,只需把这里的class变了就可以了,或者不动这里,增加一个bean -->
+    <bean id="dao" class="cn.hncu.demo1.login.dao.LoginDaoJdbc2">
+    </bean>
+ + + +

增加的DAO实现类:

+ + + +
package cn.hncu.demo1.login.dao;
+
+import cn.hncu.demo1.domain.Person;
+
+public class LoginDaoJdbc2 implements LoginDAO{
+
+    @Override
+    public void login(Person p) {
+        System.out.println("dao2,到数据库中读取用户信息以进行登录....");        
+        System.out.println("dao2中获取的用户输入信息:"+p);        
+    }
+
+}
+
+ + + +

改动后的演示结果:

+ +

+ + + +

Spring IOC 控制反转

+ +

IoC(Inversion of Control)中文译为控制反转也可以叫做DI(Dependency Injection,依赖注入)。

+ +

控制反转模式的基本概念是:不直接创建对象,但是在xml配置文件中描述创建它们的方式。
+在工程中使用该Bean时由Spring容器创建Bean的实例。在代码中不直接与对象和服务连接,但在配置文件中描述哪一个组件需要哪一项服务。

+ + + +

1、Spring注入(又称依赖注入DI):

+ +

其目的是为其中bean的属性赋值

+ +

通过Setter方法。(一般属性赋值即基本类型赋值示例)

+ +

第1步:编写JavaBean-必须写set方法

+ +
package cn.hncu.demo2.domain;
+
+public class Cat {
+    private String name;
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    @Override
+    public String toString() {
+        return "Cat [name=" + name + "]";
+    }
+
+}
+
+ +

第2步: 在配置文件中注入属性的初始值

+ + + +
<?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:tx="http://www.springframework.org/schema/tx"
+        xsi:schemaLocation="http://www.springframework.org/schema/beans%20http://www.springframework.org/schema/beans/spring-beans-3.0.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/context%20http://www.springframework.org/schema/context/spring-context-3.0.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/tx%20http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
+
+    <bean id="cat" class="cn.hncu.demo2.domain.Cat">
+    <!-- 初始化name -->
+        <property name="name" value="黑猫"></property>
+    </bean>
+
+</beans>
+
+ +

这样拿到的Cat对象就有初始值了,name的初始值为”黑猫”。

+ + + +

复杂数据类型的初始化:

+ +

例如,含有List,Map,Set,或者其他对象的数据,这样的bean对象如何初始化值呢。

+ +

结构如下:

+ +

+ +

Cat类就是前面那个。

+ + + +

User

+ + + +
package cn.hncu.demo2.domain;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class User {
+    private String name;
+    private Integer age;
+    private List<Object> pets;
+    private Map<String, Object> map;
+    private Set<Object> set;
+    private Object objs[];
+    private Cat cat;
+
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public Integer getAge() {
+        return age;
+    }
+
+    public void setAge(Integer age) {
+        this.age = age;
+    }
+
+
+    public List<Object> getPets() {
+        return pets;
+    }
+
+    public void setPets(List<Object> pets) {
+        this.pets = pets;
+    }
+
+
+    public Map<String, Object> getMap() {
+        return map;
+    }
+
+    public void setMap(Map<String, Object> map) {
+        this.map = map;
+    }
+
+
+
+    public Set<Object> getSet() {
+        return set;
+    }
+
+    public void setSet(Set<Object> set) {
+        this.set = set;
+    }
+
+
+
+    public Object[] getObjs() {
+        return objs;
+    }
+
+    public void setObjs(Object[] objs) {
+        this.objs = objs;
+    }
+
+    public Cat getCat() {
+        return cat;
+    }
+
+    public void setCat(Cat cat) {
+        this.cat = cat;
+    }
+
+    @Override
+    public String toString() {
+        return "User [name=" + name + ", age=" + age + ", pets=" + pets
+                + "\r\n map=" + map + "\r\n set=" + set + "\r\n objs="
+                + Arrays.toString(objs) + ", cat=" + cat + "]";
+    }
+
+}
+
+ + + +

配置文件

+ +

在这里我取名为:applicationContext2.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:tx="http://www.springframework.org/schema/tx"
+        xsi:schemaLocation="http://www.springframework.org/schema/beans%20http://www.springframework.org/schema/beans/spring-beans-3.0.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/context%20http://www.springframework.org/schema/context/spring-context-3.0.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/tx%20http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
+
+
+    <bean id="cat" class="cn.hncu.demo2.domain.Cat">
+    <!-- 初始化name -->
+        <property name="name" value="黑猫"></property>
+    </bean>
+
+    <bean id="user" class="cn.hncu.demo2.domain.User">
+        <property name="name" value="Jack"></property>
+        <property name="age" value="25"></property>
+
+        <property name="pets">
+            <list>
+                <value>cat</value>
+                <value>dog</value>
+                <value>tiger</value>
+            </list>
+        </property>
+
+        <property name="map">
+            <map>
+                <entry key="name" value="中国"></entry>
+                <entry key="age" value="67"></entry>
+                <!-- ref是引用 -->
+                <entry key="cat" value-ref="cat"></entry>
+            </map>
+        </property>
+        <property name="set">
+         <set>
+            <!-- 引用 -->
+             <ref bean="cat"/>
+             <value>aaa</value>
+             <value>bbb</value>
+         </set>
+       </property>
+        <property name="objs">
+            <!-- 数组 -->
+            <array>
+                <value>hrllo</value>
+                <ref bean="cat"/>
+                <list>
+                    <value>obj1</value>
+                    <value>obj2</value>
+                </list>
+                <bean class="cn.hncu.demo2.domain.Cat">
+                    <property name="name" value="白猫"></property>
+                </bean>
+            </array>
+        </property>
+    </bean>
+</beans>
+
+ +

测试类:

+ + + +
package cn.hncu.demo2;
+
+import org.junit.Test;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.support.ClassPathXmlApplicationContext;
+
+import cn.hncu.demo2.domain.User;
+
+public class Demo2 {
+
+    //演示spring中<bean>属性注入的一些细节
+    @Test
+    public void demo(){
+        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext2.xml");
+        User user = ctx.getBean("user",User.class);
+        System.out.println(user);
+    }
+
+
+}
+
+ + + +

测试结果:

+ +

+ +

如果对于这个User的类的赋值搞懂了,我想应该在这块就会很熟练了。

+ + + +

完整的项目源码:

+ +

本文章由[谙忆]编写, 所有权利保留。

+ +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ \ No newline at end of file diff --git a/Spring/mySpringAopDemo/.classpath b/Spring/mySpringAopDemo/.classpath new file mode 100644 index 0000000..f02c7ef --- /dev/null +++ b/Spring/mySpringAopDemo/.classpath @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/Spring/mySpringAopDemo/.project b/Spring/mySpringAopDemo/.project new file mode 100644 index 0000000..9921f04 --- /dev/null +++ b/Spring/mySpringAopDemo/.project @@ -0,0 +1,17 @@ + + + mySpringAopDemo + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/Spring/mySpringAopDemo/.settings/org.eclipse.jdt.core.prefs b/Spring/mySpringAopDemo/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..d772054 --- /dev/null +++ b/Spring/mySpringAopDemo/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +#Thu Sep 01 16:45:40 CST 2016 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/Spring/mySpringAopDemo/README.md b/Spring/mySpringAopDemo/README.md new file mode 100644 index 0000000..c369d58 --- /dev/null +++ b/Spring/mySpringAopDemo/README.md @@ -0,0 +1,29 @@ +【框架】[Spring]主要讲解的是纯Java的方式实现AOP切面技术: +http://blog.csdn.net/qq_26525215/article/details/52400791 + +【框架】[Spring]XML配置实现AOP拦截-切点:JdkRegexpMethodPointcut: +http://blog.csdn.net/qq_26525215/article/details/52411726 + +【框架】[Spring]AOP拦截-三种方式实现自动代理 : +http://blog.csdn.net/qq_26525215/article/details/52412901 + +【框架】[Spring]纯Java方式实现AOP拦截-详解ThrowsAdvice异常通知 : +http://blog.csdn.net/qq_26525215/article/details/52420658 + + +【框架】[Spring]AOP拦截-使用切点:AspectJExpressionPointcut-切点语言: +http://blog.csdn.net/qq_26525215/article/details/52422395 + + + + + + + + + + + + + + diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/AopJavaImplDemo$1.class b/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/AopJavaImplDemo$1.class new file mode 100644 index 0000000..a950c79 Binary files /dev/null and b/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/AopJavaImplDemo$1.class differ diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/AopJavaImplDemo$2.class b/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/AopJavaImplDemo$2.class new file mode 100644 index 0000000..59aa5f1 Binary files /dev/null and b/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/AopJavaImplDemo$2.class differ diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/AopJavaImplDemo$3.class b/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/AopJavaImplDemo$3.class new file mode 100644 index 0000000..bb75f4b Binary files /dev/null and b/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/AopJavaImplDemo$3.class differ diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/AopJavaImplDemo$4.class b/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/AopJavaImplDemo$4.class new file mode 100644 index 0000000..0813b67 Binary files /dev/null and b/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/AopJavaImplDemo$4.class differ diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/AopJavaImplDemo.class b/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/AopJavaImplDemo.class new file mode 100644 index 0000000..aa9f662 Binary files /dev/null and b/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/AopJavaImplDemo.class differ diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/Person.class b/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/Person.class new file mode 100644 index 0000000..339594b Binary files /dev/null and b/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/Person.class differ diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/ThrowException.class b/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/ThrowException.class new file mode 100644 index 0000000..e174c36 Binary files /dev/null and b/Spring/mySpringAopDemo/bin/cn/hncu/javaImpl/ThrowException.class differ diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/1.xml b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/1.xml new file mode 100644 index 0000000..af23706 --- /dev/null +++ b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/1.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + advisor + + + + + + \ No newline at end of file diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/2.xml b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/2.xml new file mode 100644 index 0000000..e529360 --- /dev/null +++ b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/2.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + advisor + + + + + + \ No newline at end of file diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/3.xml b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/3.xml new file mode 100644 index 0000000..95aac6e --- /dev/null +++ b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/3.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + .*run.* + + + + + + + + + + + + + + + + + advisor + + + + + + \ No newline at end of file diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/4.xml b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/4.xml new file mode 100644 index 0000000..ee4c5fd --- /dev/null +++ b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/4.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + .*run.* + + + + + + + + + + + + + \ No newline at end of file diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/5.xml b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/5.xml new file mode 100644 index 0000000..c271198 --- /dev/null +++ b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/5.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + .*run.* + + + + + + + + + + + + \ No newline at end of file diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/6.xml b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/6.xml new file mode 100644 index 0000000..e2ae3f4 --- /dev/null +++ b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/6.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + .*run.* + + + + + + + + + \ No newline at end of file diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/AopXmlDemo.class b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/AopXmlDemo.class new file mode 100644 index 0000000..f81453b Binary files /dev/null and b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/AopXmlDemo.class differ diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/AroundAdvice.class b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/AroundAdvice.class new file mode 100644 index 0000000..68c373a Binary files /dev/null and b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/AroundAdvice.class differ diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/MyAutoProxy.class b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/MyAutoProxy.class new file mode 100644 index 0000000..4d95fa9 Binary files /dev/null and b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/MyAutoProxy.class differ diff --git a/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/Person.class b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/Person.class new file mode 100644 index 0000000..0a9e03d Binary files /dev/null and b/Spring/mySpringAopDemo/bin/cn/hncu/xmlImpl/Person.class differ diff --git a/Spring/mySpringAopDemo/lib/aspectjrt-1.8.9.jar b/Spring/mySpringAopDemo/lib/aspectjrt-1.8.9.jar new file mode 100644 index 0000000..9fb7f88 Binary files /dev/null and b/Spring/mySpringAopDemo/lib/aspectjrt-1.8.9.jar differ diff --git a/Spring/mySpringAopDemo/lib/aspectjweaver-1.8.9.jar b/Spring/mySpringAopDemo/lib/aspectjweaver-1.8.9.jar new file mode 100644 index 0000000..87f5c8f Binary files /dev/null and b/Spring/mySpringAopDemo/lib/aspectjweaver-1.8.9.jar differ diff --git a/Spring/mySpringAopDemo/lib/commons-logging-1.2.jar b/Spring/mySpringAopDemo/lib/commons-logging-1.2.jar new file mode 100644 index 0000000..93a3b9f Binary files /dev/null and b/Spring/mySpringAopDemo/lib/commons-logging-1.2.jar differ diff --git a/Spring/mySpringAopDemo/lib/spring-aop-4.3.2.RELEASE.jar b/Spring/mySpringAopDemo/lib/spring-aop-4.3.2.RELEASE.jar new file mode 100644 index 0000000..e89e193 Binary files /dev/null and b/Spring/mySpringAopDemo/lib/spring-aop-4.3.2.RELEASE.jar differ diff --git a/Spring/mySpringAopDemo/lib/spring-beans-4.3.2.RELEASE.jar b/Spring/mySpringAopDemo/lib/spring-beans-4.3.2.RELEASE.jar new file mode 100644 index 0000000..bd08cf8 Binary files /dev/null and b/Spring/mySpringAopDemo/lib/spring-beans-4.3.2.RELEASE.jar differ diff --git a/Spring/mySpringAopDemo/lib/spring-context-4.3.2.RELEASE.jar b/Spring/mySpringAopDemo/lib/spring-context-4.3.2.RELEASE.jar new file mode 100644 index 0000000..c88bdd9 Binary files /dev/null and b/Spring/mySpringAopDemo/lib/spring-context-4.3.2.RELEASE.jar differ diff --git a/Spring/mySpringAopDemo/lib/spring-core-4.3.2.RELEASE.jar b/Spring/mySpringAopDemo/lib/spring-core-4.3.2.RELEASE.jar new file mode 100644 index 0000000..e89f6f1 Binary files /dev/null and b/Spring/mySpringAopDemo/lib/spring-core-4.3.2.RELEASE.jar differ diff --git a/Spring/mySpringAopDemo/lib/spring-expression-4.3.2.RELEASE.jar b/Spring/mySpringAopDemo/lib/spring-expression-4.3.2.RELEASE.jar new file mode 100644 index 0000000..9cf63ea Binary files /dev/null and b/Spring/mySpringAopDemo/lib/spring-expression-4.3.2.RELEASE.jar differ diff --git a/Spring/mySpringAopDemo/mySpringAopDemo.zip b/Spring/mySpringAopDemo/mySpringAopDemo.zip new file mode 100644 index 0000000..77b7ef6 Binary files /dev/null and b/Spring/mySpringAopDemo/mySpringAopDemo.zip differ diff --git a/Spring/mySpringAopDemo/src/cn/hncu/javaImpl/AopJavaImplDemo.java b/Spring/mySpringAopDemo/src/cn/hncu/javaImpl/AopJavaImplDemo.java new file mode 100644 index 0000000..c081128 --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/javaImpl/AopJavaImplDemo.java @@ -0,0 +1,155 @@ +package cn.hncu.javaImpl; + +import java.lang.reflect.Method; + +import org.aopalliance.aop.Advice; +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; +import org.junit.Test; +import org.springframework.aop.Advisor; +import org.springframework.aop.AfterAdvice; +import org.springframework.aop.AfterReturningAdvice; +import org.springframework.aop.MethodBeforeAdvice; +import org.springframework.aop.ThrowsAdvice; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.aop.framework.ProxyFactoryBean; +import org.springframework.aop.support.DefaultPointcutAdvisor; +import org.springframework.aop.support.JdkRegexpMethodPointcut; +import org.springframework.aop.support.RegexpMethodPointcutAdvisor; + +/** + * 纯Java的方式实现切面(拦截)技术 + * @author 陈浩翔 + * 2016-9-1 + */ +public class AopJavaImplDemo { + + //如果你对动态代理有过了解了,对下面的代码会很好理解的 + @Test + public void demo1(){ + //准备好需要被代理的原型对象 + Person p = new Person(); + ProxyFactory factory = new ProxyFactory();//ProxyFactoryBean的功能比ProxyFactory强 + factory.setTarget(p);//给代理工厂一个原型对象 + + //构造切面 + //切面=切点 + 通知 + + //切点 + JdkRegexpMethodPointcut cut = new JdkRegexpMethodPointcut(); + //cut.setPattern("cn.hncu.javaImpl.Person.run");//可以直接给方法全名 + //或者给正则表达式 + cut.setPattern(".*run.*");//.号匹配除"\r\n"之外的任何单个字符。*号代表零次或多次匹配前面的字符或子表达式 + + //通知 + Advice advice = new MethodInterceptor() { + //哈哈,看到这个是不是和动态代理中的那个方法很像 + @Override + public Object invoke(MethodInvocation methodInv) throws Throwable { + System.out.println("前面拦拦..."); + Object resObj = methodInv.proceed();//放行 + System.out.println("后面拦拦..."); + return resObj; + } + }; + //切面 = 切点 + 通知 + Advisor advisor = new DefaultPointcutAdvisor(cut, advice); + + factory.addAdvisor(advisor);//给代理工厂一个切面 + Person p2 = (Person) factory.getProxy();//从代理工厂中获取一个代理后的对象 + + try { + p2.run(); + } catch (Exception e) { + e.printStackTrace(); + } + p2.say();//不会拦 + p2.run(3333); + } + + + @Test + public void demo2(){ + ProxyFactoryBean factory = new ProxyFactoryBean(); + factory.setTarget(new Person());//给代理工厂一个原型对象 + + //切面 = 切点 + 通知 + //切点 + JdkRegexpMethodPointcut cut = new JdkRegexpMethodPointcut(); + cut.setPatterns(new String[]{".*run.*",".*say.*"});//可以配置多个正则表达式 + + //通知 前切面---不需要放行,原方法也能执行 + Advice before = new MethodBeforeAdvice() { + @Override + public void before(Method method, Object[] args, Object obj) + throws Throwable { + System.out.println("before...拦截"); + } + }; + + Advice after = new AfterReturningAdvice() { + + @Override + public void afterReturning(Object returnValue, Method method, + Object[] args, Object target) throws Throwable { + System.out.println("afterReturning...拦截"); + } + }; + +// Advice throwsAdvice = new A(); +// Advice afterAdvice = new AfterAdvice() { +// }; + + + Advice around = new MethodInterceptor() { + + @Override + public Object invoke(MethodInvocation invocation) throws Throwable { + System.out.println("MethodInterceptor...前面拦截"); + Object returnValue = invocation.proceed();//放行 + System.out.println("MethodInterceptor...后面拦截"); + return returnValue; + } + }; + + //切面 = 切点 + 通知 + Advisor beforeAdvisor = new DefaultPointcutAdvisor(cut, before); + Advisor afterAdvisor = new DefaultPointcutAdvisor(cut,after); + Advisor aroundAdvisor = new DefaultPointcutAdvisor(cut, around); +// Advisor throwsAdviceAdvisor = new DefaultPointcutAdvisor(cut, throwsAdvice); + + // 给代理工厂一个切面 ---注意,添加的顺序的拦截动作执行的顺序是有关系的!!! + //factory.addAdvisors(beforeAdvisor,afterAdvisor,aroundAdvisor); + //factory.addAdvisors(beforeAdvisor,aroundAdvisor,afterAdvisor); + factory.addAdvisors(aroundAdvisor,beforeAdvisor,afterAdvisor); + + Person p2 = (Person) factory.getObject();//从代理工厂中获取一个代理后的对象 + + p2.run(2222); + } + + @Test + public void demo3(){ + ProxyFactoryBean factory = new ProxyFactoryBean(); + factory.setTarget(new Person());//给代理工厂一个原型对象 + + //切面 = 切点 + 通知 + //切点 + JdkRegexpMethodPointcut cut = new JdkRegexpMethodPointcut(); + cut.setPatterns(new String[]{".*run.*",".*say.*"});//可以配置多个正则表达式 + + Advice throwsAdvice = new ThrowException(); + + //切面 = 切点 + 通知 + Advisor throwsAdviceAdvisor = new DefaultPointcutAdvisor(cut, throwsAdvice); + + factory.addAdvisors(throwsAdviceAdvisor); + + Person p2 = (Person) factory.getObject();//从代理工厂中获取一个代理后的对象 + + p2.run(); + p2.run(2222); + } + + +} diff --git a/Spring/mySpringAopDemo/src/cn/hncu/javaImpl/Person.java b/Spring/mySpringAopDemo/src/cn/hncu/javaImpl/Person.java new file mode 100644 index 0000000..988747e --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/javaImpl/Person.java @@ -0,0 +1,17 @@ +package cn.hncu.javaImpl; + +public class Person { + public void run(){ + System.out.println("我在run..."); + } + + public void run(int i){ + System.out.println("我在run"+i+"..."); + throw new IllegalArgumentException(); + } + + public void say(){ + System.out.println("我在say..."); + } + +} diff --git a/Spring/mySpringAopDemo/src/cn/hncu/javaImpl/ThrowException.java b/Spring/mySpringAopDemo/src/cn/hncu/javaImpl/ThrowException.java new file mode 100644 index 0000000..5ddb664 --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/javaImpl/ThrowException.java @@ -0,0 +1,9 @@ +package cn.hncu.javaImpl; + +import org.springframework.aop.ThrowsAdvice; + +public class ThrowException implements ThrowsAdvice{ + public void afterThrowing(Exception e) throws Throwable{ + System.out.println("出异常了..."+e); + } +} diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/1.xml b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/1.xml new file mode 100644 index 0000000..af23706 --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/1.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + advisor + + + + + + \ No newline at end of file diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/2.xml b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/2.xml new file mode 100644 index 0000000..e529360 --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/2.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + advisor + + + + + + \ No newline at end of file diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/3.xml b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/3.xml new file mode 100644 index 0000000..95aac6e --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/3.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + .*run.* + + + + + + + + + + + + + + + + + advisor + + + + + + \ No newline at end of file diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/4.xml b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/4.xml new file mode 100644 index 0000000..ee4c5fd --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/4.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + .*run.* + + + + + + + + + + + + + \ No newline at end of file diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/5.xml b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/5.xml new file mode 100644 index 0000000..c271198 --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/5.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + .*run.* + + + + + + + + + + + + \ No newline at end of file diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/6.xml b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/6.xml new file mode 100644 index 0000000..e2ae3f4 --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/6.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + .*run.* + + + + + + + + + \ No newline at end of file diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/AopXmlDemo.java b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/AopXmlDemo.java new file mode 100644 index 0000000..0a904ec --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/AopXmlDemo.java @@ -0,0 +1,63 @@ +package cn.hncu.xmlImpl; + +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + + +/** + * 采用配置文件的方式使用切面拦截 + * @author 陈浩翔 + * 2016-9-2 + */ +public class AopXmlDemo { + + @Test//把切点和通知配置成 切面的外部bean + public void demo1(){ + ApplicationContext ctx = new ClassPathXmlApplicationContext("cn/hncu/xmlImpl/1.xml"); + Person p =ctx.getBean("personProxied",Person.class); + p.run(); + p.say(); + } + + @Test//把切点和通知配置成 切面的内部bean + public void demo2(){ + ApplicationContext ctx = new ClassPathXmlApplicationContext("cn/hncu/xmlImpl/2.xml"); + Person p =ctx.getBean("personProxied",Person.class); + p.run(); + p.say(); + } + + @Test//直接在切面bean中配置“切点的正则表达式”,省去“切点bean”的配置 + public void demo3(){ + ApplicationContext ctx = new ClassPathXmlApplicationContext("cn/hncu/xmlImpl/3.xml"); + Person p =ctx.getBean("personProxied",Person.class); + p.run(); + p.say(); + } + + @Test//自动代理 + public void demo4(){ + ApplicationContext ctx = new ClassPathXmlApplicationContext("cn/hncu/xmlImpl/4.xml"); + Person p =ctx.getBean(Person.class); + p.run(); + p.say(); + } + + @Test//自己实现的自动代理 + public void demo5(){ + ApplicationContext ctx = new ClassPathXmlApplicationContext("cn/hncu/xmlImpl/5.xml"); + Person p =ctx.getBean(Person.class); + p.run(); + p.say(); + } + + @Test//自动代理 + public void demo6(){ + ApplicationContext ctx = new ClassPathXmlApplicationContext("cn/hncu/xmlImpl/6.xml"); + Person p =ctx.getBean(Person.class); + p.run(); + p.say(); + } + +} diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/AroundAdvice.java b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/AroundAdvice.java new file mode 100644 index 0000000..17e6df7 --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/AroundAdvice.java @@ -0,0 +1,15 @@ +package cn.hncu.xmlImpl; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +public class AroundAdvice implements MethodInterceptor{ + @Override + public Object invoke(MethodInvocation invocation) throws Throwable { + System.out.println("前面拦截...."); + Object resObj = invocation.proceed();//放行 + System.out.println("后面拦截....."); + return resObj; + } + +} diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/MyAutoProxy.java b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/MyAutoProxy.java new file mode 100644 index 0000000..95c947c --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/MyAutoProxy.java @@ -0,0 +1,41 @@ +package cn.hncu.xmlImpl; + +import org.springframework.aop.Advisor; +import org.springframework.aop.framework.ProxyFactoryBean; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; + +public class MyAutoProxy implements BeanPostProcessor,ApplicationContextAware{ + private ApplicationContext applicationContext=null; + + //bean创建之前调用 + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) + throws BeansException { + return bean;//在这里,我们直接放行 + } + + //bean创建之后调用 + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) + throws BeansException { + ProxyFactoryBean factory = new ProxyFactoryBean(); + //把原型对象放入代理工厂 + factory.setTarget(bean); + //在这里 + Advisor adv = applicationContext.getBean(Advisor.class); + factory.addAdvisor(adv); + //返回被代理后的对象 + return factory.getObject(); + } + + //拿到原来的spring中的容器 + @Override + public void setApplicationContext(ApplicationContext applicationContext) + throws BeansException { + this.applicationContext=applicationContext; + } + +} diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/Person.java b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/Person.java new file mode 100644 index 0000000..39433ee --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/Person.java @@ -0,0 +1,16 @@ +package cn.hncu.xmlImpl; + +public class Person { + public void run(){ + System.out.println("我在run..."); + } + + public void run(int i){ + System.out.println("我在run"+i+"..."); + } + + public void say(){ + System.out.println("我在say..."); + } + +} diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/AroundAdvice.java b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/AroundAdvice.java new file mode 100644 index 0000000..c31df58 --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/AroundAdvice.java @@ -0,0 +1,15 @@ +package cn.hncu.xmlImpl.aspectj; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +public class AroundAdvice implements MethodInterceptor{ + @Override + public Object invoke(MethodInvocation invocation) throws Throwable { + System.out.println("前面拦截...."); + Object resObj = invocation.proceed();//放行 + System.out.println("后面拦截....."); + return resObj; + } + +} diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/AspectjDemo.java b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/AspectjDemo.java new file mode 100644 index 0000000..5e97a6e --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/AspectjDemo.java @@ -0,0 +1,57 @@ +package cn.hncu.xmlImpl.aspectj; + +import org.aopalliance.aop.Advice; +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; +import org.junit.Test; +import org.springframework.aop.Advisor; +import org.springframework.aop.aspectj.AspectJExpressionPointcut; +import org.springframework.aop.framework.ProxyFactoryBean; +import org.springframework.aop.support.DefaultPointcutAdvisor; + +public class AspectjDemo { + + @Test + public void demo(){ + + ProxyFactoryBean factory = new ProxyFactoryBean(); + factory.setTarget(new Person()); + + //声明一个aspectj切点 + AspectJExpressionPointcut cut = new AspectJExpressionPointcut(); + + //设置需要拦截的方法-用切点语言来写 + cut.setExpression("execution( int cn.hncu.xmlImpl.aspectj.Person.run() )");//拦截:空参返回值为int的run方法 + //cut.setExpression("execution( void cn.hncu.xmlImpl.aspectj.Person.*() )");//拦截:空参空返回值的任意方法 + //cut.setExpression("execution (void cn.hncu.xmlImpl.aspectj.Person.*(String))");//拦截:只有1个String类型参数,空返回值的任意方法 + //cut.setExpression("execution( void cn.hncu.xmlImpl.aspectj.Person.*(*) )");//拦截:有1个参数(类型不限),空返回值的任意方法 + //cut.setExpression("execution( void cn.hncu.xmlImpl.aspectj.Person.*(*,*) )");//拦截:有2个参数(类型不限),空返回值的任意方法 + //cut.setExpression("execution( void cn.hncu.xmlImpl.aspectj.Person.*(..) )");//拦截:任意(个数和类型)参数,空返回值的任意方法 + //cut.setExpression("execution( int cn.hncu.xmlImpl.aspectj.Person.*(*,..) )");//拦截:至少有1个参数(类型不限),返回值类型是int的任意方法 + //cut.setExpression("execution( * cn.hncu.xmlImpl.aspectj.Person.*(*,..) )");//拦截:至少有1个参数(类型不限),返回值类型任意的方法 + //cut.setExpression("execution( * cn.hncu..*son.*(*,..) )");//拦截:cn.hncu包下,类名以"son"结束,至少有1个参数(类型不限),返回值类型任意的方法 + + Advice advice = new MethodInterceptor() { + @Override + public Object invoke(MethodInvocation invocation) throws Throwable { + System.out.println("放行前拦截..."); + Object obj = invocation.proceed();//放行 + System.out.println("放行后拦截..."); + return obj; + } + }; + + //切面=切点+通知 + Advisor advisor = new DefaultPointcutAdvisor(cut,advice); + factory.addAdvisor(advisor); + Person p = (Person) factory.getObject(); + + p.run(); + p.run(10); + p.say(); + p.sayHi("Jack"); + p.say("Tom", 666); + } + + +} diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/AspectjXmlDemo.java b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/AspectjXmlDemo.java new file mode 100644 index 0000000..4e5d159 --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/AspectjXmlDemo.java @@ -0,0 +1,18 @@ +package cn.hncu.xmlImpl.aspectj; + +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class AspectjXmlDemo { + @Test + public void demo1(){ + ApplicationContext ctx = new ClassPathXmlApplicationContext("cn/hncu/xmlImpl/aspectj/aspectj.xml"); + Person p = ctx.getBean(Person.class); + p.run(); + p.run(10); + p.say(); + p.sayHi("Jack"); + p.say("Tom", 666); + } +} diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/Person.java b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/Person.java new file mode 100644 index 0000000..156a3ea --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/Person.java @@ -0,0 +1,24 @@ +package cn.hncu.xmlImpl.aspectj; + +public class Person { + public int run(){ + System.out.println("返回值为int-我在run..."); + return 0; + } + + public void run(int i){ + System.out.println("我在run...<"+i+">"); + } + + public void say(){ + System.out.println("我在say..."); + } + public void sayHi(String name){ + System.out.println("Hi,"+name+",你好"); + } + public int say(String name, int i){ + System.out.println(name+ "----"+ i); + return 0; + } + +} diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/aspectj.xml b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/aspectj.xml new file mode 100644 index 0000000..44d6062 --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/aspectj.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/aspectj2.xml b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/aspectj2.xml new file mode 100644 index 0000000..7a31be6 --- /dev/null +++ b/Spring/mySpringAopDemo/src/cn/hncu/xmlImpl/aspectj/aspectj2.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Spring/mySpringWebDemo/.classpath b/Spring/mySpringWebDemo/.classpath new file mode 100644 index 0000000..96c5a3c --- /dev/null +++ b/Spring/mySpringWebDemo/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Spring/mySpringWebDemo/.mymetadata b/Spring/mySpringWebDemo/.mymetadata new file mode 100644 index 0000000..915729f --- /dev/null +++ b/Spring/mySpringWebDemo/.mymetadata @@ -0,0 +1,13 @@ + + + + + + + diff --git a/Spring/mySpringWebDemo/.project b/Spring/mySpringWebDemo/.project new file mode 100644 index 0000000..1051ac9 --- /dev/null +++ b/Spring/mySpringWebDemo/.project @@ -0,0 +1,58 @@ + + + mySpringWebDemo + + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + com.genuitec.eclipse.j2eedt.core.WebClasspathBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + com.genuitec.eclipse.j2eedt.core.J2EEProjectValidator + + + + + com.genuitec.eclipse.j2eedt.core.DeploymentDescriptorValidator + + + + + org.eclipse.wst.validation.validationbuilder + + + + + com.genuitec.eclipse.ast.deploy.core.DeploymentBuilder + + + + + + com.genuitec.eclipse.ast.deploy.core.deploymentnature + org.eclipse.jem.workbench.JavaEMFNature + com.genuitec.eclipse.j2eedt.core.webnature + org.eclipse.jdt.core.javanature + org.eclipse.wst.jsdt.core.jsNature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.common.modulecore.ModuleCoreNature + + diff --git a/Spring/mySpringWebDemo/.settings/.jsdtscope b/Spring/mySpringWebDemo/.settings/.jsdtscope new file mode 100644 index 0000000..252e54f --- /dev/null +++ b/Spring/mySpringWebDemo/.settings/.jsdtscope @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/Spring/mySpringWebDemo/.settings/org.eclipse.core.resources.prefs b/Spring/mySpringWebDemo/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..a2ea129 --- /dev/null +++ b/Spring/mySpringWebDemo/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,3 @@ +#Sun Sep 04 10:47:33 CST 2016 +eclipse.preferences.version=1 +encoding//WebRoot/WEB-INF/conf/jdbc.properties=UTF-8 diff --git a/Spring/mySpringWebDemo/.settings/org.eclipse.jdt.core.prefs b/Spring/mySpringWebDemo/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..3e09a61 --- /dev/null +++ b/Spring/mySpringWebDemo/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Sat Sep 03 14:04:48 CST 2016 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/Spring/mySpringWebDemo/.settings/org.eclipse.wst.common.component b/Spring/mySpringWebDemo/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..242e735 --- /dev/null +++ b/Spring/mySpringWebDemo/.settings/org.eclipse.wst.common.component @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Spring/mySpringWebDemo/.settings/org.eclipse.wst.common.project.facet.core.xml b/Spring/mySpringWebDemo/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..5a88726 --- /dev/null +++ b/Spring/mySpringWebDemo/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Spring/mySpringWebDemo/.settings/org.eclipse.wst.jsdt.ui.superType.container b/Spring/mySpringWebDemo/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/Spring/mySpringWebDemo/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/Spring/mySpringWebDemo/.settings/org.eclipse.wst.jsdt.ui.superType.name b/Spring/mySpringWebDemo/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/Spring/mySpringWebDemo/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/Spring/mySpringWebDemo/README.md b/Spring/mySpringWebDemo/README.md new file mode 100644 index 0000000..39096be --- /dev/null +++ b/Spring/mySpringWebDemo/README.md @@ -0,0 +1,470 @@ + + + + + +【框架】[Spring] 基于Spring框架的Web应用演示(附带cglib工具进行动态代理) + + + +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ + + +

前言:

+ +

Spring也差不多学了Ioc控制反转和实现AOP技术的两种方式了,分享一个学习Spring,用来入门挺好的例子。

+ +

如果你是刚刚学习Spring,那么此实例应该可以很好的帮助你应用Spring到Web项目中。

+ +

里面的DAO层-提交数据库的事务我并没有使用Spring 的注解功能,而是用spring的AOP来实现的。这样更灵活,其实,框架为我们做的事越多,我们就越受框架的约束。想把功能做灵活,就越难实现。

+ +

只要我们把底层学好,框架的功能我们都能自己写出来的,而且自己写出来的东西,肯定会更熟悉。
+框架是为了降低程序之间的依赖性和耦合性,使重用性达到最高。

+ +

学习框架,我更多的希望自己能学会框架的思想,理解为什么!

+ + + +

首先准备数据库:

+ + + +
create database mydb charset=utf8;
+
+create table stud(
+  s_id varchar(32) primary key,
+  s_name varchar(40)
+);
+
+create table book(
+  b_id int primary key  auto_increment,
+  b_name varchar(40)
+);
+ +

准备好这2个表:

+ +

+ + + +

Jar包少不了:

+ +

+ +

相信学到这一步的朋友应该有了自己的一个配套包了吧,在这里我就不去一 一将包链接写出了。
+如果需要这些包的,在本博客最后我会给出整个项目的链接,请到里面的WEB-INF/lib目录下去下载。

+ + + +

配好web.xml:

+ +

配置web.xml-以使用Spring。

+ + + +
  <context-param>
+        <!-- param的name必须为contextConfigLocation,Spring内部会解析的 -->
+        <param-name>contextConfigLocation</param-name>
+        <!-- contextConfigLocation参数的值,课配置多个,用英文逗号隔开 -->
+        <param-value>
+            classpath:beans.xml,
+            /WEB-INF/conf/applicationContext.xml
+        </param-value>
+  </context-param>
+  <listener>
+        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
+  </listener>
+ +

org.springframework.web.context.ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行Spring实现的方法。

+ +

小知识点:
+容器对于web.xml的加载过程是context-param >> listener >> fileter >> servlet.

+ +

接下来就是写:
+classpath:beans.xml和/WEB-INF/conf/applicationContext.xml这2个xml。
+classpath:代表beans.xml的位置在src(bin)目录下。

+ +

既然需要连接数据库,我们还需要一个配置文件jdbc.properties,声明一些数据库的协议(其实可以在applicationContext.xml中直接配置的,可以不用这个文件)

+ + + +

jdbc.properties:

+ +

+ + + +
#如果是utf-8编码,第一行必须空一行.因为utf-8的文件开头有一个符号
+#在本例中,我用这个配置文件会出现账号密码错误,无法连接数据库,原因未知
+#所以,我在本例是直接配置dataSource的,未用到本文件
+#数据库驱动包
+driver=com.mysql.jdbc.Driver
+#连接数据库的协议--三个"/"代表通过数据库默认端口连接本机的数据库,也可以写成//localhost:3306/
+url=jdbc:mysql:///mydb?characterEncoding=utf-8
+username=root
+pwd=1234
+#其实前面的4个变量名都是自己随便可以取的,因为真正的读取不是在这里
+#真正的读取在applicationContext.xml中
+ +

在applicationContext.xml配置如下就可以拿到数据库连接了。

+ + + +
    <!-- 使用jdbc.properties配置文件,就要写下面这句 -->
+<!--    <context:property-placeholder location="WEB-INF/conf/jdbc.properties"/> -->
+    <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
+        <!-- 使用jdbc.properties配置文件,类似如下配置 -->
+<!--        <property name="driverClass" value="${driver}"></property> -->
+        <property name="driverClass" value="com.mysql.jdbc.Driver"></property> 
+        <property name="url" value="jdbc:mysql:///mydb?characterEncoding=UTF-8"></property> 
+        <property name="username" value="root"></property> 
+        <property name="password" value="1234"></property> 
+    </bean>
+ + + +

beans.xml

+ +

写好DAO,service,servlet层的架构-方法和变量:
+在beans.xml中配置好DAO,service的初始化bean,初始化属性。
+而由于我们在web.xml配置了servlet,是Tomcat帮我们new-servlet的,所以,但是我们需要在servlet中需要访问service的对象,这个时候,我们就可以利用servlet的生命周期,在init方法中,给service对象赋值.

+ + + +
<?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:tx="http://www.springframework.org/schema/tx"
+        xsi:schemaLocation="http://www.springframework.org/schema/beans%20http://www.springframework.org/schema/beans/spring-beans-4.3.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/context%20http://www.springframework.org/schema/context/spring-context-4.3.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/tx%20http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
+    <bean id="studDao" class="cn.hncu.stud.dao.StudDaoJdbc">
+       <!--ref="dataSource",引用applicationContext.xml中的dataSource  -->
+       <property name="dataSource" ref="dataSource"></property>
+    </bean>
+    <bean id="bookDao" class="cn.hncu.stud.dao.BookDaoJdbc">
+       <!--ref="dataSource",引用applicationContext.xml中的dataSource  -->
+       <property name="dataSource" ref="dataSource"></property>
+    </bean>
+
+    <bean id="saveService" class="cn.hncu.stud.service.StudServiceImpl">
+        <property name="studDao" ref="studDao"></property>
+        <property name="bookDao" ref="bookDao"></property>
+    </bean>
+</beans>
+
+ + + +

servlet中加入此方法,实现service的初始化:

+ + + +
@Override
+    public void init() throws ServletException {
+        //在这里,我们可以直接获取Web中的Spring容器-不能重新去new,因为那样就不是同一个容器的了
+        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
+        service=ctx.getBean(ISaveService.class);
+    }
+ + + +

TxAdvice-AOP通知

+ + + +
package cn.hncu.utils;
+
+import java.sql.Connection;
+
+import javax.sql.DataSource;
+
+import org.aopalliance.intercept.MethodInterceptor;
+import org.aopalliance.intercept.MethodInvocation;
+import org.springframework.beans.BeansException;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+
+//另外一种方法获取Web中的spring容器--实现ApplicationContextAware接口
+public class TxAdvice implements MethodInterceptor,ApplicationContextAware{
+    private ApplicationContext ctx =null;
+
+    @Override
+    public void setApplicationContext(ApplicationContext ctx)
+            throws BeansException {
+        this.ctx=ctx;
+    }
+
+    //通知---这个里面需要拿到dataSource,所以需要先拿到Spring的容器
+    @Override
+    public Object invoke(MethodInvocation invocation) throws Throwable {
+        DataSource dataSource = ctx.getBean(DataSource.class);
+
+        Connection con = dataSource.getConnection();
+        Object res =null;
+        try {
+            con.setAutoCommit(false);
+            //开启一个事务
+            res = invocation.proceed();//放行
+            con.commit();//提交
+            System.out.println("提交一个事务...");
+        } catch (Exception e) {
+            con.rollback();
+            System.out.println("事务回滚...");
+        }finally{
+            con.setAutoCommit(true);//关闭事务
+            con.close();
+        }
+        return res;
+    }
+
+
+}
+
+ + + +

事务

+ +

如果只代理到上面这里,写con.close方法其实会出问题的。
+当然,本例很简单,servlet只请求了一个service中的一个方法,这样写没什么问题,
+但是,假如我有多个service和一个service有多个方法,需要被一个用户请求servlet时同时调用时,这个连接就不能被关闭了。
+因为Spring容器的事务机制的实质是对传统JDBC的封装,也即是Spring事务管理无论是对单数据库实例还是分布式数据库实例,要实现事务管理,那么必须保证在一个事务过程获得Connetion对象是同一个。

+ +

假如是servlet调用多个service或service中多个方法,需要实现的是同一个事务,我们可以:在service中写一个综合方法,在其中调用其它方法,然后给综合方法设置代理,因为这个综合方法在这里就是一个业务
+,多个service,原理一样。

+ + + +

AOP拦截getConnection()方法,cglib工具进行动态代理Connection

+ +

然后再拦截Connection的close方法!

+ + + +
package cn.hncu.utils;
+
+import java.lang.reflect.Method;
+import java.sql.Connection;
+
+import net.sf.cglib.proxy.Callback;
+import net.sf.cglib.proxy.Enhancer;
+import net.sf.cglib.proxy.MethodProxy;
+
+import org.aopalliance.intercept.MethodInterceptor;
+import org.aopalliance.intercept.MethodInvocation;
+
+public class CloseAdvice implements MethodInterceptor{
+    private ThreadLocal<Object> t = new ThreadLocal<Object>();
+
+    @Override
+    public Object invoke(MethodInvocation invocation) throws Throwable {
+
+        Object obj = t.get();
+        if(obj==null){
+
+            final Object con = invocation.proceed();//返回原型对象Connection
+
+            //通过cglib工具进行动态代理
+            Callback callback = new net.sf.cglib.proxy.MethodInterceptor() {
+
+                @Override
+                public Object intercept(Object proxiedObj, Method method,
+                        Object[] args, MethodProxy proxy) throws Throwable {
+                    if(method.getName().equals("close")){
+                        return null;
+                    }
+                    //con为原型Connection对象
+                    return method.invoke(con, args);
+                }
+            };
+
+            //obj为cglib工具代理后的Connection对象
+            obj=Enhancer.create(Connection.class, callback);
+            t.set(obj);
+        }
+        return obj;
+    }
+
+
+
+
+
+}
+
+ + + +

在applicationContext.xml中配置拦截getConnection()

+ + + +
<bean id="conClose" class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor">
+       <property name="expression" value="execution( * *..*.*.getConnection() )"></property>
+       <property name="advice">
+            <bean id="advice" class="cn.hncu.utils.CloseAdvice"></bean>
+       </property>
+    </bean>
+ +

接下来就是要用到AOP了,拦截事务。
+拦截service层的。

+ + + +

拦截事务的切面配置:

+ + + +
<!-- 自动代理 -->
+    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"></bean>
+    <!-- 事务  切面=切点+通知 -->
+    <bean id="tx" class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor">
+        <!-- 拦截cn.hncu包下的,方法名最后为Service的任意返回值任意参数的方法 -->
+        <property name="expression" value="execution (* cn.hncu..*Service.*(..) )">
+        </property>
+        <property name="advice">
+            <bean class="cn.hncu.utils.TxAdvice"></bean>
+        </property>
+    </bean>
+ + + +

DAO层的实现类代码:

+ + + +

stud的实现类:

+ + + +
package cn.hncu.stud.dao;
+
+import java.sql.SQLException;
+import java.util.UUID;
+
+import javax.sql.DataSource;
+
+import org.apache.commons.dbutils.QueryRunner;
+
+import cn.hncu.stud.domain.Book;
+import cn.hncu.stud.domain.Stud;
+
+public class StudDaoJdbc implements StudDAO{
+    private DataSource dataSource = null;//依赖注入
+    public DataSource getDataSource() {
+        return dataSource;
+    }
+
+    public void setDataSource(DataSource dataSource) {
+        this.dataSource = dataSource;
+    }
+
+    @Override
+    public void saveStud(Stud stud) throws SQLException {
+        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
+        stud.setS_id(uuid);
+        QueryRunner run = new QueryRunner(dataSource);
+        run.update("insert into stud(s_id,s_name) values(?,?)", stud.getS_id(),stud.getS_name());
+    }
+}
+
+ + + +

book的实现类

+ + + +
package cn.hncu.stud.dao;
+
+import java.sql.SQLException;
+
+import javax.sql.DataSource;
+
+import org.apache.commons.dbutils.QueryRunner;
+
+import cn.hncu.stud.domain.Book;
+
+public class BookDaoJdbc implements BookDAO{
+    private DataSource dataSource = null;//依赖注入
+
+    public DataSource getDataSource() {
+        return dataSource;
+    }
+
+    public void setDataSource(DataSource dataSource) {
+        this.dataSource = dataSource;
+    }
+
+    @Override
+    public void saveBook(Book book) throws SQLException {
+        QueryRunner run = new QueryRunner(dataSource);
+        run.update("insert into book(b_name) values(?)", book.getB_name());
+    }
+
+}
+
+ + + +

测试:

+ +

打开页面输入:

+ +

+ +

点按钮提交:

+ +


+service:cn.hncu.stud.service.SaveServiceImpl@4adeee3d这个输出是我在servlet中测试一个错误的时候的输出。

+ +

再看数据库的数据:

+ +

+ +

+ +

然后,我们来测试下,事务回滚情况:

+ +

因为service层是:

+ + + +
@Override
+    public void saveStudAndBook(Stud stud, Book book) throws SQLException {
+        studDao.saveStud(stud);
+        bookDao.saveBook(book);
+    }
+ +

后调用bookDao的,所以,我们让saveBook挂了,改一下saveBook的方法中sql语句为:
+

+ +

这样,后面Book的存储肯定是出问题的。

+ +

再来测试:
+

+ +

点添加。

+ +

+ +

可以看到事务回滚了,但是看这里没用,我们去看下stud和book表有没有存储。当然book表肯定是不会被存储的,去看stud表就可以了:

+ +

+ +

可以看到,李四这个用户并没有被保存,证明事务起作用了。

+ +

此实例适合初学Spring者学习哦。

+ +

本文章由[谙忆]编写, 所有权利保留。

+ +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ \ No newline at end of file diff --git a/Spring/mySpringWebDemo/WebRoot/META-INF/MANIFEST.MF b/Spring/mySpringWebDemo/WebRoot/META-INF/MANIFEST.MF new file mode 100644 index 0000000..254272e --- /dev/null +++ b/Spring/mySpringWebDemo/WebRoot/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/beans.xml b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/beans.xml new file mode 100644 index 0000000..fb613ba --- /dev/null +++ b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/beans.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/dao/BookDAO.class b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/dao/BookDAO.class new file mode 100644 index 0000000..d47f822 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/dao/BookDAO.class differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/dao/BookDaoJdbc.class b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/dao/BookDaoJdbc.class new file mode 100644 index 0000000..78c5629 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/dao/BookDaoJdbc.class differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/dao/StudDAO.class b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/dao/StudDAO.class new file mode 100644 index 0000000..8969622 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/dao/StudDAO.class differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/dao/StudDaoJdbc.class b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/dao/StudDaoJdbc.class new file mode 100644 index 0000000..cb838a2 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/dao/StudDaoJdbc.class differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/domain/Book.class b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/domain/Book.class new file mode 100644 index 0000000..8a74efe Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/domain/Book.class differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/domain/Stud.class b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/domain/Stud.class new file mode 100644 index 0000000..19455b8 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/domain/Stud.class differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/service/ISaveService.class b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/service/ISaveService.class new file mode 100644 index 0000000..410013b Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/service/ISaveService.class differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/service/SaveServiceImpl.class b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/service/SaveServiceImpl.class new file mode 100644 index 0000000..0177cf0 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/service/SaveServiceImpl.class differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/servlet/StudServlet.class b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/servlet/StudServlet.class new file mode 100644 index 0000000..36d9c65 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/stud/servlet/StudServlet.class differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/utils/CloseAdvice$1.class b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/utils/CloseAdvice$1.class new file mode 100644 index 0000000..435c136 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/utils/CloseAdvice$1.class differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/utils/CloseAdvice.class b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/utils/CloseAdvice.class new file mode 100644 index 0000000..64c303a Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/utils/CloseAdvice.class differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/utils/TxAdvice.class b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/utils/TxAdvice.class new file mode 100644 index 0000000..a225646 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/classes/cn/hncu/utils/TxAdvice.class differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/conf/applicationContext.xml b/Spring/mySpringWebDemo/WebRoot/WEB-INF/conf/applicationContext.xml new file mode 100644 index 0000000..c5fe4de --- /dev/null +++ b/Spring/mySpringWebDemo/WebRoot/WEB-INF/conf/applicationContext.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/conf/jdbc.properties b/Spring/mySpringWebDemo/WebRoot/WEB-INF/conf/jdbc.properties new file mode 100644 index 0000000..1ec6400 --- /dev/null +++ b/Spring/mySpringWebDemo/WebRoot/WEB-INF/conf/jdbc.properties @@ -0,0 +1,6 @@ +#如果是utf-8编码,这里必须空一行.因为utf-8的文件开头有一个符号- +#在本例中,我用这个配置文件会出现账号密码错误,无法连接数据库,原因未知 +driver=com.mysql.jdbc.Driver +url=jdbc\:mysql\:///mydb?characterEncoding\=UTF-8 +username=root +pwd=1234 \ No newline at end of file diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/aspectjweaver-1.8.9.jar b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/aspectjweaver-1.8.9.jar new file mode 100644 index 0000000..87f5c8f Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/aspectjweaver-1.8.9.jar differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/cglib-nodep-2.1_3.jar b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/cglib-nodep-2.1_3.jar new file mode 100644 index 0000000..e9b17eb Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/cglib-nodep-2.1_3.jar differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/commons-dbutils-1.3.jar b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/commons-dbutils-1.3.jar new file mode 100644 index 0000000..953e13c Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/commons-dbutils-1.3.jar differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/commons-logging.jar b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/commons-logging.jar new file mode 100644 index 0000000..8758a96 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/commons-logging.jar differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.34-bin.jar b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.34-bin.jar new file mode 100644 index 0000000..0236900 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.34-bin.jar differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-aop-4.3.2.RELEASE.jar b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-aop-4.3.2.RELEASE.jar new file mode 100644 index 0000000..e89e193 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-aop-4.3.2.RELEASE.jar differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-beans-4.3.2.RELEASE.jar b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-beans-4.3.2.RELEASE.jar new file mode 100644 index 0000000..bd08cf8 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-beans-4.3.2.RELEASE.jar differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-context-4.3.2.RELEASE.jar b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-context-4.3.2.RELEASE.jar new file mode 100644 index 0000000..c88bdd9 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-context-4.3.2.RELEASE.jar differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-core-4.3.2.RELEASE.jar b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-core-4.3.2.RELEASE.jar new file mode 100644 index 0000000..e89f6f1 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-core-4.3.2.RELEASE.jar differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-expression-4.3.2.RELEASE.jar b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-expression-4.3.2.RELEASE.jar new file mode 100644 index 0000000..9cf63ea Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-expression-4.3.2.RELEASE.jar differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-jdbc-4.3.2.RELEASE.jar b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-jdbc-4.3.2.RELEASE.jar new file mode 100644 index 0000000..b1e4183 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-jdbc-4.3.2.RELEASE.jar differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-tx-4.3.2.RELEASE.jar b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-tx-4.3.2.RELEASE.jar new file mode 100644 index 0000000..0e652e0 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-tx-4.3.2.RELEASE.jar differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-web-4.3.2.RELEASE.jar b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-web-4.3.2.RELEASE.jar new file mode 100644 index 0000000..f306ce0 Binary files /dev/null and b/Spring/mySpringWebDemo/WebRoot/WEB-INF/lib/spring-web-4.3.2.RELEASE.jar differ diff --git a/Spring/mySpringWebDemo/WebRoot/WEB-INF/web.xml b/Spring/mySpringWebDemo/WebRoot/WEB-INF/web.xml new file mode 100644 index 0000000..2e2fe35 --- /dev/null +++ b/Spring/mySpringWebDemo/WebRoot/WEB-INF/web.xml @@ -0,0 +1,33 @@ + + + + + + + contextConfigLocation + + + classpath:beans.xml, + /WEB-INF/conf/applicationContext.xml + + + + org.springframework.web.context.ContextLoaderListener + + + StudServlet + cn.hncu.stud.servlet.StudServlet + + + + StudServlet + /servlet/StudServlet + + + + index.jsp + + diff --git a/Spring/mySpringWebDemo/WebRoot/index.jsp b/Spring/mySpringWebDemo/WebRoot/index.jsp new file mode 100644 index 0000000..acef4d9 --- /dev/null +++ b/Spring/mySpringWebDemo/WebRoot/index.jsp @@ -0,0 +1,17 @@ +<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> +<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + + + + + 基于Spring框架的Web应用演示 + + + +

添加学生信息

+
+ 姓名:
+ 图书:
+ +
+ diff --git a/Spring/mySpringWebDemo/mySpringWebDemo.zip b/Spring/mySpringWebDemo/mySpringWebDemo.zip new file mode 100644 index 0000000..bee1186 Binary files /dev/null and b/Spring/mySpringWebDemo/mySpringWebDemo.zip differ diff --git a/Spring/mySpringWebDemo/src/beans.xml b/Spring/mySpringWebDemo/src/beans.xml new file mode 100644 index 0000000..fb613ba --- /dev/null +++ b/Spring/mySpringWebDemo/src/beans.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + diff --git a/Spring/mySpringWebDemo/src/cn/hncu/stud/dao/BookDAO.java b/Spring/mySpringWebDemo/src/cn/hncu/stud/dao/BookDAO.java new file mode 100644 index 0000000..172b0dd --- /dev/null +++ b/Spring/mySpringWebDemo/src/cn/hncu/stud/dao/BookDAO.java @@ -0,0 +1,9 @@ +package cn.hncu.stud.dao; + +import java.sql.SQLException; + +import cn.hncu.stud.domain.Book; + +public interface BookDAO { + public void saveBook(Book book) throws SQLException; +} diff --git a/Spring/mySpringWebDemo/src/cn/hncu/stud/dao/BookDaoJdbc.java b/Spring/mySpringWebDemo/src/cn/hncu/stud/dao/BookDaoJdbc.java new file mode 100644 index 0000000..aa4a6d7 --- /dev/null +++ b/Spring/mySpringWebDemo/src/cn/hncu/stud/dao/BookDaoJdbc.java @@ -0,0 +1,30 @@ +package cn.hncu.stud.dao; + +import java.sql.SQLException; + +import javax.sql.DataSource; + +import org.apache.commons.dbutils.QueryRunner; + +import cn.hncu.stud.domain.Book; + +public class BookDaoJdbc implements BookDAO{ + private DataSource dataSource = null;//依赖注入 + + public DataSource getDataSource() { + return dataSource; + } + + public void setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + } + + @Override + public void saveBook(Book book) throws SQLException { + QueryRunner run = new QueryRunner(dataSource); + //run.update("insert into book(b_name) values(?)", book.getB_name()); + //演示事务回滚 + run.update("insert into bme) values(?)", book.getB_name()); + } + +} diff --git a/Spring/mySpringWebDemo/src/cn/hncu/stud/dao/StudDAO.java b/Spring/mySpringWebDemo/src/cn/hncu/stud/dao/StudDAO.java new file mode 100644 index 0000000..f248c3d --- /dev/null +++ b/Spring/mySpringWebDemo/src/cn/hncu/stud/dao/StudDAO.java @@ -0,0 +1,10 @@ +package cn.hncu.stud.dao; + +import java.sql.SQLException; + +import cn.hncu.stud.domain.Book; +import cn.hncu.stud.domain.Stud; + +public interface StudDAO { + public void saveStud(Stud stud) throws SQLException; +} diff --git a/Spring/mySpringWebDemo/src/cn/hncu/stud/dao/StudDaoJdbc.java b/Spring/mySpringWebDemo/src/cn/hncu/stud/dao/StudDaoJdbc.java new file mode 100644 index 0000000..4c96764 --- /dev/null +++ b/Spring/mySpringWebDemo/src/cn/hncu/stud/dao/StudDaoJdbc.java @@ -0,0 +1,30 @@ +package cn.hncu.stud.dao; + +import java.sql.SQLException; +import java.util.UUID; + +import javax.sql.DataSource; + +import org.apache.commons.dbutils.QueryRunner; + +import cn.hncu.stud.domain.Book; +import cn.hncu.stud.domain.Stud; + +public class StudDaoJdbc implements StudDAO{ + private DataSource dataSource = null;//依赖注入 + public DataSource getDataSource() { + return dataSource; + } + + public void setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + } + + @Override + public void saveStud(Stud stud) throws SQLException { + String uuid = UUID.randomUUID().toString().replaceAll("-", ""); + stud.setS_id(uuid); + QueryRunner run = new QueryRunner(dataSource); + run.update("insert into stud(s_id,s_name) values(?,?)", stud.getS_id(),stud.getS_name()); + } +} diff --git a/Spring/mySpringWebDemo/src/cn/hncu/stud/domain/Book.java b/Spring/mySpringWebDemo/src/cn/hncu/stud/domain/Book.java new file mode 100644 index 0000000..7c58d57 --- /dev/null +++ b/Spring/mySpringWebDemo/src/cn/hncu/stud/domain/Book.java @@ -0,0 +1,24 @@ +package cn.hncu.stud.domain; + +public class Book { + private int b_id; + private String b_name; + public int getB_id() { + return b_id; + } + public void setB_id(int b_id) { + this.b_id = b_id; + } + public String getB_name() { + return b_name; + } + public void setB_name(String b_name) { + this.b_name = b_name; + } + @Override + public String toString() { + return "Book [b_id=" + b_id + ", b_name=" + b_name + "]"; + } + + +} diff --git a/Spring/mySpringWebDemo/src/cn/hncu/stud/domain/Stud.java b/Spring/mySpringWebDemo/src/cn/hncu/stud/domain/Stud.java new file mode 100644 index 0000000..9a80362 --- /dev/null +++ b/Spring/mySpringWebDemo/src/cn/hncu/stud/domain/Stud.java @@ -0,0 +1,23 @@ +package cn.hncu.stud.domain; + +public class Stud { + private String s_id; + private String s_name; + public String getS_id() { + return s_id; + } + public void setS_id(String s_id) { + this.s_id = s_id; + } + public String getS_name() { + return s_name; + } + public void setS_name(String s_name) { + this.s_name = s_name; + } + @Override + public String toString() { + return "Stud [s_id=" + s_id + ", s_name=" + s_name + "]"; + } + +} diff --git a/Spring/mySpringWebDemo/src/cn/hncu/stud/service/ISaveService.java b/Spring/mySpringWebDemo/src/cn/hncu/stud/service/ISaveService.java new file mode 100644 index 0000000..9d7b78f --- /dev/null +++ b/Spring/mySpringWebDemo/src/cn/hncu/stud/service/ISaveService.java @@ -0,0 +1,10 @@ +package cn.hncu.stud.service; + +import java.sql.SQLException; + +import cn.hncu.stud.domain.Book; +import cn.hncu.stud.domain.Stud; + +public interface ISaveService { + public void saveStudAndBook(Stud stud,Book book) throws SQLException; +} diff --git a/Spring/mySpringWebDemo/src/cn/hncu/stud/service/SaveServiceImpl.java b/Spring/mySpringWebDemo/src/cn/hncu/stud/service/SaveServiceImpl.java new file mode 100644 index 0000000..f9d1be4 --- /dev/null +++ b/Spring/mySpringWebDemo/src/cn/hncu/stud/service/SaveServiceImpl.java @@ -0,0 +1,35 @@ +package cn.hncu.stud.service; + +import java.sql.SQLException; + +import cn.hncu.stud.dao.BookDAO; +import cn.hncu.stud.dao.BookDaoJdbc; +import cn.hncu.stud.dao.StudDAO; +import cn.hncu.stud.domain.Book; +import cn.hncu.stud.domain.Stud; + +public class SaveServiceImpl implements ISaveService{ + //依赖注入 + private StudDAO studDao = null; + private BookDAO bookDao = null; + + //必须写好set-get方法 + public StudDAO getStudDao() { + return studDao; + } + public void setStudDao(StudDAO studDao) { + this.studDao = studDao; + } + public BookDAO getBookDao() { + return bookDao; + } + public void setBookDao(BookDAO bookDao) { + this.bookDao = bookDao; + } + @Override + public void saveStudAndBook(Stud stud, Book book) throws SQLException { + studDao.saveStud(stud); + bookDao.saveBook(book); + } + +} diff --git a/Spring/mySpringWebDemo/src/cn/hncu/stud/servlet/StudServlet.java b/Spring/mySpringWebDemo/src/cn/hncu/stud/servlet/StudServlet.java new file mode 100644 index 0000000..8e7b24b --- /dev/null +++ b/Spring/mySpringWebDemo/src/cn/hncu/stud/servlet/StudServlet.java @@ -0,0 +1,60 @@ +package cn.hncu.stud.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.sql.SQLException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.context.ApplicationContext; +import org.springframework.web.context.support.WebApplicationContextUtils; + +import cn.hncu.stud.domain.Book; +import cn.hncu.stud.domain.Stud; +import cn.hncu.stud.service.ISaveService; + +public class StudServlet extends HttpServlet { + //依赖注入 + private ISaveService service =null; + + @Override + public void init() throws ServletException { + //在这里,我们可以直接获取Web中的Spring容器-不能重新去new,因为那样就不是同一个容器的了 + ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); + service=ctx.getBean("saveService",ISaveService.class); + System.err.println("service:"+service); + } + public ISaveService getService() { + return service; + } + public void setService(ISaveService service) { + this.service = service; + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + doPost(request, response); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + request.setCharacterEncoding("utf-8");//应该在过滤器中设置编码 + String studName = request.getParameter("studName"); + Stud stud = new Stud(); + stud.setS_name(studName); + + String bookName = request.getParameter("bookName"); + Book book = new Book(); + book.setB_name(bookName); + try { + service.saveStudAndBook(stud, book); + } catch (SQLException e) { + //如果有异常,应该返回到专门的处理异常的页面去,返回用户能够看懂的信息 + e.printStackTrace(); + } + } + +} diff --git a/Spring/mySpringWebDemo/src/cn/hncu/utils/CloseAdvice.java b/Spring/mySpringWebDemo/src/cn/hncu/utils/CloseAdvice.java new file mode 100644 index 0000000..77714ca --- /dev/null +++ b/Spring/mySpringWebDemo/src/cn/hncu/utils/CloseAdvice.java @@ -0,0 +1,46 @@ +package cn.hncu.utils; + +import java.lang.reflect.Method; +import java.sql.Connection; + +import net.sf.cglib.proxy.Callback; +import net.sf.cglib.proxy.Enhancer; +import net.sf.cglib.proxy.MethodProxy; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +public class CloseAdvice implements MethodInterceptor{ + private ThreadLocal t = new ThreadLocal(); + + @Override + public Object invoke(MethodInvocation invocation) throws Throwable { + + Object obj = t.get(); + if(obj==null){ + final Object con = invocation.proceed();//返回原型对象Connection + //通过cglib工具进行动态代理 + Callback callback = new net.sf.cglib.proxy.MethodInterceptor() { + @Override + public Object intercept(Object proxiedObj, Method method, + Object[] args, MethodProxy proxy) throws Throwable { + if(method.getName().equals("close")){ + return null; + } + //con为原型Connection对象 + return method.invoke(con, args); + } + }; + + //obj为cglib工具代理后的Connection对象 + obj=Enhancer.create(Connection.class, callback); + t.set(obj); + } + return obj; + } + + + + + +} diff --git a/Spring/mySpringWebDemo/src/cn/hncu/utils/TxAdvice.java b/Spring/mySpringWebDemo/src/cn/hncu/utils/TxAdvice.java new file mode 100644 index 0000000..13a741c --- /dev/null +++ b/Spring/mySpringWebDemo/src/cn/hncu/utils/TxAdvice.java @@ -0,0 +1,45 @@ +package cn.hncu.utils; + +import java.sql.Connection; + +import javax.sql.DataSource; + +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; + + +//另外一种方法获取Web中的spring容器--实现ApplicationContextAware接口 +public class TxAdvice implements MethodInterceptor,ApplicationContextAware{ + private ApplicationContext ctx =null; + @Override + public void setApplicationContext(ApplicationContext ctx) + throws BeansException { + this.ctx=ctx; + } + + //通知---这个里面需要拿到dataSource,所以需要先拿到Spring的容器 + @Override + public Object invoke(MethodInvocation invocation) throws Throwable { + DataSource dataSource = ctx.getBean("dataSource",DataSource.class); + Connection con = dataSource.getConnection(); + Object res =null; + try { + con.setAutoCommit(false); + //开启一个事务 + res = invocation.proceed();//放行 + con.commit();//提交 + System.out.println("提交一个事务..."); + } catch (Exception e) { + con.rollback(); + System.out.println("事务回滚..."); + }finally{ + con.setAutoCommit(true);//关闭事务 + con.close(); + } + return res; + } + +} diff --git "a/Spring/mySpringWebDemo/\343\200\220\346\241\206\346\236\266\343\200\221[Spring] \345\237\272\344\272\216Spring\346\241\206\346\236\266\347\232\204Web\345\272\224\347\224\250\346\274\224\347\244\272(\351\231\204\345\270\246cglib\345\267\245\345\205\267\350\277\233\350\241\214\345\212\250\346\200\201\344\273\243\347\220\206).html" "b/Spring/mySpringWebDemo/\343\200\220\346\241\206\346\236\266\343\200\221[Spring] \345\237\272\344\272\216Spring\346\241\206\346\236\266\347\232\204Web\345\272\224\347\224\250\346\274\224\347\244\272(\351\231\204\345\270\246cglib\345\267\245\345\205\267\350\277\233\350\241\214\345\212\250\346\200\201\344\273\243\347\220\206).html" new file mode 100644 index 0000000..82abf69 --- /dev/null +++ "b/Spring/mySpringWebDemo/\343\200\220\346\241\206\346\236\266\343\200\221[Spring] \345\237\272\344\272\216Spring\346\241\206\346\236\266\347\232\204Web\345\272\224\347\224\250\346\274\224\347\244\272(\351\231\204\345\270\246cglib\345\267\245\345\205\267\350\277\233\350\241\214\345\212\250\346\200\201\344\273\243\347\220\206).html" @@ -0,0 +1,470 @@ + + + + + +【框架】[Spring] 基于Spring框架的Web应用演示(附带cglib工具进行动态代理) + + + +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ + + +

前言:

+ +

Spring也差不多学了Ioc控制反转和实现AOP技术的两种方式了,分享一个学习Spring,用来入门挺好的例子。

+ +

如果你是刚刚学习Spring,那么此实例应该可以很好的帮助你应用Spring到Web项目中。

+ +

里面的DAO层-提交数据库的事务我并没有使用Spring 的注解功能,而是用spring的AOP来实现的。这样更灵活,其实,框架为我们做的事越多,我们就越受框架的约束。想把功能做灵活,就越难实现。

+ +

只要我们把底层学好,框架的功能我们都能自己写出来的,而且自己写出来的东西,肯定会更熟悉。
+框架是为了降低程序之间的依赖性和耦合性,使重用性达到最高。

+ +

学习框架,我更多的希望自己能学会框架的思想,理解为什么!

+ + + +

首先准备数据库:

+ + + +
create database mydb charset=utf8;
+
+create table stud(
+  s_id varchar(32) primary key,
+  s_name varchar(40)
+);
+
+create table book(
+  b_id int primary key  auto_increment,
+  b_name varchar(40)
+);
+ +

准备好这2个表:

+ +

+ + + +

Jar包少不了:

+ +

+ +

相信学到这一步的朋友应该有了自己的一个配套包了吧,在这里我就不去一 一将包链接写出了。
+如果需要这些包的,在本博客最后我会给出整个项目的链接,请到里面的WEB-INF/lib目录下去下载。

+ + + +

配好web.xml:

+ +

配置web.xml-以使用Spring。

+ + + +
  <context-param>
+        <!-- param的name必须为contextConfigLocation,Spring内部会解析的 -->
+        <param-name>contextConfigLocation</param-name>
+        <!-- contextConfigLocation参数的值,课配置多个,用英文逗号隔开 -->
+        <param-value>
+            classpath:beans.xml,
+            /WEB-INF/conf/applicationContext.xml
+        </param-value>
+  </context-param>
+  <listener>
+        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
+  </listener>
+ +

org.springframework.web.context.ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行Spring实现的方法。

+ +

小知识点:
+容器对于web.xml的加载过程是context-param >> listener >> fileter >> servlet.

+ +

接下来就是写:
+classpath:beans.xml和/WEB-INF/conf/applicationContext.xml这2个xml。
+classpath:代表beans.xml的位置在src(bin)目录下。

+ +

既然需要连接数据库,我们还需要一个配置文件jdbc.properties,声明一些数据库的协议(其实可以在applicationContext.xml中直接配置的,可以不用这个文件)

+ + + +

jdbc.properties:

+ +

+ + + +
#如果是utf-8编码,第一行必须空一行.因为utf-8的文件开头有一个符号
+#在本例中,我用这个配置文件会出现账号密码错误,无法连接数据库,原因未知
+#所以,我在本例是直接配置dataSource的,未用到本文件
+#数据库驱动包
+driver=com.mysql.jdbc.Driver
+#连接数据库的协议--三个"/"代表通过数据库默认端口连接本机的数据库,也可以写成//localhost:3306/
+url=jdbc:mysql:///mydb?characterEncoding=utf-8
+username=root
+pwd=1234
+#其实前面的4个变量名都是自己随便可以取的,因为真正的读取不是在这里
+#真正的读取在applicationContext.xml中
+ +

在applicationContext.xml配置如下就可以拿到数据库连接了。

+ + + +
    <!-- 使用jdbc.properties配置文件,就要写下面这句 -->
+<!--    <context:property-placeholder location="WEB-INF/conf/jdbc.properties"/> -->
+    <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
+        <!-- 使用jdbc.properties配置文件,类似如下配置 -->
+<!--        <property name="driverClass" value="${driver}"></property> -->
+        <property name="driverClass" value="com.mysql.jdbc.Driver"></property> 
+        <property name="url" value="jdbc:mysql:///mydb?characterEncoding=UTF-8"></property> 
+        <property name="username" value="root"></property> 
+        <property name="password" value="1234"></property> 
+    </bean>
+ + + +

beans.xml

+ +

写好DAO,service,servlet层的架构-方法和变量:
+在beans.xml中配置好DAO,service的初始化bean,初始化属性。
+而由于我们在web.xml配置了servlet,是Tomcat帮我们new-servlet的,所以,但是我们需要在servlet中需要访问service的对象,这个时候,我们就可以利用servlet的生命周期,在init方法中,给service对象赋值.

+ + + +
<?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:tx="http://www.springframework.org/schema/tx"
+        xsi:schemaLocation="http://www.springframework.org/schema/beans%20http://www.springframework.org/schema/beans/spring-beans-4.3.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/context%20http://www.springframework.org/schema/context/spring-context-4.3.xsd+%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://www.springframework.org/schema/tx%20http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
+    <bean id="studDao" class="cn.hncu.stud.dao.StudDaoJdbc">
+       <!--ref="dataSource",引用applicationContext.xml中的dataSource  -->
+       <property name="dataSource" ref="dataSource"></property>
+    </bean>
+    <bean id="bookDao" class="cn.hncu.stud.dao.BookDaoJdbc">
+       <!--ref="dataSource",引用applicationContext.xml中的dataSource  -->
+       <property name="dataSource" ref="dataSource"></property>
+    </bean>
+
+    <bean id="saveService" class="cn.hncu.stud.service.StudServiceImpl">
+        <property name="studDao" ref="studDao"></property>
+        <property name="bookDao" ref="bookDao"></property>
+    </bean>
+</beans>
+
+ + + +

servlet中加入此方法,实现service的初始化:

+ + + +
@Override
+    public void init() throws ServletException {
+        //在这里,我们可以直接获取Web中的Spring容器-不能重新去new,因为那样就不是同一个容器的了
+        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
+        service=ctx.getBean(ISaveService.class);
+    }
+ + + +

TxAdvice-AOP通知

+ + + +
package cn.hncu.utils;
+
+import java.sql.Connection;
+
+import javax.sql.DataSource;
+
+import org.aopalliance.intercept.MethodInterceptor;
+import org.aopalliance.intercept.MethodInvocation;
+import org.springframework.beans.BeansException;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+
+//另外一种方法获取Web中的spring容器--实现ApplicationContextAware接口
+public class TxAdvice implements MethodInterceptor,ApplicationContextAware{
+    private ApplicationContext ctx =null;
+
+    @Override
+    public void setApplicationContext(ApplicationContext ctx)
+            throws BeansException {
+        this.ctx=ctx;
+    }
+
+    //通知---这个里面需要拿到dataSource,所以需要先拿到Spring的容器
+    @Override
+    public Object invoke(MethodInvocation invocation) throws Throwable {
+        DataSource dataSource = ctx.getBean(DataSource.class);
+
+        Connection con = dataSource.getConnection();
+        Object res =null;
+        try {
+            con.setAutoCommit(false);
+            //开启一个事务
+            res = invocation.proceed();//放行
+            con.commit();//提交
+            System.out.println("提交一个事务...");
+        } catch (Exception e) {
+            con.rollback();
+            System.out.println("事务回滚...");
+        }finally{
+            con.setAutoCommit(true);//关闭事务
+            con.close();
+        }
+        return res;
+    }
+
+
+}
+
+ + + +

事务

+ +

如果只代理到上面这里,写con.close方法其实会出问题的。
+当然,本例很简单,servlet只请求了一个service中的一个方法,这样写没什么问题,
+但是,假如我有多个service和一个service有多个方法,需要被一个用户请求servlet时同时调用时,这个连接就不能被关闭了。
+因为Spring容器的事务机制的实质是对传统JDBC的封装,也即是Spring事务管理无论是对单数据库实例还是分布式数据库实例,要实现事务管理,那么必须保证在一个事务过程获得Connetion对象是同一个。

+ +

假如是servlet调用多个service或service中多个方法,需要实现的是同一个事务,我们可以:在service中写一个综合方法,在其中调用其它方法,然后给综合方法设置代理,因为这个综合方法在这里就是一个业务
+,多个service,原理一样。

+ + + +

AOP拦截getConnection()方法,cglib工具进行动态代理Connection

+ +

然后再拦截Connection的close方法!

+ + + +
package cn.hncu.utils;
+
+import java.lang.reflect.Method;
+import java.sql.Connection;
+
+import net.sf.cglib.proxy.Callback;
+import net.sf.cglib.proxy.Enhancer;
+import net.sf.cglib.proxy.MethodProxy;
+
+import org.aopalliance.intercept.MethodInterceptor;
+import org.aopalliance.intercept.MethodInvocation;
+
+public class CloseAdvice implements MethodInterceptor{
+    private ThreadLocal<Object> t = new ThreadLocal<Object>();
+
+    @Override
+    public Object invoke(MethodInvocation invocation) throws Throwable {
+
+        Object obj = t.get();
+        if(obj==null){
+
+            final Object con = invocation.proceed();//返回原型对象Connection
+
+            //通过cglib工具进行动态代理
+            Callback callback = new net.sf.cglib.proxy.MethodInterceptor() {
+
+                @Override
+                public Object intercept(Object proxiedObj, Method method,
+                        Object[] args, MethodProxy proxy) throws Throwable {
+                    if(method.getName().equals("close")){
+                        return null;
+                    }
+                    //con为原型Connection对象
+                    return method.invoke(con, args);
+                }
+            };
+
+            //obj为cglib工具代理后的Connection对象
+            obj=Enhancer.create(Connection.class, callback);
+            t.set(obj);
+        }
+        return obj;
+    }
+
+
+
+
+
+}
+
+ + + +

在applicationContext.xml中配置拦截getConnection()

+ + + +
<bean id="conClose" class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor">
+       <property name="expression" value="execution( * *..*.*.getConnection() )"></property>
+       <property name="advice">
+            <bean id="advice" class="cn.hncu.utils.CloseAdvice"></bean>
+       </property>
+    </bean>
+ +

接下来就是要用到AOP了,拦截事务。
+拦截service层的。

+ + + +

拦截事务的切面配置:

+ + + +
<!-- 自动代理 -->
+    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"></bean>
+    <!-- 事务  切面=切点+通知 -->
+    <bean id="tx" class="org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor">
+        <!-- 拦截cn.hncu包下的,方法名最后为Service的任意返回值任意参数的方法 -->
+        <property name="expression" value="execution (* cn.hncu..*Service.*(..) )">
+        </property>
+        <property name="advice">
+            <bean class="cn.hncu.utils.TxAdvice"></bean>
+        </property>
+    </bean>
+ + + +

DAO层的实现类代码:

+ + + +

stud的实现类:

+ + + +
package cn.hncu.stud.dao;
+
+import java.sql.SQLException;
+import java.util.UUID;
+
+import javax.sql.DataSource;
+
+import org.apache.commons.dbutils.QueryRunner;
+
+import cn.hncu.stud.domain.Book;
+import cn.hncu.stud.domain.Stud;
+
+public class StudDaoJdbc implements StudDAO{
+    private DataSource dataSource = null;//依赖注入
+    public DataSource getDataSource() {
+        return dataSource;
+    }
+
+    public void setDataSource(DataSource dataSource) {
+        this.dataSource = dataSource;
+    }
+
+    @Override
+    public void saveStud(Stud stud) throws SQLException {
+        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
+        stud.setS_id(uuid);
+        QueryRunner run = new QueryRunner(dataSource);
+        run.update("insert into stud(s_id,s_name) values(?,?)", stud.getS_id(),stud.getS_name());
+    }
+}
+
+ + + +

book的实现类

+ + + +
package cn.hncu.stud.dao;
+
+import java.sql.SQLException;
+
+import javax.sql.DataSource;
+
+import org.apache.commons.dbutils.QueryRunner;
+
+import cn.hncu.stud.domain.Book;
+
+public class BookDaoJdbc implements BookDAO{
+    private DataSource dataSource = null;//依赖注入
+
+    public DataSource getDataSource() {
+        return dataSource;
+    }
+
+    public void setDataSource(DataSource dataSource) {
+        this.dataSource = dataSource;
+    }
+
+    @Override
+    public void saveBook(Book book) throws SQLException {
+        QueryRunner run = new QueryRunner(dataSource);
+        run.update("insert into book(b_name) values(?)", book.getB_name());
+    }
+
+}
+
+ + + +

测试:

+ +

打开页面输入:

+ +

+ +

点按钮提交:

+ +


+service:cn.hncu.stud.service.SaveServiceImpl@4adeee3d这个输出是我在servlet中测试一个错误的时候的输出。

+ +

再看数据库的数据:

+ +

+ +

+ +

然后,我们来测试下,事务回滚情况:

+ +

因为service层是:

+ + + +
@Override
+    public void saveStudAndBook(Stud stud, Book book) throws SQLException {
+        studDao.saveStud(stud);
+        bookDao.saveBook(book);
+    }
+ +

后调用bookDao的,所以,我们让saveBook挂了,改一下saveBook的方法中sql语句为:
+

+ +

这样,后面Book的存储肯定是出问题的。

+ +

再来测试:
+

+ +

点添加。

+ +

+ +

可以看到事务回滚了,但是看这里没用,我们去看下stud和book表有没有存储。当然book表肯定是不会被存储的,去看stud表就可以了:

+ +

+ +

可以看到,李四这个用户并没有被保存,证明事务起作用了。

+ +

此实例适合初学Spring者学习哦。

+ +

本文章由[谙忆]编写, 所有权利保留。

+ +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ \ No newline at end of file diff --git a/Spring/spring-framework-3.1.1.RELEASE.zip b/Spring/spring-framework-3.1.1.RELEASE.zip new file mode 100644 index 0000000..0e69a3e Binary files /dev/null and b/Spring/spring-framework-3.1.1.RELEASE.zip differ diff --git a/Tomcat7.0/apache-tomcat-7.0-doc.zip b/Tomcat7.0/apache-tomcat-7.0-doc.zip new file mode 100644 index 0000000..d49e4aa Binary files /dev/null and b/Tomcat7.0/apache-tomcat-7.0-doc.zip differ diff --git a/Tomcat7.0/apache-tomcat-7.0.30-windows-x64.zip b/Tomcat7.0/apache-tomcat-7.0.30-windows-x64.zip new file mode 100644 index 0000000..67b62d0 Binary files /dev/null and b/Tomcat7.0/apache-tomcat-7.0.30-windows-x64.zip differ diff --git a/Tomcat7.0/apache-tomcat-7.0.30-windows-x86.zip b/Tomcat7.0/apache-tomcat-7.0.30-windows-x86.zip new file mode 100644 index 0000000..0a9aec2 Binary files /dev/null and b/Tomcat7.0/apache-tomcat-7.0.30-windows-x86.zip differ diff --git a/Tomcat7.0/apache-tomcat-7.0.57-src-x64.zip b/Tomcat7.0/apache-tomcat-7.0.57-src-x64.zip new file mode 100644 index 0000000..0e1e63b Binary files /dev/null and b/Tomcat7.0/apache-tomcat-7.0.57-src-x64.zip differ diff --git a/UltraISO/README.md b/UltraISO/README.md new file mode 100644 index 0000000..feaa2f5 --- /dev/null +++ b/UltraISO/README.md @@ -0,0 +1,49 @@ +UltraISO软碟通是一款光盘映像ISO文件编辑制作工具,它可以图形化地从光盘、硬盘制作和编辑ISO文件。 + +UltraISO是一款功能强大而又方便实用的光盘映像文件制作/编辑/格式转换工具,它可以直接编辑光盘映像和从映像中直接提取文件,也可以从CD-ROM制作光盘映像或者将硬盘上的文件制作成ISO文件。同时,你也可以处理ISO文件的启动信息,从而制作可引导光盘。本特别版软件具有如下特点: + + + 本软件是UltraISOV9.6.5.3237简体中文版安装版,注意,是真正的简体中文版,而非多国语言版精简而来,所有功能均可用,使用上无任何限制,试用了这么多版本,还是安装版的最完美,单文件版会出现不能关联ISO或者关联后打开ISO显示软件本身还要再选择你的ISO文件的问题; + +简体中文版专用: + 注册名:Guanjiu + + 注册码:A06C-83A7-701D-6CFC + + + 多国语言版专用: + + 注册名: Home + + 注册码: 4BA9-0D54-214A-C938 + + 新版本可以检测设置Nero 12以及imgburn的刻录软件,修复了了对闪迪和blade系列优盘写盘的问题。 +更新支持pci-e sd/mmc读卡器,支持从更多的ISO镜像文件制作U盘启动盘,可以编辑win8.1 64位ISO映像文件。 + + + +UltraISO PE功能特点: +1、从CD-ROM制作光盘的映像文件。 +2、将硬盘、光盘、网络磁盘文件制作成ISO文件。 +3、从ISO文件中提取文件或文件夹。 +4、编辑各种ISO文件(如Nero Burning ROM、Easy CD Creator、Clone CD 制作的光盘映像文件)。 +5、制作可启动ISO文件。 +UltraISO V 9.6.5.3237 (2015-7-21)更新日志: ++) 支持 Windows 10 ++) 改进了写入磁盘映像功能,并可以从更多的ISO制作可启动U盘, 包括 Debian 8,Ubuntu 15.04,SBAV 5.14 和 gparted 0.22 等 ++) 在制作音乐光盘时支持 WMA 媒体文件重新采样 ++) 支持加载 NTFS/exFAT 磁盘上的深度隐藏分区(bootpart) ++) 在制作映像或刻录完成后自动弹出光盘 ++) 可以打开并提取 Android 启动/恢复映像中的文件 +*) 修正了某些 AHCI 接口的刻录机刻录光盘时报错的问题 +*) 一些小的改进和错误修正 + + + + + + + + + + diff --git a/UltraISO/UltraISO.zip b/UltraISO/UltraISO.zip new file mode 100644 index 0000000..a291aa2 Binary files /dev/null and b/UltraISO/UltraISO.zip differ diff --git a/addQQFriend.rar b/addQQFriend.rar new file mode 100644 index 0000000..d290a7a Binary files /dev/null and b/addQQFriend.rar differ diff --git a/commit-to-master.sh b/commit-to-master.sh new file mode 100644 index 0000000..ccb8ced --- /dev/null +++ b/commit-to-master.sh @@ -0,0 +1,15 @@ +#!/bin/sh +git checkout master +git add . +echo 请输入本次提交的注释 如输入空白字符则使用"commit" +read -t 600 var +#会读取一行到var变量 +if [ -z $var ];then +echo 未输入注释 空白注释 +git commit -am "commit" +else +echo commit is $var +git commit -am "$var" +fi +git push origin master +sleep 15 \ No newline at end of file diff --git a/druid_spring_config/.idea/artifacts/druid_spring_config_war_exploded.xml b/druid_spring_config/.idea/artifacts/druid_spring_config_war_exploded.xml new file mode 100644 index 0000000..b09dce0 --- /dev/null +++ b/druid_spring_config/.idea/artifacts/druid_spring_config_war_exploded.xml @@ -0,0 +1,44 @@ + + + $PROJECT_DIR$/out/artifacts/druid_spring_config_war_exploded + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/compiler.xml b/druid_spring_config/.idea/compiler.xml new file mode 100644 index 0000000..532ec8f --- /dev/null +++ b/druid_spring_config/.idea/compiler.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__aopalliance_aopalliance_1_0.xml b/druid_spring_config/.idea/libraries/Maven__aopalliance_aopalliance_1_0.xml new file mode 100644 index 0000000..30ff5cb --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__aopalliance_aopalliance_1_0.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__com_alibaba_druid_1_1_0.xml b/druid_spring_config/.idea/libraries/Maven__com_alibaba_druid_1_1_0.xml new file mode 100644 index 0000000..b349885 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__com_alibaba_druid_1_1_0.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_annotations_2_8_5.xml b/druid_spring_config/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_annotations_2_8_5.xml new file mode 100644 index 0000000..6246e81 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_annotations_2_8_5.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_core_2_8_5.xml b/druid_spring_config/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_core_2_8_5.xml new file mode 100644 index 0000000..1c8e0ca --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_core_2_8_5.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_databind_2_8_5.xml b/druid_spring_config/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_databind_2_8_5.xml new file mode 100644 index 0000000..75e6312 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_databind_2_8_5.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__commons_fileupload_commons_fileupload_1_3_2.xml b/druid_spring_config/.idea/libraries/Maven__commons_fileupload_commons_fileupload_1_3_2.xml new file mode 100644 index 0000000..f180407 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__commons_fileupload_commons_fileupload_1_3_2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__commons_io_commons_io_2_2.xml b/druid_spring_config/.idea/libraries/Maven__commons_io_commons_io_2_2.xml new file mode 100644 index 0000000..f8084ec --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__commons_io_commons_io_2_2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__commons_logging_commons_logging_1_2.xml b/druid_spring_config/.idea/libraries/Maven__commons_logging_commons_logging_1_2.xml new file mode 100644 index 0000000..eab40b3 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__commons_logging_commons_logging_1_2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__javax_servlet_jsp_jsp_api_2_2_1_b03.xml b/druid_spring_config/.idea/libraries/Maven__javax_servlet_jsp_jsp_api_2_2_1_b03.xml new file mode 100644 index 0000000..7e6f6c3 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__javax_servlet_jsp_jsp_api_2_2_1_b03.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__javax_servlet_jstl_1_2.xml b/druid_spring_config/.idea/libraries/Maven__javax_servlet_jstl_1_2.xml new file mode 100644 index 0000000..f329893 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__javax_servlet_jstl_1_2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__javax_servlet_servlet_api_3_0_alpha_1.xml b/druid_spring_config/.idea/libraries/Maven__javax_servlet_servlet_api_3_0_alpha_1.xml new file mode 100644 index 0000000..4783258 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__javax_servlet_servlet_api_3_0_alpha_1.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__log4j_log4j_1_2_12.xml b/druid_spring_config/.idea/libraries/Maven__log4j_log4j_1_2_12.xml new file mode 100644 index 0000000..f398ab4 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__log4j_log4j_1_2_12.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__mysql_mysql_connector_java_5_1_36.xml b/druid_spring_config/.idea/libraries/Maven__mysql_mysql_connector_java_5_1_36.xml new file mode 100644 index 0000000..a298445 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__mysql_mysql_connector_java_5_1_36.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_aspectj_aspectjrt_1_7_1.xml b/druid_spring_config/.idea/libraries/Maven__org_aspectj_aspectjrt_1_7_1.xml new file mode 100644 index 0000000..e2462b2 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_aspectj_aspectjrt_1_7_1.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_aspectj_aspectjweaver_1_7_1.xml b/druid_spring_config/.idea/libraries/Maven__org_aspectj_aspectjweaver_1_7_1.xml new file mode 100644 index 0000000..5a5a22b --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_aspectj_aspectjweaver_1_7_1.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_codehaus_jackson_jackson_core_asl_1_9_13.xml b/druid_spring_config/.idea/libraries/Maven__org_codehaus_jackson_jackson_core_asl_1_9_13.xml new file mode 100644 index 0000000..98eb549 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_codehaus_jackson_jackson_core_asl_1_9_13.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_codehaus_jackson_jackson_mapper_asl_1_9_13.xml b/druid_spring_config/.idea/libraries/Maven__org_codehaus_jackson_jackson_mapper_asl_1_9_13.xml new file mode 100644 index 0000000..77f3bad --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_codehaus_jackson_jackson_mapper_asl_1_9_13.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_mybatis_mybatis_3_3_0.xml b/druid_spring_config/.idea/libraries/Maven__org_mybatis_mybatis_3_3_0.xml new file mode 100644 index 0000000..86720b3 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_mybatis_mybatis_3_3_0.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_mybatis_mybatis_spring_1_2_2.xml b/druid_spring_config/.idea/libraries/Maven__org_mybatis_mybatis_spring_1_2_2.xml new file mode 100644 index 0000000..8828a9a --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_mybatis_mybatis_spring_1_2_2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_projectlombok_lombok_1_16_20.xml b/druid_spring_config/.idea/libraries/Maven__org_projectlombok_lombok_1_16_20.xml new file mode 100644 index 0000000..bcbf2ac --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_projectlombok_lombok_1_16_20.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_aop_4_2_3_RELEASE.xml b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_aop_4_2_3_RELEASE.xml new file mode 100644 index 0000000..7ef1712 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_aop_4_2_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_beans_4_2_3_RELEASE.xml b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_beans_4_2_3_RELEASE.xml new file mode 100644 index 0000000..ca546e9 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_beans_4_2_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_context_4_2_3_RELEASE.xml b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_context_4_2_3_RELEASE.xml new file mode 100644 index 0000000..2963b01 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_context_4_2_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_context_support_4_2_3_RELEASE.xml b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_context_support_4_2_3_RELEASE.xml new file mode 100644 index 0000000..cf792ac --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_context_support_4_2_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_core_4_2_3_RELEASE.xml b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_core_4_2_3_RELEASE.xml new file mode 100644 index 0000000..42a85bb --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_core_4_2_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_expression_4_2_3_RELEASE.xml b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_expression_4_2_3_RELEASE.xml new file mode 100644 index 0000000..2b109cd --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_expression_4_2_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_jdbc_4_2_3_RELEASE.xml b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_jdbc_4_2_3_RELEASE.xml new file mode 100644 index 0000000..96a6e90 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_jdbc_4_2_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_tx_4_2_3_RELEASE.xml b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_tx_4_2_3_RELEASE.xml new file mode 100644 index 0000000..b7247fc --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_tx_4_2_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_web_4_2_3_RELEASE.xml b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_web_4_2_3_RELEASE.xml new file mode 100644 index 0000000..6362302 --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_web_4_2_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_webmvc_4_2_3_RELEASE.xml b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_webmvc_4_2_3_RELEASE.xml new file mode 100644 index 0000000..6ae47bc --- /dev/null +++ b/druid_spring_config/.idea/libraries/Maven__org_springframework_spring_webmvc_4_2_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/misc.xml b/druid_spring_config/.idea/misc.xml new file mode 100644 index 0000000..691fc66 --- /dev/null +++ b/druid_spring_config/.idea/misc.xml @@ -0,0 +1,13 @@ + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/modules.xml b/druid_spring_config/.idea/modules.xml new file mode 100644 index 0000000..1436a16 --- /dev/null +++ b/druid_spring_config/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/.idea/workspace.xml b/druid_spring_config/.idea/workspace.xml new file mode 100644 index 0000000..41cf02e --- /dev/null +++ b/druid_spring_config/.idea/workspace.xml @@ -0,0 +1,963 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + mappingJacksonHttpMessageConverter + systemId + sqlSessionFactory + jackson + druid + dataSource + + + + + + + + + + + + true + DEFINITION_ORDER + + + + + + + + + + + + + + + + Android + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + select + + from user + where id = #{id,jdbcType=INTEGER} + + + delete from user + where id = #{id,jdbcType=INTEGER} + + + insert into user (id, name) + values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}) + + + insert into user + + + id, + + + name, + + + + + #{id,jdbcType=INTEGER}, + + + #{name,jdbcType=VARCHAR}, + + + + + update user + + + name = #{name,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=INTEGER} + + + update user + set name = #{name,jdbcType=VARCHAR} + where id = #{id,jdbcType=INTEGER} + + \ No newline at end of file diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/com/uifuture/user/service/UserService.class b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/com/uifuture/user/service/UserService.class new file mode 100644 index 0000000..bc1200d Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/com/uifuture/user/service/UserService.class differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/com/uifuture/user/service/impl/UserServiceImpl.class b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/com/uifuture/user/service/impl/UserServiceImpl.class new file mode 100644 index 0000000..af1a4ef Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/com/uifuture/user/service/impl/UserServiceImpl.class differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/config.properties b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/config.properties new file mode 100644 index 0000000..a13cc2e --- /dev/null +++ b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/config.properties @@ -0,0 +1,14 @@ + +# ������sql���Լ���־��� +druid_filters=stat,wall,log4j + +driverClassName=com.mysql.jdbc.Driver +jdbc_url=jdbc:mysql://localhost:3306/druid_spring_config?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull +jdbc_username=root +jdbc_password=1234 +#��ʼ�����Ӵ�С +jdbc_init=50 +#���ӳ���С���� +jdbc_minIdle=20 +#��ȡ�������ȴ�ʱ�� ��λΪ���� +jdbc_maxActive=60000 \ No newline at end of file diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/log4j.properties b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/log4j.properties new file mode 100644 index 0000000..0a3a35f --- /dev/null +++ b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/log4j.properties @@ -0,0 +1,69 @@ +#####配置根元素 +#调试模式,写成DEBUG ---设置日志级别-存储DEBUG以及以上级别的记录 +#log4j.rootLogger=DEBUG,console,file,error,druid +log4j.rootLogger=INFO,console,file,error,druid +#log4j.rootLogger=ERROR,console,file,error +#生产级项目,写成INFO就可以了 +#INFO级别比DEBUG级别高 ---console,file,error都是自己写的-名称自己定 + +####以下配置输出到控制台的配置#### +log4j.appender.console=org.apache.log4j.ConsoleAppender +log4j.appender.console.layout=org.apache.log4j.PatternLayout +log4j.appender.console.Target=System.out +log4j.appender.console.layout.ConversionPattern=[%p] %d{yyyy-MM-dd HH\:mm\:ss} [%l] -> %m [%t] [chx]%n + +### 输出到日志文件 ### +log4j.appender.file=org.apache.log4j.RollingFileAppender +#。RollingFileAppender按log文件最大长度限度生成新文件 +#以下是具体的目录 +log4j.appender.file.File=${catalina.home}/logs/druid_spring_config/info.log +#每个文件的最大大小 +log4j.appender.file.MaxFileSize=5MB +#最多可以是多少个文件 +log4j.appender.file.MaxBackupIndex=30 +## 输出INFO级别以上的日志 --Threshold是个全局的过滤器,它将把低于所设置的INFO的信息过滤不显示出来。 +#log4j.appender.file.Threshold=INFO +log4j.appender.file.Threshold=DEBUG +#服务器启动日志是追加, false:服务器启动后会生成日志文件把老的覆盖掉 +log4j.appender.file.Append = true +#信息的布局格式-按指定的格式打出 +log4j.appender.file.layout=org.apache.log4j.PatternLayout +#具体的布局格式 - %d为时间 +#log4j.appender.file.layout.ConversionPattern=%d %p [%c] %m %l %n +log4j.appender.file.layout.ConversionPattern=[%p] %d{yyyy-MM-dd HH\:mm\:ss} [%l] -> %m [%t] [chx]%n +#设置输出日志文件编码(可以控制乱码情况) +log4j.appender.file.encoding=UTF-8 + + +### 保存异常信息到单独文件 ### +log4j.appender.error = org.apache.log4j.DailyRollingFileAppender +#DailyRollingFileAppender按日期生成新文件 +## 异常日志文件名 +log4j.appender.error.File =${catalina.home}/logs/druid_spring_config/error.log +#这个路径是Tomcat的路径 +#在每天产生的文件后面追加 +log4j.appender.error.DatePattern = '.'yyyyMMdd +#服务器启动日志是追加,false:服务器启动后会生成日志文件把老的覆盖掉 +log4j.appender.error.Append = true +## 只输出ERROR级别以上的日志!!! +log4j.appender.error.Threshold = error +log4j.appender.error.layout = org.apache.log4j.PatternLayout +log4j.appender.error.layout.ConversionPattern =[%p] %d{yyyy-MM-dd HH\:mm\:ss} [%l] -> %m [%t] [chx]%n +#设置输出日志文件编码(可以控制乱码情况) +log4j.appender.error.encoding=UTF-8 + + +# Druid 慢查询记录日志 +log4j.logger.druid.sql=WARN,druid +log4j.logger.druid.sql.DataSource=WARN,druid +log4j.logger.druid.sql.Connection=WARN,druid +log4j.logger.druid.sql.Statement=WARN,druid + +log4j.appender.druid=org.apache.log4j.DailyRollingFileAppender +log4j.appender.druid.layout=org.apache.log4j.PatternLayout +log4j.appender.druid.layout.ConversionPattern= [%p] %d{yyyy-MM-dd HH\:mm\:ss} [%l] -> %m [%t] [chx]%n +log4j.appender.druid.datePattern='.'yyyy-MM-dd +log4j.appender.druid.Threshold = WARN +log4j.appender.druid.append=true +log4j.appender.druid.File=${catalina.home}/logs/druid_spring_config/druid-slow-sql.log +# ${catalina.home}是在tomcat的目录下 \ No newline at end of file diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/spring-mybatis.xml b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/spring-mybatis.xml new file mode 100644 index 0000000..96b9d99 --- /dev/null +++ b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/spring-mybatis.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/spring.xml b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/spring.xml new file mode 100644 index 0000000..802e290 --- /dev/null +++ b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/classes/spring.xml @@ -0,0 +1,158 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + classpath*:com/uifuture/*/mapping/*.xml + + + + + + + + + + + + + + + + + + + + + + + + + com.uifuture.user.service.* + com.uifuture.user.dao.* + + + + + + + + + + + + + + + + + + + + + + text/html;charset=UTF-8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + UTF-8 + + + 32505856 + + + 4096 + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/aopalliance-1.0.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/aopalliance-1.0.jar new file mode 100644 index 0000000..578b1a0 Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/aopalliance-1.0.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/aspectjrt-1.7.1.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/aspectjrt-1.7.1.jar new file mode 100644 index 0000000..351409c Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/aspectjrt-1.7.1.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/aspectjweaver-1.7.1.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/aspectjweaver-1.7.1.jar new file mode 100644 index 0000000..9949bc5 Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/aspectjweaver-1.7.1.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/commons-fileupload-1.3.2.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/commons-fileupload-1.3.2.jar new file mode 100644 index 0000000..4975590 Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/commons-fileupload-1.3.2.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/commons-io-2.2.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/commons-io-2.2.jar new file mode 100644 index 0000000..84ca565 Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/commons-io-2.2.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/commons-logging-1.2.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/commons-logging-1.2.jar new file mode 100644 index 0000000..93a3b9f Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/commons-logging-1.2.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/druid-1.1.0.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/druid-1.1.0.jar new file mode 100644 index 0000000..6c329ac Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/druid-1.1.0.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jackson-annotations-2.8.5.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jackson-annotations-2.8.5.jar new file mode 100644 index 0000000..76567bf Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jackson-annotations-2.8.5.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jackson-core-2.8.5.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jackson-core-2.8.5.jar new file mode 100644 index 0000000..05e1be2 Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jackson-core-2.8.5.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jackson-core-asl-1.9.13.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jackson-core-asl-1.9.13.jar new file mode 100644 index 0000000..bb4fe1d Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jackson-core-asl-1.9.13.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jackson-databind-2.8.5.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jackson-databind-2.8.5.jar new file mode 100644 index 0000000..2794824 Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jackson-databind-2.8.5.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jackson-mapper-asl-1.9.13.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jackson-mapper-asl-1.9.13.jar new file mode 100644 index 0000000..0f2073f Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jackson-mapper-asl-1.9.13.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jconsole.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jconsole.jar new file mode 100644 index 0000000..1ec218d Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/jconsole.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/log4j-1.2.12.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/log4j-1.2.12.jar new file mode 100644 index 0000000..9b5a720 Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/log4j-1.2.12.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/lombok-1.16.20.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/lombok-1.16.20.jar new file mode 100644 index 0000000..1728da7 Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/lombok-1.16.20.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/mybatis-3.3.0.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/mybatis-3.3.0.jar new file mode 100644 index 0000000..1cc5f4e Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/mybatis-3.3.0.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/mybatis-spring-1.2.2.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/mybatis-spring-1.2.2.jar new file mode 100644 index 0000000..63a226f Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/mybatis-spring-1.2.2.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/mysql-connector-java-5.1.36.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/mysql-connector-java-5.1.36.jar new file mode 100644 index 0000000..a839c3d Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/mysql-connector-java-5.1.36.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-aop-4.2.3.RELEASE.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-aop-4.2.3.RELEASE.jar new file mode 100644 index 0000000..99e8d0b Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-aop-4.2.3.RELEASE.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-beans-4.2.3.RELEASE.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-beans-4.2.3.RELEASE.jar new file mode 100644 index 0000000..801c67b Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-beans-4.2.3.RELEASE.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-context-4.2.3.RELEASE.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-context-4.2.3.RELEASE.jar new file mode 100644 index 0000000..3dd244e Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-context-4.2.3.RELEASE.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-context-support-4.2.3.RELEASE.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-context-support-4.2.3.RELEASE.jar new file mode 100644 index 0000000..1bea51b Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-context-support-4.2.3.RELEASE.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-core-4.2.3.RELEASE.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-core-4.2.3.RELEASE.jar new file mode 100644 index 0000000..c38bc9a Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-core-4.2.3.RELEASE.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-expression-4.2.3.RELEASE.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-expression-4.2.3.RELEASE.jar new file mode 100644 index 0000000..54baeb3 Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-expression-4.2.3.RELEASE.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-jdbc-4.2.3.RELEASE.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-jdbc-4.2.3.RELEASE.jar new file mode 100644 index 0000000..fe18aa2 Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-jdbc-4.2.3.RELEASE.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-tx-4.2.3.RELEASE.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-tx-4.2.3.RELEASE.jar new file mode 100644 index 0000000..ec2ee7d Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-tx-4.2.3.RELEASE.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-web-4.2.3.RELEASE.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-web-4.2.3.RELEASE.jar new file mode 100644 index 0000000..f708763 Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-web-4.2.3.RELEASE.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-webmvc-4.2.3.RELEASE.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-webmvc-4.2.3.RELEASE.jar new file mode 100644 index 0000000..69b7d18 Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/spring-webmvc-4.2.3.RELEASE.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/tools.jar b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/tools.jar new file mode 100644 index 0000000..27e7bee Binary files /dev/null and b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/lib/tools.jar differ diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/views/index.jsp b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/views/index.jsp new file mode 100644 index 0000000..8ed39f0 --- /dev/null +++ b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/views/index.jsp @@ -0,0 +1,24 @@ +<%-- + Created by IntelliJ IDEA. + User: 陈浩翔 + Date: 2018/02/06 + Time: 下午 8:19 + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + + + druid配置 + + + + + + + +

druid配置

+ + + diff --git a/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/web.xml b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/web.xml new file mode 100644 index 0000000..90840fe --- /dev/null +++ b/druid_spring_config/out/artifacts/druid_spring_config_war_exploded/WEB-INF/web.xml @@ -0,0 +1,117 @@ + + UIFuture + + contextConfigLocation + classpath:spring.xml,classpath:spring-mybatis.xml + + + 字符集过滤器 + encodingFilter + org.springframework.web.filter.CharacterEncodingFilter + + 字符集编码 + encoding + UTF-8 + + + + encodingFilter + /* + + + + + DruidWebStatFilter + com.alibaba.druid.support.http.WebStatFilter + + exclusions + + *.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/* + + + profileEnable + true + + + + DruidWebStatFilter + /* + + + + + + spring监听器-上下文监听器 + org.springframework.web.context.ContextLoaderListener + + + + + org.springframework.web.context.request.RequestContextListener + + + + + org.springframework.web.util.IntrospectorCleanupListener + + + + + spring mvc servlet + springMvc + org.springframework.web.servlet.DispatcherServlet + + spring mvc 配置文件 + contextConfigLocation + classpath:spring.xml + + 1 + + + + + + DruidStatView + com.alibaba.druid.support.http.StatViewServlet + + + + + + + + + loginUsername + root + + + + loginPassword + chenhaoxiang + + + + DruidStatView + /druid/* + + + + + index + + + + springMvc + / + + + + + 30 + + + \ No newline at end of file diff --git a/druid_spring_config/pom.xml b/druid_spring_config/pom.xml new file mode 100644 index 0000000..91ddb3f --- /dev/null +++ b/druid_spring_config/pom.xml @@ -0,0 +1,205 @@ + + + 4.0.0 + + com.uifuture + druid_spring_config + 1.0-SNAPSHOT + + + 1.7 + + 4.2.3.RELEASE + + 3.3.0 + + 1.2.2 + + 5.1.36 + + 4.12 + 1.7.1 + 1.9.13 + + + + + + org.springframework + spring-core + ${spring-framework.version} + + + + org.springframework + spring-context + ${spring-framework.version} + + + org.springframework + spring-context-support + ${spring-framework.version} + + + + + org.springframework + spring-jdbc + ${spring-framework.version} + + + + org.springframework + spring-webmvc + ${spring-framework.version} + + + + org.mybatis + mybatis + ${mybatis.version} + + + + org.mybatis + mybatis-spring + ${mybatis-spring.version} + + + + mysql + mysql-connector-java + ${mysql.version} + runtime + + + + org.codehaus.jackson + jackson-mapper-asl + ${jackson-mapper-asl.version} + + + org.codehaus.jackson + jackson-core-asl + ${jackson-mapper-asl.version} + + + + + + javax.servlet + servlet-api + 3.0-alpha-1 + + + + javax.servlet + jstl + 1.2 + + + javax.servlet.jsp + jsp-api + 2.2.1-b03 + + + + + com.alibaba + druid + 1.1.0 + + + + org.springframework + spring-aop + ${spring-framework.version} + + + + + org.aspectj + aspectjrt + ${aspectjweaver.version} + + + + org.aspectj + aspectjweaver + ${aspectjweaver.version} + + + + log4j + log4j + 1.2.12 + + + + + com.fasterxml.jackson.core + jackson-core + 2.8.5 + + + com.fasterxml.jackson.core + jackson-annotations + 2.8.5 + + + com.fasterxml.jackson.core + jackson-databind + 2.8.5 + + + + + commons-fileupload + commons-fileupload + 1.3.2 + + + + + org.projectlombok + lombok + 1.16.20 + + + + + + + + + + + ${basedir}/src/main/java + + **/*.properties + **/*.xml + + + + ${basedir}/src/main/resources + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.6 + 1.6 + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/sql/druid_spring_config.sql b/druid_spring_config/sql/druid_spring_config.sql new file mode 100644 index 0000000..04c9cd5 --- /dev/null +++ b/druid_spring_config/sql/druid_spring_config.sql @@ -0,0 +1,26 @@ +/* +Navicat MySQL Data Transfer + +Source Server : uifuture +Source Server Version : 50714 +Source Host : localhost:3306 +Source Database : druid_spring_config + +Target Server Type : MYSQL +Target Server Version : 50714 +File Encoding : 65001 + +Date: 2018-02-06 23:19:42 +*/ + +SET FOREIGN_KEY_CHECKS=0; + +-- ---------------------------- +-- Table structure for user +-- ---------------------------- +DROP TABLE IF EXISTS `user`; +CREATE TABLE `user` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(64) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; diff --git a/druid_spring_config/src/main/java/com/uifuture/user/controller/UserContriller.java b/druid_spring_config/src/main/java/com/uifuture/user/controller/UserContriller.java new file mode 100644 index 0000000..5d7ed91 --- /dev/null +++ b/druid_spring_config/src/main/java/com/uifuture/user/controller/UserContriller.java @@ -0,0 +1,43 @@ +package com.uifuture.user.controller; + +import com.uifuture.user.entity.User; +import com.uifuture.user.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.ModelAndView; + +/** + * Created with IntelliJ IDEA. + * User: 陈浩翔. + * Date: 2018/2/6. + * Time: 下午 8:46. + * Explain: + */ +@RestController +public class UserContriller { + + @Autowired + private UserService userService; + @RequestMapping(value = {"/index","/"}) + public ModelAndView index(){ + return new ModelAndView("index"); + } + + @RequestMapping("/insert") + public @ResponseBody String insert(User user){ + Integer result = userService.insertUser(user); + if(result.equals(1)){ + return "success"; + } + return "error"; + } + + @RequestMapping("/find") + public @ResponseBody User find(Integer id){ + return userService.findUserById(id); + } + + +} diff --git a/druid_spring_config/src/main/java/com/uifuture/user/dao/UserMapper.java b/druid_spring_config/src/main/java/com/uifuture/user/dao/UserMapper.java new file mode 100644 index 0000000..9beaedd --- /dev/null +++ b/druid_spring_config/src/main/java/com/uifuture/user/dao/UserMapper.java @@ -0,0 +1,21 @@ +package com.uifuture.user.dao; + +import com.uifuture.user.entity.User; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserMapper { + int deleteByPrimaryKey(Integer id); + + int insert(User record); + + int insertSelective(User record); + + User selectByPrimaryKey(Integer id); + + int updateByPrimaryKeySelective(User record); + + int updateByPrimaryKey(User record); + + +} \ No newline at end of file diff --git a/druid_spring_config/src/main/java/com/uifuture/user/entity/User.java b/druid_spring_config/src/main/java/com/uifuture/user/entity/User.java new file mode 100644 index 0000000..8ae71d9 --- /dev/null +++ b/druid_spring_config/src/main/java/com/uifuture/user/entity/User.java @@ -0,0 +1,12 @@ +package com.uifuture.user.entity; + +import lombok.Data; + +import java.io.Serializable; + +@Data +public class User implements Serializable{ + private static final long serialVersionUID = 5205810816225483373L; + private Integer id; + private String name; +} \ No newline at end of file diff --git a/druid_spring_config/src/main/java/com/uifuture/user/mapping/UserMapper.xml b/druid_spring_config/src/main/java/com/uifuture/user/mapping/UserMapper.xml new file mode 100644 index 0000000..7623130 --- /dev/null +++ b/druid_spring_config/src/main/java/com/uifuture/user/mapping/UserMapper.xml @@ -0,0 +1,58 @@ + + + + + + + + + id, name + + + + delete from user + where id = #{id,jdbcType=INTEGER} + + + insert into user (id, name) + values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}) + + + insert into user + + + id, + + + name, + + + + + #{id,jdbcType=INTEGER}, + + + #{name,jdbcType=VARCHAR}, + + + + + update user + + + name = #{name,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=INTEGER} + + + update user + set name = #{name,jdbcType=VARCHAR} + where id = #{id,jdbcType=INTEGER} + + \ No newline at end of file diff --git a/druid_spring_config/src/main/java/com/uifuture/user/service/UserService.java b/druid_spring_config/src/main/java/com/uifuture/user/service/UserService.java new file mode 100644 index 0000000..3f7213b --- /dev/null +++ b/druid_spring_config/src/main/java/com/uifuture/user/service/UserService.java @@ -0,0 +1,27 @@ +package com.uifuture.user.service; + +import com.uifuture.user.entity.User; + +/** + * Created with IntelliJ IDEA. + * User: 陈浩翔. + * Date: 2018/2/6. + * Time: 下午 8:42. + * Explain: + */ +public interface UserService { + + /** + * 通过id查询用户 + * @param id + * @return + */ + User findUserById(Integer id); + + /** + * 插入用户 + * @param user + * @return + */ + Integer insertUser(User user); +} diff --git a/druid_spring_config/src/main/java/com/uifuture/user/service/impl/UserServiceImpl.java b/druid_spring_config/src/main/java/com/uifuture/user/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..8edd7bd --- /dev/null +++ b/druid_spring_config/src/main/java/com/uifuture/user/service/impl/UserServiceImpl.java @@ -0,0 +1,29 @@ +package com.uifuture.user.service.impl; + +import com.uifuture.user.dao.UserMapper; +import com.uifuture.user.entity.User; +import com.uifuture.user.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * Created with IntelliJ IDEA. + * User: 陈浩翔. + * Date: 2018/2/6. + * Time: 下午 8:43. + * Explain: + */ +@Service +public class UserServiceImpl implements UserService{ + + @Autowired + private UserMapper userMapper; + + public User findUserById(Integer id) { + return userMapper.selectByPrimaryKey(id); + } + + public Integer insertUser(User user) { + return userMapper.insertSelective(user); + } +} diff --git a/druid_spring_config/src/main/resources/config.properties b/druid_spring_config/src/main/resources/config.properties new file mode 100644 index 0000000..a13cc2e --- /dev/null +++ b/druid_spring_config/src/main/resources/config.properties @@ -0,0 +1,14 @@ + +# ������sql���Լ���־��� +druid_filters=stat,wall,log4j + +driverClassName=com.mysql.jdbc.Driver +jdbc_url=jdbc:mysql://localhost:3306/druid_spring_config?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull +jdbc_username=root +jdbc_password=1234 +#��ʼ�����Ӵ�С +jdbc_init=50 +#���ӳ���С���� +jdbc_minIdle=20 +#��ȡ�������ȴ�ʱ�� ��λΪ���� +jdbc_maxActive=60000 \ No newline at end of file diff --git a/druid_spring_config/src/main/resources/log4j.properties b/druid_spring_config/src/main/resources/log4j.properties new file mode 100644 index 0000000..0a3a35f --- /dev/null +++ b/druid_spring_config/src/main/resources/log4j.properties @@ -0,0 +1,69 @@ +#####配置根元素 +#调试模式,写成DEBUG ---设置日志级别-存储DEBUG以及以上级别的记录 +#log4j.rootLogger=DEBUG,console,file,error,druid +log4j.rootLogger=INFO,console,file,error,druid +#log4j.rootLogger=ERROR,console,file,error +#生产级项目,写成INFO就可以了 +#INFO级别比DEBUG级别高 ---console,file,error都是自己写的-名称自己定 + +####以下配置输出到控制台的配置#### +log4j.appender.console=org.apache.log4j.ConsoleAppender +log4j.appender.console.layout=org.apache.log4j.PatternLayout +log4j.appender.console.Target=System.out +log4j.appender.console.layout.ConversionPattern=[%p] %d{yyyy-MM-dd HH\:mm\:ss} [%l] -> %m [%t] [chx]%n + +### 输出到日志文件 ### +log4j.appender.file=org.apache.log4j.RollingFileAppender +#。RollingFileAppender按log文件最大长度限度生成新文件 +#以下是具体的目录 +log4j.appender.file.File=${catalina.home}/logs/druid_spring_config/info.log +#每个文件的最大大小 +log4j.appender.file.MaxFileSize=5MB +#最多可以是多少个文件 +log4j.appender.file.MaxBackupIndex=30 +## 输出INFO级别以上的日志 --Threshold是个全局的过滤器,它将把低于所设置的INFO的信息过滤不显示出来。 +#log4j.appender.file.Threshold=INFO +log4j.appender.file.Threshold=DEBUG +#服务器启动日志是追加, false:服务器启动后会生成日志文件把老的覆盖掉 +log4j.appender.file.Append = true +#信息的布局格式-按指定的格式打出 +log4j.appender.file.layout=org.apache.log4j.PatternLayout +#具体的布局格式 - %d为时间 +#log4j.appender.file.layout.ConversionPattern=%d %p [%c] %m %l %n +log4j.appender.file.layout.ConversionPattern=[%p] %d{yyyy-MM-dd HH\:mm\:ss} [%l] -> %m [%t] [chx]%n +#设置输出日志文件编码(可以控制乱码情况) +log4j.appender.file.encoding=UTF-8 + + +### 保存异常信息到单独文件 ### +log4j.appender.error = org.apache.log4j.DailyRollingFileAppender +#DailyRollingFileAppender按日期生成新文件 +## 异常日志文件名 +log4j.appender.error.File =${catalina.home}/logs/druid_spring_config/error.log +#这个路径是Tomcat的路径 +#在每天产生的文件后面追加 +log4j.appender.error.DatePattern = '.'yyyyMMdd +#服务器启动日志是追加,false:服务器启动后会生成日志文件把老的覆盖掉 +log4j.appender.error.Append = true +## 只输出ERROR级别以上的日志!!! +log4j.appender.error.Threshold = error +log4j.appender.error.layout = org.apache.log4j.PatternLayout +log4j.appender.error.layout.ConversionPattern =[%p] %d{yyyy-MM-dd HH\:mm\:ss} [%l] -> %m [%t] [chx]%n +#设置输出日志文件编码(可以控制乱码情况) +log4j.appender.error.encoding=UTF-8 + + +# Druid 慢查询记录日志 +log4j.logger.druid.sql=WARN,druid +log4j.logger.druid.sql.DataSource=WARN,druid +log4j.logger.druid.sql.Connection=WARN,druid +log4j.logger.druid.sql.Statement=WARN,druid + +log4j.appender.druid=org.apache.log4j.DailyRollingFileAppender +log4j.appender.druid.layout=org.apache.log4j.PatternLayout +log4j.appender.druid.layout.ConversionPattern= [%p] %d{yyyy-MM-dd HH\:mm\:ss} [%l] -> %m [%t] [chx]%n +log4j.appender.druid.datePattern='.'yyyy-MM-dd +log4j.appender.druid.Threshold = WARN +log4j.appender.druid.append=true +log4j.appender.druid.File=${catalina.home}/logs/druid_spring_config/druid-slow-sql.log +# ${catalina.home}是在tomcat的目录下 \ No newline at end of file diff --git a/druid_spring_config/src/main/resources/spring-mybatis.xml b/druid_spring_config/src/main/resources/spring-mybatis.xml new file mode 100644 index 0000000..96b9d99 --- /dev/null +++ b/druid_spring_config/src/main/resources/spring-mybatis.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/src/main/resources/spring.xml b/druid_spring_config/src/main/resources/spring.xml new file mode 100644 index 0000000..802e290 --- /dev/null +++ b/druid_spring_config/src/main/resources/spring.xml @@ -0,0 +1,158 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + classpath*:com/uifuture/*/mapping/*.xml + + + + + + + + + + + + + + + + + + + + + + + + + com.uifuture.user.service.* + com.uifuture.user.dao.* + + + + + + + + + + + + + + + + + + + + + + text/html;charset=UTF-8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + UTF-8 + + + 32505856 + + + 4096 + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/src/main/webapp/WEB-INF/views/index.jsp b/druid_spring_config/src/main/webapp/WEB-INF/views/index.jsp new file mode 100644 index 0000000..8ed39f0 --- /dev/null +++ b/druid_spring_config/src/main/webapp/WEB-INF/views/index.jsp @@ -0,0 +1,24 @@ +<%-- + Created by IntelliJ IDEA. + User: 陈浩翔 + Date: 2018/02/06 + Time: 下午 8:19 + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + + + druid配置 + + + + + + + +

druid配置

+ + + diff --git a/druid_spring_config/src/main/webapp/WEB-INF/web.xml b/druid_spring_config/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..90840fe --- /dev/null +++ b/druid_spring_config/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,117 @@ + + UIFuture + + contextConfigLocation + classpath:spring.xml,classpath:spring-mybatis.xml + + + 字符集过滤器 + encodingFilter + org.springframework.web.filter.CharacterEncodingFilter + + 字符集编码 + encoding + UTF-8 + + + + encodingFilter + /* + + + + + DruidWebStatFilter + com.alibaba.druid.support.http.WebStatFilter + + exclusions + + *.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/* + + + profileEnable + true + + + + DruidWebStatFilter + /* + + + + + + spring监听器-上下文监听器 + org.springframework.web.context.ContextLoaderListener + + + + + org.springframework.web.context.request.RequestContextListener + + + + + org.springframework.web.util.IntrospectorCleanupListener + + + + + spring mvc servlet + springMvc + org.springframework.web.servlet.DispatcherServlet + + spring mvc 配置文件 + contextConfigLocation + classpath:spring.xml + + 1 + + + + + + DruidStatView + com.alibaba.druid.support.http.StatViewServlet + + + + + + + + + loginUsername + root + + + + loginPassword + chenhaoxiang + + + + DruidStatView + /druid/* + + + + + index + + + + springMvc + / + + + + + 30 + + + \ No newline at end of file diff --git a/druid_spring_config/target/classes/com/uifuture/user/controller/UserContriller.class b/druid_spring_config/target/classes/com/uifuture/user/controller/UserContriller.class new file mode 100644 index 0000000..a23923a Binary files /dev/null and b/druid_spring_config/target/classes/com/uifuture/user/controller/UserContriller.class differ diff --git a/druid_spring_config/target/classes/com/uifuture/user/dao/UserMapper.class b/druid_spring_config/target/classes/com/uifuture/user/dao/UserMapper.class new file mode 100644 index 0000000..dec8ac0 Binary files /dev/null and b/druid_spring_config/target/classes/com/uifuture/user/dao/UserMapper.class differ diff --git a/druid_spring_config/target/classes/com/uifuture/user/entity/User.class b/druid_spring_config/target/classes/com/uifuture/user/entity/User.class new file mode 100644 index 0000000..5d66b1c Binary files /dev/null and b/druid_spring_config/target/classes/com/uifuture/user/entity/User.class differ diff --git a/druid_spring_config/target/classes/com/uifuture/user/mapping/UserMapper.xml b/druid_spring_config/target/classes/com/uifuture/user/mapping/UserMapper.xml new file mode 100644 index 0000000..7623130 --- /dev/null +++ b/druid_spring_config/target/classes/com/uifuture/user/mapping/UserMapper.xml @@ -0,0 +1,58 @@ + + + + + + + + + id, name + + + + delete from user + where id = #{id,jdbcType=INTEGER} + + + insert into user (id, name) + values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}) + + + insert into user + + + id, + + + name, + + + + + #{id,jdbcType=INTEGER}, + + + #{name,jdbcType=VARCHAR}, + + + + + update user + + + name = #{name,jdbcType=VARCHAR}, + + + where id = #{id,jdbcType=INTEGER} + + + update user + set name = #{name,jdbcType=VARCHAR} + where id = #{id,jdbcType=INTEGER} + + \ No newline at end of file diff --git a/druid_spring_config/target/classes/com/uifuture/user/service/UserService.class b/druid_spring_config/target/classes/com/uifuture/user/service/UserService.class new file mode 100644 index 0000000..bc1200d Binary files /dev/null and b/druid_spring_config/target/classes/com/uifuture/user/service/UserService.class differ diff --git a/druid_spring_config/target/classes/com/uifuture/user/service/impl/UserServiceImpl.class b/druid_spring_config/target/classes/com/uifuture/user/service/impl/UserServiceImpl.class new file mode 100644 index 0000000..af1a4ef Binary files /dev/null and b/druid_spring_config/target/classes/com/uifuture/user/service/impl/UserServiceImpl.class differ diff --git a/druid_spring_config/target/classes/config.properties b/druid_spring_config/target/classes/config.properties new file mode 100644 index 0000000..a13cc2e --- /dev/null +++ b/druid_spring_config/target/classes/config.properties @@ -0,0 +1,14 @@ + +# ������sql���Լ���־��� +druid_filters=stat,wall,log4j + +driverClassName=com.mysql.jdbc.Driver +jdbc_url=jdbc:mysql://localhost:3306/druid_spring_config?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull +jdbc_username=root +jdbc_password=1234 +#��ʼ�����Ӵ�С +jdbc_init=50 +#���ӳ���С���� +jdbc_minIdle=20 +#��ȡ�������ȴ�ʱ�� ��λΪ���� +jdbc_maxActive=60000 \ No newline at end of file diff --git a/druid_spring_config/target/classes/log4j.properties b/druid_spring_config/target/classes/log4j.properties new file mode 100644 index 0000000..0a3a35f --- /dev/null +++ b/druid_spring_config/target/classes/log4j.properties @@ -0,0 +1,69 @@ +#####配置根元素 +#调试模式,写成DEBUG ---设置日志级别-存储DEBUG以及以上级别的记录 +#log4j.rootLogger=DEBUG,console,file,error,druid +log4j.rootLogger=INFO,console,file,error,druid +#log4j.rootLogger=ERROR,console,file,error +#生产级项目,写成INFO就可以了 +#INFO级别比DEBUG级别高 ---console,file,error都是自己写的-名称自己定 + +####以下配置输出到控制台的配置#### +log4j.appender.console=org.apache.log4j.ConsoleAppender +log4j.appender.console.layout=org.apache.log4j.PatternLayout +log4j.appender.console.Target=System.out +log4j.appender.console.layout.ConversionPattern=[%p] %d{yyyy-MM-dd HH\:mm\:ss} [%l] -> %m [%t] [chx]%n + +### 输出到日志文件 ### +log4j.appender.file=org.apache.log4j.RollingFileAppender +#。RollingFileAppender按log文件最大长度限度生成新文件 +#以下是具体的目录 +log4j.appender.file.File=${catalina.home}/logs/druid_spring_config/info.log +#每个文件的最大大小 +log4j.appender.file.MaxFileSize=5MB +#最多可以是多少个文件 +log4j.appender.file.MaxBackupIndex=30 +## 输出INFO级别以上的日志 --Threshold是个全局的过滤器,它将把低于所设置的INFO的信息过滤不显示出来。 +#log4j.appender.file.Threshold=INFO +log4j.appender.file.Threshold=DEBUG +#服务器启动日志是追加, false:服务器启动后会生成日志文件把老的覆盖掉 +log4j.appender.file.Append = true +#信息的布局格式-按指定的格式打出 +log4j.appender.file.layout=org.apache.log4j.PatternLayout +#具体的布局格式 - %d为时间 +#log4j.appender.file.layout.ConversionPattern=%d %p [%c] %m %l %n +log4j.appender.file.layout.ConversionPattern=[%p] %d{yyyy-MM-dd HH\:mm\:ss} [%l] -> %m [%t] [chx]%n +#设置输出日志文件编码(可以控制乱码情况) +log4j.appender.file.encoding=UTF-8 + + +### 保存异常信息到单独文件 ### +log4j.appender.error = org.apache.log4j.DailyRollingFileAppender +#DailyRollingFileAppender按日期生成新文件 +## 异常日志文件名 +log4j.appender.error.File =${catalina.home}/logs/druid_spring_config/error.log +#这个路径是Tomcat的路径 +#在每天产生的文件后面追加 +log4j.appender.error.DatePattern = '.'yyyyMMdd +#服务器启动日志是追加,false:服务器启动后会生成日志文件把老的覆盖掉 +log4j.appender.error.Append = true +## 只输出ERROR级别以上的日志!!! +log4j.appender.error.Threshold = error +log4j.appender.error.layout = org.apache.log4j.PatternLayout +log4j.appender.error.layout.ConversionPattern =[%p] %d{yyyy-MM-dd HH\:mm\:ss} [%l] -> %m [%t] [chx]%n +#设置输出日志文件编码(可以控制乱码情况) +log4j.appender.error.encoding=UTF-8 + + +# Druid 慢查询记录日志 +log4j.logger.druid.sql=WARN,druid +log4j.logger.druid.sql.DataSource=WARN,druid +log4j.logger.druid.sql.Connection=WARN,druid +log4j.logger.druid.sql.Statement=WARN,druid + +log4j.appender.druid=org.apache.log4j.DailyRollingFileAppender +log4j.appender.druid.layout=org.apache.log4j.PatternLayout +log4j.appender.druid.layout.ConversionPattern= [%p] %d{yyyy-MM-dd HH\:mm\:ss} [%l] -> %m [%t] [chx]%n +log4j.appender.druid.datePattern='.'yyyy-MM-dd +log4j.appender.druid.Threshold = WARN +log4j.appender.druid.append=true +log4j.appender.druid.File=${catalina.home}/logs/druid_spring_config/druid-slow-sql.log +# ${catalina.home}是在tomcat的目录下 \ No newline at end of file diff --git a/druid_spring_config/target/classes/spring-mybatis.xml b/druid_spring_config/target/classes/spring-mybatis.xml new file mode 100644 index 0000000..96b9d99 --- /dev/null +++ b/druid_spring_config/target/classes/spring-mybatis.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/druid_spring_config/target/classes/spring.xml b/druid_spring_config/target/classes/spring.xml new file mode 100644 index 0000000..802e290 --- /dev/null +++ b/druid_spring_config/target/classes/spring.xml @@ -0,0 +1,158 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + classpath*:com/uifuture/*/mapping/*.xml + + + + + + + + + + + + + + + + + + + + + + + + + com.uifuture.user.service.* + com.uifuture.user.dao.* + + + + + + + + + + + + + + + + + + + + + + text/html;charset=UTF-8 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + UTF-8 + + + 32505856 + + + 4096 + + + + + + + + \ No newline at end of file diff --git a/log4j_jar/log4j-1.2.17.zip b/log4j_jar/log4j-1.2.17.zip new file mode 100644 index 0000000..8fc4845 Binary files /dev/null and b/log4j_jar/log4j-1.2.17.zip differ diff --git a/myBeanUtils/.classpath b/myBeanUtils/.classpath new file mode 100644 index 0000000..2a50e7e --- /dev/null +++ b/myBeanUtils/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/myBeanUtils/.project b/myBeanUtils/.project new file mode 100644 index 0000000..2480b82 --- /dev/null +++ b/myBeanUtils/.project @@ -0,0 +1,17 @@ + + + myBeanUtils + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/myBeanUtils/.settings/org.eclipse.jdt.core.prefs b/myBeanUtils/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..2d19835 --- /dev/null +++ b/myBeanUtils/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +#Thu Aug 25 11:01:52 CST 2016 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/myBeanUtils/README.md b/myBeanUtils/README.md new file mode 100644 index 0000000..be86153 --- /dev/null +++ b/myBeanUtils/README.md @@ -0,0 +1,361 @@ + + + + + +【BeanUtils】自己写的一个BeanUtils-代码方法详解 + + + +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ +

BeanUtils工具包是由Apache公司所开发,主要是方便程序员对Bean类能够进行简便的操作。

+ +

在这里,不讲解如何使用apache的BeanUtils工具,而是我们自己写底层,自己利用类反射来实现BeanUtils的功能。
+需要先学习类反射!

+ +

通过给定bean对象的类,和封装的Map对象,返回出一个bean对象。

+ +

准备bean对象:

+ +

这里准备了User类和Book类:

+ + + +

User

+ + + +
package cn.hncu.domain;
+
+/**
+ * @author 陈浩翔
+ *
+ * 2016-8-25
+ */
+public class User {
+    private String uuid;
+    private String name;
+    private int age;
+    public String getUuid() {
+        return uuid;
+    }
+    public void setUuid(String uuid) {
+        this.uuid = uuid;
+    }
+    public String getName() {
+        return name;
+    }
+    public void setName(String name) {
+        this.name = name;
+    }
+    public int getAge() {
+        return age;
+    }
+    public void setAge(int age) {
+        this.age = age;
+    }
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());
+        return result;
+    }
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj)
+            return true;
+        if (obj == null)
+            return false;
+        if (getClass() != obj.getClass())
+            return false;
+        User other = (User) obj;
+        if (uuid == null) {
+            if (other.uuid != null)
+                return false;
+        } else if (!uuid.equals(other.uuid))
+            return false;
+        return true;
+    }
+    @Override
+    public String toString() {
+        return "User [uuid=" + uuid + ", name=" + name + ", age=" + age + "]";
+    }
+
+}
+
+ + + +

Book

+ + + +
package cn.hncu.domain;
+
+/**
+ * @author 陈浩翔
+ *
+ * 2016-8-25
+ */
+public class Book {
+    private String uuid;
+    private String name;
+    private double inPrice;
+    private double outPrice;
+    private int num;
+    public String getUuid() {
+        return uuid;
+    }
+    public void setUuid(String uuid) {
+        this.uuid = uuid;
+    }
+    public String getName() {
+        return name;
+    }
+    public void setName(String name) {
+        this.name = name;
+    }
+    public double getInPrice() {
+        return inPrice;
+    }
+    public void setInPrice(double inPrice) {
+        this.inPrice = inPrice;
+    }
+    public double getOutPrice() {
+        return outPrice;
+    }
+    public void setOutPrice(double outPrice) {
+        this.outPrice = outPrice;
+    }
+    public int getNum() {
+        return num;
+    }
+    public void setNum(int num) {
+        this.num = num;
+    }
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());
+        return result;
+    }
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj)
+            return true;
+        if (obj == null)
+            return false;
+        if (getClass() != obj.getClass())
+            return false;
+        Book other = (Book) obj;
+        if (uuid == null) {
+            if (other.uuid != null)
+                return false;
+        } else if (!uuid.equals(other.uuid))
+            return false;
+        return true;
+    }
+    @Override
+    public String toString() {
+        return "Book [uuid=" + uuid + ", name=" + name + ", inPrice=" + inPrice
+                + ", outPrice=" + outPrice + ", num=" + num + "]";
+    }
+}
+
+ +

过度版的:

+ +

先看过度版的:接参后需要强转成对应的bean,因为返回类型是Object。

+ + + +

MyBeanUtils1

+ + + +
package cn.hncu.beanUtils;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Map;
+
+public class MyBeanUtils1 {
+
+    public static Object populate(Class cls ,Map map) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
+        Object obj = null;
+
+        //1、用类反射new出对象
+        obj = cls.newInstance();
+
+        //2 再用类反射对新new的对象设置属性值(必须遵守Java设置规范)--即通过setter方法设置
+        //2.1遍历出所有该类声明的属性
+        Field flds[] = cls.getDeclaredFields();//getDeclaredFields()返回Class中所有的字段,包括私有字段;
+        for(Field fld:flds){
+            //获取该fld对象所代表的属性名
+            String fldName = fld.getName();
+            //根据属性名,到map中去读取数据,只有数据非空才需要给该属性设置值 
+            Object value = map.get(fldName);
+            if(value==null){//如果map中不存在对应的属性数据,我们在这里给出提示信息
+                System.out.println(fldName+"的数据为空");
+            }else{
+                //如果map中存在对应的属性数据,则由属性名得出它的setter方法的名字
+                String mothodName = "set"+fldName.substring(0, 1).toUpperCase()+fldName.substring(1);
+
+                 //根据方法名和参数的数据类型(其实就是属性的类型),获得Method对象
+                Class paramTypes[] = new Class[1];
+                paramTypes[0] = fld.getType();
+                Method method = cls.getDeclaredMethod(mothodName, paramTypes);
+
+                //调用该method对象所代表的方法
+                Object args[] = new Object[1];
+                args[0]=value;
+                method.invoke(obj, args);
+            }
+        }
+        return obj;
+    }
+
+}
+ + + +

测试

+ + + +
@Test
+    public void test1() {
+        Map map = new HashMap();
+        map.put("uuid", "001");
+        map.put("name", "Jack");
+        map.put("age", 20);
+
+        Map map2 = new HashMap();
+        map2.put("uuid", "001");
+        map2.put("name", "红楼梦");
+        map2.put("inPrice", 20.5);
+        //数据可能不全
+        map2.put("num", 123);
+        try {
+            User user =  (User) MyBeanUtils1.populate(User.class, map);
+            System.out.println(user);
+            Book book =  (Book) MyBeanUtils1.populate(Book.class, map2);
+            System.out.println(book);
+        } catch (ReflectiveOperationException e) {
+            e.printStackTrace();
+        }
+    }
+ + + +

测试结果:

+ +

+ +

这个还不是很完善,为什么呢,因为返回类型是Object,每次都要强转,比较麻烦,而且我们传了bean的class对象过去了,完全可以实现不用强转的,这个时候我们就需要用到泛型了。
+而且Map的泛型我们可以确定了,肯定是Map<String,Object>这样的

+ +

好了,学习一下最终版的、

+ +

最终版:

+ + + +

MyBeanUtils

+ + + +
package cn.hncu.beanUtils;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Map;
+
+public class MyBeanUtils {
+
+    public static<T> T populate(Class<T> cls ,Map<String, Object> map) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
+        T obj = null;
+
+        //1、用类反射new出对象
+        obj = cls.newInstance();
+
+        //2 再用类反射对新new的对象设置属性值(必须遵守Java设置规范)--即通过setter方法设置
+        //2.1遍历出所有该类声明的属性
+        Field flds[] = cls.getDeclaredFields();//getDeclaredFields()返回Class中所有的字段,包括私有字段;
+        for(Field fld:flds){
+            //获取该fld对象所代表的属性名
+            String fldName = fld.getName();
+            //根据属性名,到map中去读取数据,只有数据非空才需要给该属性设置值 
+            Object value = map.get(fldName);
+            if(value==null){//如果map中不存在对应的属性数据,我们在这里给出提示信息
+                System.out.println(fldName+"的数据为空");
+            }else{
+                //如果map中存在对应的属性数据,则由属性名得出它的setter方法的名字
+                String mothodName = "set"+fldName.substring(0, 1).toUpperCase()+fldName.substring(1);
+
+                 //根据方法名和参数的数据类型(其实就是属性的类型),获得Method对象
+                Class<?> paramTypes[] = new Class[1];
+                paramTypes[0] = fld.getType();
+                Method method = cls.getDeclaredMethod(mothodName, paramTypes);
+
+                //调用该method对象所代表的方法
+                Object args[] = new Object[1];
+                args[0]=value;
+                method.invoke(obj, args);
+            }
+        }
+        return obj;
+    }
+
+}
+
+ + + +

测试方法:

+ + + +
@Test
+    @SuppressWarnings("unchecked")
+    public void test() {
+        Map<String, Object> map = new HashMap();
+        map.put("uuid", "001");
+        map.put("name", "Jack");
+        map.put("age", 20);
+
+        Map<String, Object> map2 = new HashMap();
+        map2.put("uuid", "001");
+        map2.put("name", "红楼梦");
+        map2.put("inPrice", 20.5);
+        //数据可能不全
+        map2.put("num", 123);
+        try {
+            User user = MyBeanUtils.populate(User.class, map);
+            System.out.println(user);
+            Book book = MyBeanUtils.populate(Book.class, map2);
+            System.out.println(book);
+        } catch (ReflectiveOperationException e) {
+            e.printStackTrace();
+        }
+    }
+ + + +

测试结果:

+ +

+ +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ \ No newline at end of file diff --git a/myBeanUtils/bin/cn/hncu/TestDemo.class b/myBeanUtils/bin/cn/hncu/TestDemo.class new file mode 100644 index 0000000..f99eee1 Binary files /dev/null and b/myBeanUtils/bin/cn/hncu/TestDemo.class differ diff --git a/myBeanUtils/bin/cn/hncu/beanUtils/MyBeanUtils.class b/myBeanUtils/bin/cn/hncu/beanUtils/MyBeanUtils.class new file mode 100644 index 0000000..d417937 Binary files /dev/null and b/myBeanUtils/bin/cn/hncu/beanUtils/MyBeanUtils.class differ diff --git a/myBeanUtils/bin/cn/hncu/beanUtils/MyBeanUtils1.class b/myBeanUtils/bin/cn/hncu/beanUtils/MyBeanUtils1.class new file mode 100644 index 0000000..498c29b Binary files /dev/null and b/myBeanUtils/bin/cn/hncu/beanUtils/MyBeanUtils1.class differ diff --git a/myBeanUtils/bin/cn/hncu/domain/Address.class b/myBeanUtils/bin/cn/hncu/domain/Address.class new file mode 100644 index 0000000..d273f10 Binary files /dev/null and b/myBeanUtils/bin/cn/hncu/domain/Address.class differ diff --git a/myBeanUtils/bin/cn/hncu/domain/Book.class b/myBeanUtils/bin/cn/hncu/domain/Book.class new file mode 100644 index 0000000..aa24bd1 Binary files /dev/null and b/myBeanUtils/bin/cn/hncu/domain/Book.class differ diff --git a/myBeanUtils/bin/cn/hncu/domain/Person.class b/myBeanUtils/bin/cn/hncu/domain/Person.class new file mode 100644 index 0000000..2437b65 Binary files /dev/null and b/myBeanUtils/bin/cn/hncu/domain/Person.class differ diff --git a/myBeanUtils/bin/cn/hncu/domain/User.class b/myBeanUtils/bin/cn/hncu/domain/User.class new file mode 100644 index 0000000..f884e7e Binary files /dev/null and b/myBeanUtils/bin/cn/hncu/domain/User.class differ diff --git a/myBeanUtils/myBeanUtils.zip b/myBeanUtils/myBeanUtils.zip new file mode 100644 index 0000000..ab1fffa Binary files /dev/null and b/myBeanUtils/myBeanUtils.zip differ diff --git a/myBeanUtils/src/cn/hncu/TestDemo.java b/myBeanUtils/src/cn/hncu/TestDemo.java new file mode 100644 index 0000000..6d6fa7e --- /dev/null +++ b/myBeanUtils/src/cn/hncu/TestDemo.java @@ -0,0 +1,97 @@ +package cn.hncu; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +import cn.hncu.beanUtils.MyBeanUtils; +import cn.hncu.beanUtils.MyBeanUtils1; +import cn.hncu.domain.Address; +import cn.hncu.domain.Book; +import cn.hncu.domain.Person; +import cn.hncu.domain.User; + +public class TestDemo { + + @Test + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void test2() { + Map p = new HashMap(); + p.put("name", "Jack"); + p.put("age", 100); + p.put("address", new Address("湖南", "长沙")); + + List lists = new ArrayList(); + lists.add(new Book("B001", "红楼梦", 25.00, 53.23, 500)); + lists.add(new User("U001", "李四", 25)); + lists.add("嵌套使用"); + p.put("lists", lists); + + Map map = new HashMap(); + map.put("user", new User("MU002", "MapUser", 30)); + map.put("string", "map中的字符串"); + p.put("map", map); + + try { + Person person = MyBeanUtils.populate(Person.class, p); + + System.out.println(person); + + } catch (ReflectiveOperationException e) { + e.printStackTrace(); + } + } + + + @Test + @SuppressWarnings("unchecked") + public void test() { + Map map = new HashMap(); + map.put("uuid", "001"); + map.put("name", "Jack"); + map.put("age", 20); + + Map map2 = new HashMap(); + map2.put("uuid", "001"); + map2.put("name", "张三"); + map2.put("inPrice", 20.5); + //数据可能不全 + map2.put("num", 123); + try { + User user = MyBeanUtils.populate(User.class, map); + System.out.println(user); + Book book = MyBeanUtils.populate(Book.class, map2); + System.out.println(book); + } catch (ReflectiveOperationException e) { + e.printStackTrace(); + } + } + + @Test + public void test1() { + Map map = new HashMap(); + map.put("uuid", "001"); + map.put("name", "Jack"); + map.put("age", 20); + + Map map2 = new HashMap(); + map2.put("uuid", "001"); + map2.put("name", "张三"); + map2.put("inPrice", 20.5); + //数据可能不全 + map2.put("num", 123); + try { + User user = (User) MyBeanUtils1.populate(User.class, map); + System.out.println(user); + Book book = (Book) MyBeanUtils1.populate(Book.class, map2); + System.out.println(book); + } catch (ReflectiveOperationException e) { + e.printStackTrace(); + } + } + + +} diff --git a/myBeanUtils/src/cn/hncu/beanUtils/MyBeanUtils.java b/myBeanUtils/src/cn/hncu/beanUtils/MyBeanUtils.java new file mode 100644 index 0000000..ed75b5d --- /dev/null +++ b/myBeanUtils/src/cn/hncu/beanUtils/MyBeanUtils.java @@ -0,0 +1,49 @@ +package cn.hncu.beanUtils; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Map; + +/** + * @author 陈浩翔 + * + * 2016-8-25 + */ +public class MyBeanUtils { + + public static T populate(Class cls ,Map map) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{ + T obj = null; + + //1、用类反射new出对象 + obj = cls.newInstance(); + + //2 再用类反射对新new的对象设置属性值(必须遵守Java设置规范)--即通过setter方法设置 + //2.1遍历出所有该类声明的属性 + Field flds[] = cls.getDeclaredFields();//getDeclaredFields()返回Class中所有的字段,包括私有字段; + for(Field fld:flds){ + //获取该fld对象所代表的属性名 + String fldName = fld.getName(); + //根据属性名,到map中去读取数据,只有数据非空才需要给该属性设置值 + Object value = map.get(fldName); + if(value==null){//如果map中不存在对应的属性数据,我们在这里给出提示信息 + System.out.println(fldName+"的数据为空"); + }else{ + //如果map中存在对应的属性数据,则由属性名得出它的setter方法的名字 + String mothodName = "set"+fldName.substring(0, 1).toUpperCase()+fldName.substring(1); + + //根据方法名和参数的数据类型(其实就是属性的类型),获得Method对象 + Class paramTypes[] = new Class[1]; + paramTypes[0] = fld.getType(); + Method method = cls.getDeclaredMethod(mothodName, paramTypes); + + //调用该method对象所代表的方法 + Object args[] = new Object[1]; + args[0]=value; + method.invoke(obj, args); + } + } + return obj; + } + +} diff --git a/myBeanUtils/src/cn/hncu/beanUtils/MyBeanUtils1.java b/myBeanUtils/src/cn/hncu/beanUtils/MyBeanUtils1.java new file mode 100644 index 0000000..34fadf5 --- /dev/null +++ b/myBeanUtils/src/cn/hncu/beanUtils/MyBeanUtils1.java @@ -0,0 +1,44 @@ +package cn.hncu.beanUtils; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Map; + +public class MyBeanUtils1 { + + public static Object populate(Class cls ,Map map) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{ + Object obj = null; + + //1、用类反射new出对象 + obj = cls.newInstance(); + + //2 再用类反射对新new的对象设置属性值(必须遵守Java设置规范)--即通过setter方法设置 + //2.1遍历出所有该类声明的属性 + Field flds[] = cls.getDeclaredFields();//getDeclaredFields()返回Class中所有的字段,包括私有字段; + for(Field fld:flds){ + //获取该fld对象所代表的属性名 + String fldName = fld.getName(); + //根据属性名,到map中去读取数据,只有数据非空才需要给该属性设置值 + Object value = map.get(fldName); + if(value==null){//如果map中不存在对应的属性数据,我们在这里给出提示信息 + System.out.println(fldName+"的数据为空"); + }else{ + //如果map中存在对应的属性数据,则由属性名得出它的setter方法的名字 + String mothodName = "set"+fldName.substring(0, 1).toUpperCase()+fldName.substring(1); + + //根据方法名和参数的数据类型(其实就是属性的类型),获得Method对象 + Class paramTypes[] = new Class[1]; + paramTypes[0] = fld.getType(); + Method method = cls.getDeclaredMethod(mothodName, paramTypes); + + //调用该method对象所代表的方法 + Object args[] = new Object[1]; + args[0]=value; + method.invoke(obj, args); + } + } + return obj; + } + +} diff --git a/myBeanUtils/src/cn/hncu/domain/Address.java b/myBeanUtils/src/cn/hncu/domain/Address.java new file mode 100644 index 0000000..acb904f --- /dev/null +++ b/myBeanUtils/src/cn/hncu/domain/Address.java @@ -0,0 +1,33 @@ +package cn.hncu.domain; + +/** + * @author 陈浩翔 + * + * 2016-8-25 + */ +public class Address { + private String province;//省份 + private String city;//城市 + public Address() { + } + public Address(String province, String city) { + this.province = province; + this.city = city; + } + public String getProvince() { + return province; + } + public void setProvince(String province) { + this.province = province; + } + public String getCity() { + return city; + } + public void setCity(String city) { + this.city = city; + } + @Override + public String toString() { + return "Address [province=" + province + ", city=" + city + "]"; + } +} diff --git a/myBeanUtils/src/cn/hncu/domain/Book.java b/myBeanUtils/src/cn/hncu/domain/Book.java new file mode 100644 index 0000000..c1e13dd --- /dev/null +++ b/myBeanUtils/src/cn/hncu/domain/Book.java @@ -0,0 +1,85 @@ +package cn.hncu.domain; + +/** + * @author 陈浩翔 + * + * 2016-8-25 + */ +public class Book { + private String uuid; + private String name; + private double inPrice; + private double outPrice; + private int num; + + public Book() { + super(); + } + public Book(String uuid, String name, double inPrice, double outPrice, + int num) { + super(); + this.uuid = uuid; + this.name = name; + this.inPrice = inPrice; + this.outPrice = outPrice; + this.num = num; + } + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public double getInPrice() { + return inPrice; + } + public void setInPrice(double inPrice) { + this.inPrice = inPrice; + } + public double getOutPrice() { + return outPrice; + } + public void setOutPrice(double outPrice) { + this.outPrice = outPrice; + } + public int getNum() { + return num; + } + public void setNum(int num) { + this.num = num; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((uuid == null) ? 0 : uuid.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Book other = (Book) obj; + if (uuid == null) { + if (other.uuid != null) + return false; + } else if (!uuid.equals(other.uuid)) + return false; + return true; + } + @Override + public String toString() { + return "Book [uuid=" + uuid + ", name=" + name + ", inPrice=" + inPrice + + ", outPrice=" + outPrice + ", num=" + num + "]"; + } +} diff --git a/myBeanUtils/src/cn/hncu/domain/Person.java b/myBeanUtils/src/cn/hncu/domain/Person.java new file mode 100644 index 0000000..6d795c7 --- /dev/null +++ b/myBeanUtils/src/cn/hncu/domain/Person.java @@ -0,0 +1,65 @@ +package cn.hncu.domain; + +import java.util.List; +import java.util.Map; + +/** + * @author 陈浩翔 + * + * 2016-8-25 + */ +public class Person { + private String name; + private int age; + private Address address; + private List lists; + private Map map; + public Person() { + super(); + } + public Person(String name, int age, Address address, List lists, Map map) { + super(); + this.name = name; + this.age = age; + this.address = address; + this.lists = lists; + this.map = map; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public int getAge() { + return age; + } + public void setAge(int age) { + this.age = age; + } + public Address getAddress() { + return address; + } + public void setAddress(Address address) { + this.address = address; + } + public List getLists() { + return lists; + } + public void setLists(List lists) { + this.lists = lists; + } + public Map getMap() { + return map; + } + public void setMap(Map map) { + this.map = map; + } + + @Override + public String toString() { + return "Person [name=" + name + ", age=" + age + ", address=" + address + + ", lists=" + lists + ", map=" + map + "]"; + } + +} diff --git a/myBeanUtils/src/cn/hncu/domain/User.java b/myBeanUtils/src/cn/hncu/domain/User.java new file mode 100644 index 0000000..a6dc941 --- /dev/null +++ b/myBeanUtils/src/cn/hncu/domain/User.java @@ -0,0 +1,69 @@ +package cn.hncu.domain; + +/** + * @author 陈浩翔 + * + * 2016-8-25 + */ +public class User { + private String uuid; + private String name; + private int age; + public User() { + super(); + } + + public User(String uuid, String name, int age) { + super(); + this.uuid = uuid; + this.name = name; + this.age = age; + } + + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public int getAge() { + return age; + } + public void setAge(int age) { + this.age = age; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((uuid == null) ? 0 : uuid.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + User other = (User) obj; + if (uuid == null) { + if (other.uuid != null) + return false; + } else if (!uuid.equals(other.uuid)) + return false; + return true; + } + @Override + public String toString() { + return "User [uuid=" + uuid + ", name=" + name + ", age=" + age + "]"; + } + +} diff --git "a/myBeanUtils/\343\200\220BeanUtils\343\200\221\350\207\252\345\267\261\345\206\231\347\232\204\344\270\200\344\270\252BeanUtils-\344\273\243\347\240\201\346\226\271\346\263\225\350\257\246\350\247\243.html" "b/myBeanUtils/\343\200\220BeanUtils\343\200\221\350\207\252\345\267\261\345\206\231\347\232\204\344\270\200\344\270\252BeanUtils-\344\273\243\347\240\201\346\226\271\346\263\225\350\257\246\350\247\243.html" new file mode 100644 index 0000000..3ca43fa --- /dev/null +++ "b/myBeanUtils/\343\200\220BeanUtils\343\200\221\350\207\252\345\267\261\345\206\231\347\232\204\344\270\200\344\270\252BeanUtils-\344\273\243\347\240\201\346\226\271\346\263\225\350\257\246\350\247\243.html" @@ -0,0 +1,361 @@ + + + + + +【BeanUtils】自己写的一个BeanUtils-代码方法详解 + + + +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ +

BeanUtils工具包是由Apache公司所开发,主要是方便程序员对Bean类能够进行简便的操作。

+ +

在这里,不讲解如何使用apache的BeanUtils工具,而是我们自己写底层,自己利用类反射来实现BeanUtils的功能。
+需要先学习类反射!

+ +

通过给定bean对象的类,和封装的Map对象,返回出一个bean对象。

+ +

准备bean对象:

+ +

这里准备了User类和Book类:

+ + + +

User

+ + + +
package cn.hncu.domain;
+
+/**
+ * @author 陈浩翔
+ *
+ * 2016-8-25
+ */
+public class User {
+    private String uuid;
+    private String name;
+    private int age;
+    public String getUuid() {
+        return uuid;
+    }
+    public void setUuid(String uuid) {
+        this.uuid = uuid;
+    }
+    public String getName() {
+        return name;
+    }
+    public void setName(String name) {
+        this.name = name;
+    }
+    public int getAge() {
+        return age;
+    }
+    public void setAge(int age) {
+        this.age = age;
+    }
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());
+        return result;
+    }
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj)
+            return true;
+        if (obj == null)
+            return false;
+        if (getClass() != obj.getClass())
+            return false;
+        User other = (User) obj;
+        if (uuid == null) {
+            if (other.uuid != null)
+                return false;
+        } else if (!uuid.equals(other.uuid))
+            return false;
+        return true;
+    }
+    @Override
+    public String toString() {
+        return "User [uuid=" + uuid + ", name=" + name + ", age=" + age + "]";
+    }
+
+}
+
+ + + +

Book

+ + + +
package cn.hncu.domain;
+
+/**
+ * @author 陈浩翔
+ *
+ * 2016-8-25
+ */
+public class Book {
+    private String uuid;
+    private String name;
+    private double inPrice;
+    private double outPrice;
+    private int num;
+    public String getUuid() {
+        return uuid;
+    }
+    public void setUuid(String uuid) {
+        this.uuid = uuid;
+    }
+    public String getName() {
+        return name;
+    }
+    public void setName(String name) {
+        this.name = name;
+    }
+    public double getInPrice() {
+        return inPrice;
+    }
+    public void setInPrice(double inPrice) {
+        this.inPrice = inPrice;
+    }
+    public double getOutPrice() {
+        return outPrice;
+    }
+    public void setOutPrice(double outPrice) {
+        this.outPrice = outPrice;
+    }
+    public int getNum() {
+        return num;
+    }
+    public void setNum(int num) {
+        this.num = num;
+    }
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = 1;
+        result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());
+        return result;
+    }
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj)
+            return true;
+        if (obj == null)
+            return false;
+        if (getClass() != obj.getClass())
+            return false;
+        Book other = (Book) obj;
+        if (uuid == null) {
+            if (other.uuid != null)
+                return false;
+        } else if (!uuid.equals(other.uuid))
+            return false;
+        return true;
+    }
+    @Override
+    public String toString() {
+        return "Book [uuid=" + uuid + ", name=" + name + ", inPrice=" + inPrice
+                + ", outPrice=" + outPrice + ", num=" + num + "]";
+    }
+}
+
+ +

过度版的:

+ +

先看过度版的:接参后需要强转成对应的bean,因为返回类型是Object。

+ + + +

MyBeanUtils1

+ + + +
package cn.hncu.beanUtils;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Map;
+
+public class MyBeanUtils1 {
+
+    public static Object populate(Class cls ,Map map) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
+        Object obj = null;
+
+        //1、用类反射new出对象
+        obj = cls.newInstance();
+
+        //2 再用类反射对新new的对象设置属性值(必须遵守Java设置规范)--即通过setter方法设置
+        //2.1遍历出所有该类声明的属性
+        Field flds[] = cls.getDeclaredFields();//getDeclaredFields()返回Class中所有的字段,包括私有字段;
+        for(Field fld:flds){
+            //获取该fld对象所代表的属性名
+            String fldName = fld.getName();
+            //根据属性名,到map中去读取数据,只有数据非空才需要给该属性设置值 
+            Object value = map.get(fldName);
+            if(value==null){//如果map中不存在对应的属性数据,我们在这里给出提示信息
+                System.out.println(fldName+"的数据为空");
+            }else{
+                //如果map中存在对应的属性数据,则由属性名得出它的setter方法的名字
+                String mothodName = "set"+fldName.substring(0, 1).toUpperCase()+fldName.substring(1);
+
+                 //根据方法名和参数的数据类型(其实就是属性的类型),获得Method对象
+                Class paramTypes[] = new Class[1];
+                paramTypes[0] = fld.getType();
+                Method method = cls.getDeclaredMethod(mothodName, paramTypes);
+
+                //调用该method对象所代表的方法
+                Object args[] = new Object[1];
+                args[0]=value;
+                method.invoke(obj, args);
+            }
+        }
+        return obj;
+    }
+
+}
+ + + +

测试

+ + + +
@Test
+    public void test1() {
+        Map map = new HashMap();
+        map.put("uuid", "001");
+        map.put("name", "Jack");
+        map.put("age", 20);
+
+        Map map2 = new HashMap();
+        map2.put("uuid", "001");
+        map2.put("name", "红楼梦");
+        map2.put("inPrice", 20.5);
+        //数据可能不全
+        map2.put("num", 123);
+        try {
+            User user =  (User) MyBeanUtils1.populate(User.class, map);
+            System.out.println(user);
+            Book book =  (Book) MyBeanUtils1.populate(Book.class, map2);
+            System.out.println(book);
+        } catch (ReflectiveOperationException e) {
+            e.printStackTrace();
+        }
+    }
+ + + +

测试结果:

+ +

+ +

这个还不是很完善,为什么呢,因为返回类型是Object,每次都要强转,比较麻烦,而且我们传了bean的class对象过去了,完全可以实现不用强转的,这个时候我们就需要用到泛型了。
+而且Map的泛型我们可以确定了,肯定是Map<String,Object>这样的

+ +

好了,学习一下最终版的、

+ +

最终版:

+ + + +

MyBeanUtils

+ + + +
package cn.hncu.beanUtils;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Map;
+
+public class MyBeanUtils {
+
+    public static<T> T populate(Class<T> cls ,Map<String, Object> map) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
+        T obj = null;
+
+        //1、用类反射new出对象
+        obj = cls.newInstance();
+
+        //2 再用类反射对新new的对象设置属性值(必须遵守Java设置规范)--即通过setter方法设置
+        //2.1遍历出所有该类声明的属性
+        Field flds[] = cls.getDeclaredFields();//getDeclaredFields()返回Class中所有的字段,包括私有字段;
+        for(Field fld:flds){
+            //获取该fld对象所代表的属性名
+            String fldName = fld.getName();
+            //根据属性名,到map中去读取数据,只有数据非空才需要给该属性设置值 
+            Object value = map.get(fldName);
+            if(value==null){//如果map中不存在对应的属性数据,我们在这里给出提示信息
+                System.out.println(fldName+"的数据为空");
+            }else{
+                //如果map中存在对应的属性数据,则由属性名得出它的setter方法的名字
+                String mothodName = "set"+fldName.substring(0, 1).toUpperCase()+fldName.substring(1);
+
+                 //根据方法名和参数的数据类型(其实就是属性的类型),获得Method对象
+                Class<?> paramTypes[] = new Class[1];
+                paramTypes[0] = fld.getType();
+                Method method = cls.getDeclaredMethod(mothodName, paramTypes);
+
+                //调用该method对象所代表的方法
+                Object args[] = new Object[1];
+                args[0]=value;
+                method.invoke(obj, args);
+            }
+        }
+        return obj;
+    }
+
+}
+
+ + + +

测试方法:

+ + + +
@Test
+    @SuppressWarnings("unchecked")
+    public void test() {
+        Map<String, Object> map = new HashMap();
+        map.put("uuid", "001");
+        map.put("name", "Jack");
+        map.put("age", 20);
+
+        Map<String, Object> map2 = new HashMap();
+        map2.put("uuid", "001");
+        map2.put("name", "红楼梦");
+        map2.put("inPrice", 20.5);
+        //数据可能不全
+        map2.put("num", 123);
+        try {
+            User user = MyBeanUtils.populate(User.class, map);
+            System.out.println(user);
+            Book book = MyBeanUtils.populate(Book.class, map2);
+            System.out.println(book);
+        } catch (ReflectiveOperationException e) {
+            e.printStackTrace();
+        }
+    }
+ + + +

测试结果:

+ +

+ +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ \ No newline at end of file diff --git a/myBookStore/README.md b/myBookStore/README.md index 010599d..00140fb 100644 --- a/myBookStore/README.md +++ b/myBookStore/README.md @@ -1,48 +1,48 @@ -�������������ϵͳ(��ϰ���ģ���˼��_ϵ�л���) +单机版的书店管理系统(练习设计模块和思想_系列汇总) -��Ŀ��ϰĿ�� �� +项目练习目标 : -1��JavaӦ�ó���������� -2��������������̵Ļ���˼�� -3��Java�������ģʽ�ۺ�Ӧ�� -4�����շֲ�ͽӿڵĻ������ -5������������JavaӦ�ó�����ṹ -6���ۺ�Ӧ��JSE��ѧϰ��֪ʶ -7����Ӧ���к���ʹ�ü��Ͽ�� -8����Ӧ�����ۺ�ʹ��swing�ij������ -9�������ı��ֲ��ʵ�ֻ��� -10��IO�����ļ��Ļ������� -11���������õ�Java���ϰ�� -12����������Java����������������Ĵ������� +1、Java应用程序基本分析 +2、培养面向对象编程的基本思想 +3、Java基本设计模式综合应用 +4、掌握分层和接口的基本设计 +5、构建合理的Java应用程序包结构 +6、综合应用JSE所学习的知识 +7、在应用中合理使用集合框架 +8、在应用中综合使用swing的常用组件 +9、基本的表现层的实现机制 +10、IO流和文件的基本操作 +11、培养良好的Java编程习惯 +12、培养调试Java程序的能力,培养改错的能力 -��Ŀ�������� �� +项目功能需求 : -1���ܽ��в����û���ע�ᣬ�޸Ļ�����Ϣ��ɾ���Ͳ�ѯ�� -2���ܶ�ͼ��Ļ�����Ϣ�������ӡ�ɾ�����޸ĺͲ�ѯ������ -3������д��������һ�Ž��������ж�������Ľ�����Ϣ���������鼮������ͼ����������Ѿ��еģ�������ͬʱ�޸Ŀ���Ӧ�鼮�Ĵ������ -4������д���۵���һ�����۵����ж��������������Ϣ�����۵��鼮������ͼ����������Ѿ��еģ��������۵��������ܳ�����ǰ�������������۵�ͬʱ�޸Ŀ���Ӧ�鼮�Ĵ������ -5�����Բ鿴������ϸ�����԰����������в��Ҿ����ͼ��Ŀ��ֵ�� -6��Ȩ�޷�����м򻯣����̶���Ȩ�޿��ơ����û�����ģ��ֳɲ�ͬ����Ȩ�޵���Ա������һ��admin���û������Բ���ȫ���Ĺ��ܡ� +1、能进行操作用户的注册,修改基本信息,删除和查询。 +2、能对图书的基本信息进行增加、删除、修改和查询操作。 +3、能填写进货单,一张进货单带有多条具体的进货信息,进货的书籍必须是图书管理里面已经有的;进货的同时修改库存对应书籍的存货量。 +4、能填写销售单,一张销售单带有多条具体的销售信息,销售的书籍必须是图书管理里面已经有的,而且销售的数量不能超过当前库存的数量;销售的同时修改库存对应书籍的存货量。 +5、可以查看库存的明细,可以按照条件进行查找具体的图书的库存值。 +6、权限方面进行简化,做固定的权限控制。把用户按照模块分成不同操作权限的人员,特设一个admin的用户,可以操作全部的功能。 -��Ŀ������� �� +项目基本设计 : -�� �ܹ���� -�����ܡ�ģ�黮�� -ģ�黮�֣��û���ͼ�顢���������ۺͿ��5��ģ�� +★ 架构设计 +整体框架、模块划分 +模块划分:用户、图书、进货、销售和库存5个模块 -�� ϵͳ���ܽṹ��� -ÿ������ģ��ľ��幦����ģ�� +★ 系统功能结构设计 +每个功能模块的具体功能子模块 -�� ���ݿ���� -��Ŀ���ʵ�֣���ģ�顢�ֲ㡢�ְ�������Ӧ�ó��� +★ 数据库设计 +项目框架实现:分模块、分层、分包、构建应用程序 -�Լ����ܽ᣺ +自己的总结: -�����˵���Լ��ĵ�һ����Ŀ�ɡ�С��Ŀ��O(��_��)O����~�� -д������Ҳ��10�����ˣ��Լ��Ƚ�����д��Ŀ��������̣�������Ϊ�����Ŀ�Ǹ�����ʦָ�������ģ������أ��Լ��ĸд������Ǻ���������ڶԷְ�����ȡ���ְ���ֵ�����װ������������������ӿڱ�̰������ֲ㣬�߼��㣬���ݲ㰡����Щ��ǰ�ö�û�ù��ģ���ʱ����ȫ��������ô���£��������Լ�д��֮�󣬸о��Ҳ����ô���¡� -O(��_��)O~��������Ŀ���������ǵ��Լ��������֣�д�ö��ˣ��Լ������ˡ� -�Ժ�����ֵ������� +这可以说是自己的第一个项目吧。小项目。O(∩_∩)O哈哈~、 +写到现在也有10多天了,自己比较享受写项目的这个过程,不过因为这个项目是跟着老师指导来做的,所以呢,自己的感触还不是很深,不过现在对分包啊,取名字啊,值对象封装啊,工厂方法,面向接口编程啊,表现层,逻辑层,数据层啊,这些以前用都没用过的,那时候完全不懂得怎么回事,不过在自己写了之后,感觉嘛、也就那么回事。 +O(∩_∩)O~,这种项目开发,还是得自己多练练手,写得多了,自己就熟了。 +以后就是手到擒来。 -CSDN���͵�ַ�� +CSDN博客地址: http://blog.csdn.net/qq_26525215/article/details/51202656 \ No newline at end of file diff --git a/myDbPoolUse/README.md b/myDbPoolUse/README.md index e42194c..82750f8 100644 --- a/myDbPoolUse/README.md +++ b/myDbPoolUse/README.md @@ -1,3 +1,3 @@ -BasicDataSource����DataSource(DBCP���ӳ�����) -ComboPooledDataSource(C3P0���ӳ�����) -Apache��DBUtils���ʹ�� \ No newline at end of file +BasicDataSource创建DataSource(DBCP连接池配置) +ComboPooledDataSource(C3P0连接池配置) +Apache的DBUtils框架使用 \ No newline at end of file diff --git a/myLog4jTest/.classpath b/myLog4jTest/.classpath new file mode 100644 index 0000000..61d7608 --- /dev/null +++ b/myLog4jTest/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/myLog4jTest/.project b/myLog4jTest/.project new file mode 100644 index 0000000..8500302 --- /dev/null +++ b/myLog4jTest/.project @@ -0,0 +1,17 @@ + + + myLog4jTest + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/myLog4jTest/.settings/org.eclipse.core.resources.prefs b/myLog4jTest/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..d6f4f95 --- /dev/null +++ b/myLog4jTest/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,3 @@ +#Tue Aug 23 11:03:29 CST 2016 +eclipse.preferences.version=1 +encoding//src/log4j.properties=UTF-8 diff --git a/myLog4jTest/.settings/org.eclipse.jdt.core.prefs b/myLog4jTest/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..59ae85f --- /dev/null +++ b/myLog4jTest/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +#Tue Aug 23 00:48:21 CST 2016 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git "a/myLog4jTest/Log4j\345\237\272\346\234\254\344\275\277\347\224\250\350\257\246\350\247\243\344\270\216\345\272\224\347\224\250\344\272\216Java\347\232\204\345\256\236\344\276\213(1).html" "b/myLog4jTest/Log4j\345\237\272\346\234\254\344\275\277\347\224\250\350\257\246\350\247\243\344\270\216\345\272\224\347\224\250\344\272\216Java\347\232\204\345\256\236\344\276\213(1).html" new file mode 100644 index 0000000..93a8e0c --- /dev/null +++ "b/myLog4jTest/Log4j\345\237\272\346\234\254\344\275\277\347\224\250\350\257\246\350\247\243\344\270\216\345\272\224\347\224\250\344\272\216Java\347\232\204\345\256\236\344\276\213(1).html" @@ -0,0 +1,201 @@ + + + + + +Log4j基本使用详解与应用于Java的实例 + + + +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ + + +

log4j介绍

+ +

Log4j,具体的我就不去拷贝官网的介绍了,大家只要知道这是帮助我们记录日志的就可以了。

+ +

作用就是这2个:
+1、跟踪代码的运行轨迹。
+2、输出调试信息

+ +

很简单,但是真的很实用的一个工具!不需要很深入的去了解,但是必须知道如何使用,如何通过Log4j去记录日志,这是必须的!

+ +

在这里,通过一个实例来演示如何使用log4j,以及如何配置log4j的配置文件。

+ + + +

log4j-jar包:

+ +

首先,我们需要准备一个Log4j的jar包,不多说,直接上链接:
+版本为:log4j-1.2.17.(2016.8.22下载的最先版本)’

+ +
+点我去下载log4j-1.2.17-jar包 +
+ +

三大组成就是如下三个类:
+1、Logger类-生成日志。
+2、Appender类-定义日志输出的目的地。
+3、Layout类-指定日志输出的格式。

+ + + +

了解一下Logger组件:

+ +

日志共分为5种级别(ON开,OFF关这两个不计算在内),从高到底(从严重到轻微)排序为:

+ +

FATAL—严重的错误,可能会导致程序不能正常运行. 类似System.exit(),整个项目都不能运行
+ ERROR – 错误,影响程序的正常运行。 类似当前线程挂了,但其它线程或组件还在跑
+ WARN – 警告,不会影响程序的运行。最好将此问题修正。
+ INFO – 一般信息。不影响程序的运行。可能是用户的调试信息。可有可无。等同于system.err.
+ DEBUG – 一般的信息。等同于system.out

+ +

上面五种级别分别对应以下几个方法(Java中调用,等会会演示)
+ fatal(Object)
+ error(Object)
+ warn(Object)
+ info(Object)
+ debug(Object)
+当信息大于或是等于配置的级别时才会输出日志。

+ + + +

Appender组件

+ +

我们只要记住下面这2个就可以了:

+ +

Console—控制台–org.apache.log4j.ConsoleAppender
+File—文件–org.apache.log4j.FileAppender , org.apache.log4j.RollingFileAppender

+ + + +

Layout组件

+ +

功能是定义日志的输出格式
+ org.apache.log4j.HTMLLayout
+ org.apache.log4j.PatternLayout (自定义)
+ org.apache.log4j.SimpleLayout

+ +

就是输出到日志的时候,用哪种格式输出,理解成正则表达式就好了。

+ +

有一些转义是他规定好的,我这里列出一些,不用全部都记下来,了解就行了,然后记一个常用的匹配格式就OK!

+ +

只解释自定义格式PatternLayout:

+ + + +
%d – 具体的时间. %d{yyyy MMM dd HH:mm:ss,SSS}
+        输出类似:输出类似:2016年8月21日 00:00:00,921
+%p – 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL 
+%c – 输出所属的类目,通常就是所在类的全名 -Logger.getLogger(name) 其实就是输出这个name,所以,我们这里一般用当前类的class。
+%L(这是大写的L) — 只输出行号
+%l - 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。举例:(Log4jDemo.java:13)
+%m – 输出代码中指定的消息-我们指定的
+%n —换行符-Windows平台为“\r\n”,Unix平台为“\n” 
+%r   输出自应用启动到输出该log信息耗费的毫秒数 
+%t   输出产生该日志事件的线程名
+ + + +

配置文件的一个模板:

+ +

在src/bin目录下(即WEB-INF/classes)建立一个log4j.properties文件.

+ +

在WEB-INF/classes目录下,为log4j的默认目录。Log4j.properties也是log4j的默认文件名。

+ +
#####配置根元素
+log4j.rootLogger=INFO,console,file
+#存储INFO以及以上级别的记录
+#file的输入地址为文件
+#console表示输出到控制台
+log4j.appender.file=org.apache.log4j.RollingFileAppender
+#以下是具体的目录
+log4j.appender.file.File=d:/a/test.log
+#每个文件的最大大小
+log4j.appender.file.MaxFileSize=20KB
+#最多可以是多少个文件
+log4j.appender.file.MaxBackupIndex=3
+#信息的布局格式-按指定的格式打出
+log4j.appender.file.layout=org.apache.log4j.PatternLayout
+#具体的布局格式 - %d为时间
+#log4j.appender.file.layout.ConversionPattern=%d %p [%c] %m %l %n
+log4j.appender.file.layout.ConversionPattern=%d %p [%l]\:%m -%t%n 
+
+#以下配置输出到控制台的配置
+log4j.appender.console=org.apache.log4j.ConsoleAppender
+log4j.appender.console.layout=org.apache.log4j.PatternLayout
+#log4j.appender.console.layout.ConversionPattern=%d %p [%c] %m%n
+log4j.appender.console.layout.ConversionPattern=%d %p [%l]\:%m -%t%n 
+ + + +

演示实例:

+ + + +
package cn.hncu.lib;
+
+import org.apache.log4j.Logger;
+/**
+ * @author 陈浩翔
+ *
+ * 2016-8-23
+ */
+public class Log4jDemo {
+    public static void main(String[] args) {
+        //日志的名字是传入的任何字符串,通常为类名或包名
+        Logger log = Logger.getLogger(Log4jDemo.class);
+
+        for(int i=0;i<10;i++){
+            log.fatal("严重错误信息:"+i);
+            log.error("错误信息:"+i);
+            log.warn("警告信息:"+i);
+            log.info("一般信息:"+i);
+            log.debug("调试信息:"+i);
+        }
+    }
+}
+
+ +

演示结果:

+ + + +

控制台输出:

+ +

+ + + +

文件输出:

+ +

+ +

是不是很简单,配置好文件之后,我们在Java中用,只需要2步。
+1、Logger log = Logger.getLogger(****.class);
+2、随意调用下面5个方法:

+ + + +
log.fatal();
+log.error();
+log.warn();
+log.info();
+log.debug();
+参数是Object类型!在日志中用%m来代表我们这里传的值的toString()。
+ +

如果要去更加详细了解的,可以去Log4j官网:

+ +
+

Log4j官网

+
+ +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ \ No newline at end of file diff --git a/myLog4jTest/README.md b/myLog4jTest/README.md new file mode 100644 index 0000000..151d905 --- /dev/null +++ b/myLog4jTest/README.md @@ -0,0 +1,201 @@ + + + + + +Log4j基本使用详解与应用于Java的实例 + + + +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ + + +

log4j介绍

+ +

Log4j,具体的我就不去拷贝官网的介绍了,大家只要知道这是帮助我们记录日志的就可以了。

+ +

作用就是这2个:
+1、跟踪代码的运行轨迹。
+2、输出调试信息

+ +

很简单,但是真的很实用的一个工具!不需要很深入的去了解,但是必须知道如何使用,如何通过Log4j去记录日志,这是必须的!

+ +

在这里,通过一个实例来演示如何使用log4j,以及如何配置log4j的配置文件。

+ + + +

log4j-jar包:

+ +

首先,我们需要准备一个Log4j的jar包,不多说,直接上链接:
+版本为:log4j-1.2.17.(2016.8.22下载的最先版本)’

+ +
+点我去下载log4j-1.2.17-jar包 +
+ +

三大组成就是如下三个类:
+1、Logger类-生成日志。
+2、Appender类-定义日志输出的目的地。
+3、Layout类-指定日志输出的格式。

+ + + +

了解一下Logger组件:

+ +

日志共分为5种级别(ON开,OFF关这两个不计算在内),从高到底(从严重到轻微)排序为:

+ +

FATAL—严重的错误,可能会导致程序不能正常运行. 类似System.exit(),整个项目都不能运行
+ ERROR – 错误,影响程序的正常运行。 类似当前线程挂了,但其它线程或组件还在跑
+ WARN – 警告,不会影响程序的运行。最好将此问题修正。
+ INFO – 一般信息。不影响程序的运行。可能是用户的调试信息。可有可无。等同于system.err.
+ DEBUG – 一般的信息。等同于system.out

+ +

上面五种级别分别对应以下几个方法(Java中调用,等会会演示)
+ fatal(Object)
+ error(Object)
+ warn(Object)
+ info(Object)
+ debug(Object)
+当信息大于或是等于配置的级别时才会输出日志。

+ + + +

Appender组件

+ +

我们只要记住下面这2个就可以了:

+ +

Console—控制台–org.apache.log4j.ConsoleAppender
+File—文件–org.apache.log4j.FileAppender , org.apache.log4j.RollingFileAppender

+ + + +

Layout组件

+ +

功能是定义日志的输出格式
+ org.apache.log4j.HTMLLayout
+ org.apache.log4j.PatternLayout (自定义)
+ org.apache.log4j.SimpleLayout

+ +

就是输出到日志的时候,用哪种格式输出,理解成正则表达式就好了。

+ +

有一些转义是他规定好的,我这里列出一些,不用全部都记下来,了解就行了,然后记一个常用的匹配格式就OK!

+ +

只解释自定义格式PatternLayout:

+ + + +
%d – 具体的时间. %d{yyyy MMM dd HH:mm:ss,SSS}
+        输出类似:输出类似:2016年8月21日 00:00:00,921
+%p – 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL 
+%c – 输出所属的类目,通常就是所在类的全名 -Logger.getLogger(name) 其实就是输出这个name,所以,我们这里一般用当前类的class。
+%L(这是大写的L) — 只输出行号
+%l - 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。举例:(Log4jDemo.java:13)
+%m – 输出代码中指定的消息-我们指定的
+%n —换行符-Windows平台为“\r\n”,Unix平台为“\n” 
+%r   输出自应用启动到输出该log信息耗费的毫秒数 
+%t   输出产生该日志事件的线程名
+ + + +

配置文件的一个模板:

+ +

在src/bin目录下(即WEB-INF/classes)建立一个log4j.properties文件.

+ +

在WEB-INF/classes目录下,为log4j的默认目录。Log4j.properties也是log4j的默认文件名。

+ +
#####配置根元素
+log4j.rootLogger=INFO,console,file
+#存储INFO以及以上级别的记录
+#file的输入地址为文件
+#console表示输出到控制台
+log4j.appender.file=org.apache.log4j.RollingFileAppender
+#以下是具体的目录
+log4j.appender.file.File=d:/a/test.log
+#每个文件的最大大小
+log4j.appender.file.MaxFileSize=20KB
+#最多可以是多少个文件
+log4j.appender.file.MaxBackupIndex=3
+#信息的布局格式-按指定的格式打出
+log4j.appender.file.layout=org.apache.log4j.PatternLayout
+#具体的布局格式 - %d为时间
+#log4j.appender.file.layout.ConversionPattern=%d %p [%c] %m %l %n
+log4j.appender.file.layout.ConversionPattern=%d %p [%l]\:%m -%t%n 
+
+#以下配置输出到控制台的配置
+log4j.appender.console=org.apache.log4j.ConsoleAppender
+log4j.appender.console.layout=org.apache.log4j.PatternLayout
+#log4j.appender.console.layout.ConversionPattern=%d %p [%c] %m%n
+log4j.appender.console.layout.ConversionPattern=%d %p [%l]\:%m -%t%n 
+ + + +

演示实例:

+ + + +
package cn.hncu.lib;
+
+import org.apache.log4j.Logger;
+/**
+ * @author 陈浩翔
+ *
+ * 2016-8-23
+ */
+public class Log4jDemo {
+    public static void main(String[] args) {
+        //日志的名字是传入的任何字符串,通常为类名或包名
+        Logger log = Logger.getLogger(Log4jDemo.class);
+
+        for(int i=0;i<10;i++){
+            log.fatal("严重错误信息:"+i);
+            log.error("错误信息:"+i);
+            log.warn("警告信息:"+i);
+            log.info("一般信息:"+i);
+            log.debug("调试信息:"+i);
+        }
+    }
+}
+
+ +

演示结果:

+ + + +

控制台输出:

+ +

+ + + +

文件输出:

+ +

+ +

是不是很简单,配置好文件之后,我们在Java中用,只需要2步。
+1、Logger log = Logger.getLogger(****.class);
+2、随意调用下面5个方法:

+ + + +
log.fatal();
+log.error();
+log.warn();
+log.info();
+log.debug();
+参数是Object类型!在日志中用%m来代表我们这里传的值的toString()。
+ +

如果要去更加详细了解的,可以去Log4j官网:

+ +
+

Log4j官网

+
+ +
+

转载请注明出处:http://blog.csdn.net/qq_26525215

+本文源自大学之旅_谙忆的博客

+
+ \ No newline at end of file diff --git a/myLog4jTest/bin/cn/hncu/lib/Log4jDemo.class b/myLog4jTest/bin/cn/hncu/lib/Log4jDemo.class new file mode 100644 index 0000000..ab6a02f Binary files /dev/null and b/myLog4jTest/bin/cn/hncu/lib/Log4jDemo.class differ diff --git a/myLog4jTest/bin/cn/hncu/lib/log4j-1.2.17.jar b/myLog4jTest/bin/cn/hncu/lib/log4j-1.2.17.jar new file mode 100644 index 0000000..068867e Binary files /dev/null and b/myLog4jTest/bin/cn/hncu/lib/log4j-1.2.17.jar differ diff --git a/myLog4jTest/bin/log4j.properties b/myLog4jTest/bin/log4j.properties new file mode 100644 index 0000000..e819957 --- /dev/null +++ b/myLog4jTest/bin/log4j.properties @@ -0,0 +1,22 @@ +#####配置根元素 +log4j.rootLogger=INFO,console,file +#存储INFO以及以上级别的记录 +#file的输入地址为文件 +log4j.appender.file=org.apache.log4j.RollingFileAppender +#以下是具体的目录 +log4j.appender.file.File=d:/a/test.log +#每个文件的最大大小 +log4j.appender.file.MaxFileSize=20KB +#最多可以是多少个文件 +log4j.appender.file.MaxBackupIndex=3 +#信息的布局格式-按指定的格式打出 +log4j.appender.file.layout=org.apache.log4j.PatternLayout +#具体的布局格式 - %d为时间 +#log4j.appender.file.layout.ConversionPattern=%d %p [%c] %m %l %n +log4j.appender.file.layout.ConversionPattern=%d %p [%l]\:%m -%t%n + +#以下配置输出到控制台 +log4j.appender.console=org.apache.log4j.ConsoleAppender +log4j.appender.console.layout=org.apache.log4j.PatternLayout +#log4j.appender.console.layout.ConversionPattern=%d %p [%c] %m%n +log4j.appender.console.layout.ConversionPattern=%d %p [%l]\:%m -%t%n \ No newline at end of file diff --git a/myLog4jTest/bin/log4j_1.properties b/myLog4jTest/bin/log4j_1.properties new file mode 100644 index 0000000..cfcb871 --- /dev/null +++ b/myLog4jTest/bin/log4j_1.properties @@ -0,0 +1,4 @@ +log4j.rootLogger=DEBUG,console +log4j.appender.console=org.apache.log4j.ConsoleAppender +log4j.appender.console.layout=org.apache.log4j.PatternLayout +log4j.appender.console.layout.ConversionPattern=%d %p [%c] %m%n diff --git a/myLog4jTest/myLog4jTest.zip b/myLog4jTest/myLog4jTest.zip new file mode 100644 index 0000000..f432ec7 Binary files /dev/null and b/myLog4jTest/myLog4jTest.zip differ diff --git a/myLog4jTest/src/cn/hncu/lib/Log4jDemo.java b/myLog4jTest/src/cn/hncu/lib/Log4jDemo.java new file mode 100644 index 0000000..6fff146 --- /dev/null +++ b/myLog4jTest/src/cn/hncu/lib/Log4jDemo.java @@ -0,0 +1,22 @@ +package cn.hncu.lib; + +import org.apache.log4j.Logger; +/** + * @author 陈浩翔 + * + * 2016-8-23 + */ +public class Log4jDemo { + public static void main(String[] args) { + //日志的名字是传入的任何字符串,通常为类名或包名 + Logger log = Logger.getLogger(Log4jDemo.class); + + for(int i=0;i<10;i++){ + log.fatal("严重错误信息:"+i); + log.error("错误信息:"+i); + log.warn("警告信息:"+i); + log.info("一般信息:"+i); + log.debug("调试信息:"+i); + } + } +} diff --git a/myLog4jTest/src/cn/hncu/lib/log4j-1.2.17.jar b/myLog4jTest/src/cn/hncu/lib/log4j-1.2.17.jar new file mode 100644 index 0000000..068867e Binary files /dev/null and b/myLog4jTest/src/cn/hncu/lib/log4j-1.2.17.jar differ diff --git a/myLog4jTest/src/log4j.properties b/myLog4jTest/src/log4j.properties new file mode 100644 index 0000000..e819957 --- /dev/null +++ b/myLog4jTest/src/log4j.properties @@ -0,0 +1,22 @@ +#####配置根元素 +log4j.rootLogger=INFO,console,file +#存储INFO以及以上级别的记录 +#file的输入地址为文件 +log4j.appender.file=org.apache.log4j.RollingFileAppender +#以下是具体的目录 +log4j.appender.file.File=d:/a/test.log +#每个文件的最大大小 +log4j.appender.file.MaxFileSize=20KB +#最多可以是多少个文件 +log4j.appender.file.MaxBackupIndex=3 +#信息的布局格式-按指定的格式打出 +log4j.appender.file.layout=org.apache.log4j.PatternLayout +#具体的布局格式 - %d为时间 +#log4j.appender.file.layout.ConversionPattern=%d %p [%c] %m %l %n +log4j.appender.file.layout.ConversionPattern=%d %p [%l]\:%m -%t%n + +#以下配置输出到控制台 +log4j.appender.console=org.apache.log4j.ConsoleAppender +log4j.appender.console.layout=org.apache.log4j.PatternLayout +#log4j.appender.console.layout.ConversionPattern=%d %p [%c] %m%n +log4j.appender.console.layout.ConversionPattern=%d %p [%l]\:%m -%t%n \ No newline at end of file diff --git a/myLog4jTest/src/log4j_1.properties b/myLog4jTest/src/log4j_1.properties new file mode 100644 index 0000000..cfcb871 --- /dev/null +++ b/myLog4jTest/src/log4j_1.properties @@ -0,0 +1,4 @@ +log4j.rootLogger=DEBUG,console +log4j.appender.console=org.apache.log4j.ConsoleAppender +log4j.appender.console.layout=org.apache.log4j.PatternLayout +log4j.appender.console.layout.ConversionPattern=%d %p [%c] %m%n diff --git a/myMailWeb/.classpath b/myMailWeb/.classpath new file mode 100644 index 0000000..96c5a3c --- /dev/null +++ b/myMailWeb/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/myMailWeb/.mymetadata b/myMailWeb/.mymetadata new file mode 100644 index 0000000..0758998 --- /dev/null +++ b/myMailWeb/.mymetadata @@ -0,0 +1,13 @@ + + + + + + + diff --git a/myMailWeb/.project b/myMailWeb/.project new file mode 100644 index 0000000..ab0a74a --- /dev/null +++ b/myMailWeb/.project @@ -0,0 +1,58 @@ + + + myMailWeb + + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + com.genuitec.eclipse.j2eedt.core.WebClasspathBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + com.genuitec.eclipse.j2eedt.core.J2EEProjectValidator + + + + + com.genuitec.eclipse.j2eedt.core.DeploymentDescriptorValidator + + + + + org.eclipse.wst.validation.validationbuilder + + + + + com.genuitec.eclipse.ast.deploy.core.DeploymentBuilder + + + + + + com.genuitec.eclipse.ast.deploy.core.deploymentnature + org.eclipse.jem.workbench.JavaEMFNature + com.genuitec.eclipse.j2eedt.core.webnature + org.eclipse.jdt.core.javanature + org.eclipse.wst.jsdt.core.jsNature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.common.modulecore.ModuleCoreNature + + diff --git a/myMailWeb/.settings/.jsdtscope b/myMailWeb/.settings/.jsdtscope new file mode 100644 index 0000000..252e54f --- /dev/null +++ b/myMailWeb/.settings/.jsdtscope @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/myMailWeb/.settings/org.eclipse.jdt.core.prefs b/myMailWeb/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..dda5605 --- /dev/null +++ b/myMailWeb/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Mon Aug 22 10:13:16 CST 2016 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/myMailWeb/.settings/org.eclipse.wst.common.component b/myMailWeb/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..e7bf450 --- /dev/null +++ b/myMailWeb/.settings/org.eclipse.wst.common.component @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/myMailWeb/.settings/org.eclipse.wst.common.project.facet.core.xml b/myMailWeb/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..5a88726 --- /dev/null +++ b/myMailWeb/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/myMailWeb/.settings/org.eclipse.wst.jsdt.ui.superType.container b/myMailWeb/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/myMailWeb/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/myMailWeb/.settings/org.eclipse.wst.jsdt.ui.superType.name b/myMailWeb/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/myMailWeb/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/myMailWeb/README.md b/myMailWeb/README.md new file mode 100644 index 0000000..ee84e84 --- /dev/null +++ b/myMailWeb/README.md @@ -0,0 +1,4 @@ +网站用户注册: +主要实现如下两个功能: +1、用户在网站上注册完成后给用户发一封邮件。 +2、用户通过邮件激活后才可以登录。 \ No newline at end of file diff --git a/myMailWeb/WebRoot/META-INF/MANIFEST.MF b/myMailWeb/WebRoot/META-INF/MANIFEST.MF new file mode 100644 index 0000000..254272e --- /dev/null +++ b/myMailWeb/WebRoot/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/myMailWeb/WebRoot/WEB-INF/classes/c3p0-config.xml b/myMailWeb/WebRoot/WEB-INF/classes/c3p0-config.xml new file mode 100644 index 0000000..1316316 --- /dev/null +++ b/myMailWeb/WebRoot/WEB-INF/classes/c3p0-config.xml @@ -0,0 +1,21 @@ + + + + com.mysql.jdbc.Driver + + + + root + 1234 + + 2 + + 30 + + 10 + + 2 + + 50 + + diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/domain/User.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/domain/User.class new file mode 100644 index 0000000..96f0a3c Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/domain/User.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/filter/CharsetFilter.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/filter/CharsetFilter.class new file mode 100644 index 0000000..c6b09ca Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/filter/CharsetFilter.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/login/dao/LoginDAO.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/login/dao/LoginDAO.class new file mode 100644 index 0000000..317489c Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/login/dao/LoginDAO.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/login/dao/LoginDaoJdbc.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/login/dao/LoginDaoJdbc.class new file mode 100644 index 0000000..df4dbdd Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/login/dao/LoginDaoJdbc.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/login/service/ILoginService.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/login/service/ILoginService.class new file mode 100644 index 0000000..90f0bd5 Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/login/service/ILoginService.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/login/service/LoginServiceImpl.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/login/service/LoginServiceImpl.class new file mode 100644 index 0000000..bc26372 Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/login/service/LoginServiceImpl.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/login/servlet/LoginServlet.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/login/servlet/LoginServlet.class new file mode 100644 index 0000000..b4cc712 Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/login/servlet/LoginServlet.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/pubs/C3p0Pool.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/pubs/C3p0Pool.class new file mode 100644 index 0000000..d9cad80 Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/pubs/C3p0Pool.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/dao/RegDAO.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/dao/RegDAO.class new file mode 100644 index 0000000..10d14ba Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/dao/RegDAO.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/dao/RegDaoJdbc.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/dao/RegDaoJdbc.class new file mode 100644 index 0000000..64c978c Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/dao/RegDaoJdbc.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/sendMail/MySendMailThread$1.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/sendMail/MySendMailThread$1.class new file mode 100644 index 0000000..da16dd2 Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/sendMail/MySendMailThread$1.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/sendMail/MySendMailThread.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/sendMail/MySendMailThread.class new file mode 100644 index 0000000..d20e1f4 Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/sendMail/MySendMailThread.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/service/IRegService.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/service/IRegService.class new file mode 100644 index 0000000..9450682 Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/service/IRegService.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/service/RegServiceImpl.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/service/RegServiceImpl.class new file mode 100644 index 0000000..ce57f15 Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/service/RegServiceImpl.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/servlet/ActiveServlet.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/servlet/ActiveServlet.class new file mode 100644 index 0000000..6f0fae5 Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/servlet/ActiveServlet.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/servlet/RegServlet.class b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/servlet/RegServlet.class new file mode 100644 index 0000000..1297f53 Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/classes/cn/hncu/reg/servlet/RegServlet.class differ diff --git a/myMailWeb/WebRoot/WEB-INF/lib/activation-1.1.0.jar b/myMailWeb/WebRoot/WEB-INF/lib/activation-1.1.0.jar new file mode 100644 index 0000000..589b674 Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/lib/activation-1.1.0.jar differ diff --git a/myMailWeb/WebRoot/WEB-INF/lib/c3p0-0.9.1.2.jar b/myMailWeb/WebRoot/WEB-INF/lib/c3p0-0.9.1.2.jar new file mode 100644 index 0000000..03e68c7 Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/lib/c3p0-0.9.1.2.jar differ diff --git a/myMailWeb/WebRoot/WEB-INF/lib/commons-dbutils-1.4.jar b/myMailWeb/WebRoot/WEB-INF/lib/commons-dbutils-1.4.jar new file mode 100644 index 0000000..7b846ea Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/lib/commons-dbutils-1.4.jar differ diff --git a/myMailWeb/WebRoot/WEB-INF/lib/java-mail-1.4.4.jar b/myMailWeb/WebRoot/WEB-INF/lib/java-mail-1.4.4.jar new file mode 100644 index 0000000..9d60d13 Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/lib/java-mail-1.4.4.jar differ diff --git a/myMailWeb/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.34-bin.jar b/myMailWeb/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.34-bin.jar new file mode 100644 index 0000000..0236900 Binary files /dev/null and b/myMailWeb/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.34-bin.jar differ diff --git a/myMailWeb/WebRoot/WEB-INF/web.xml b/myMailWeb/WebRoot/WEB-INF/web.xml new file mode 100644 index 0000000..eeb9775 --- /dev/null +++ b/myMailWeb/WebRoot/WEB-INF/web.xml @@ -0,0 +1,53 @@ + + + + + + charset + cn.hncu.filter.CharsetFilter + + charset + utf-8 + + + + charset + /* + + + RegServlet + cn.hncu.reg.servlet.RegServlet + + + ActiveServlet + cn.hncu.reg.servlet.ActiveServlet + + + LoginServlet + cn.hncu.login.servlet.LoginServlet + + + + + + RegServlet + /RegServlet + + + ActiveServlet + /ActiveServlet + + + LoginServlet + /LoginServlet + + + + + index.jsp + + diff --git a/myMailWeb/WebRoot/index.jsp b/myMailWeb/WebRoot/index.jsp new file mode 100644 index 0000000..140c28e --- /dev/null +++ b/myMailWeb/WebRoot/index.jsp @@ -0,0 +1,43 @@ +<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> +<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> + + + + 带邮箱激活的注册模块 + + + + + + + + 登录失败! + + + + +
+ 姓名:
+ 密码:
+ 邮箱:-登录不用填写邮箱
+   +   + +
+
+ + 登录成功
+ 欢迎你,亲爱的${user.name} +
+ + diff --git a/myMailWeb/WebRoot/jsps/result.jsp b/myMailWeb/WebRoot/jsps/result.jsp new file mode 100644 index 0000000..f8c231d --- /dev/null +++ b/myMailWeb/WebRoot/jsps/result.jsp @@ -0,0 +1,57 @@ +<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> +<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> + + + + 带邮箱激活的注册模块 + + + + + + + + 服务器异常,请重新激活!
+ 登录 +
+
+
+
+ + 激活地址错误,请使用正确的激活地址!
+ 登录 +
+
+
+
+ + 你已经激活过,请勿重复激活!
+ 登录 +
+
+
+
+ + 激活成功,欢迎去登录!
+ 登录 +
+
+
+
+ + diff --git a/myMailWeb/WebRoot/sql/user.sql b/myMailWeb/WebRoot/sql/user.sql new file mode 100644 index 0000000..04c1ce4 --- /dev/null +++ b/myMailWeb/WebRoot/sql/user.sql @@ -0,0 +1,8 @@ +create table users( + id varchar(32) primary key, + name varchar(30), + pwd varchar(32), + email varchar(80), + active char(1), + acode varchar(32) +); \ No newline at end of file diff --git a/myMailWeb/myMailWeb.zip b/myMailWeb/myMailWeb.zip new file mode 100644 index 0000000..04dd4af Binary files /dev/null and b/myMailWeb/myMailWeb.zip differ diff --git a/myMailWeb/src/c3p0-config.xml b/myMailWeb/src/c3p0-config.xml new file mode 100644 index 0000000..1316316 --- /dev/null +++ b/myMailWeb/src/c3p0-config.xml @@ -0,0 +1,21 @@ + + + + com.mysql.jdbc.Driver + + + + root + 1234 + + 2 + + 30 + + 10 + + 2 + + 50 + + diff --git a/myMailWeb/src/cn/hncu/domain/User.java b/myMailWeb/src/cn/hncu/domain/User.java new file mode 100644 index 0000000..7403939 --- /dev/null +++ b/myMailWeb/src/cn/hncu/domain/User.java @@ -0,0 +1,84 @@ +package cn.hncu.domain; + +public class User { + private String id; + private String name; + private String pwd; + private String email; + private String active; + private String acode; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPwd() { + return pwd; + } + + public void setPwd(String pwd) { + this.pwd = pwd; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getActive() { + return active; + } + + public void setActive(String active) { + this.active = active; + } + + public String getAcode() { + return acode; + } + + public void setAcode(String acode) { + this.acode = acode; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + User other = (User) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } + +} diff --git a/myMailWeb/src/cn/hncu/filter/CharsetFilter.java b/myMailWeb/src/cn/hncu/filter/CharsetFilter.java new file mode 100644 index 0000000..7a0f0d3 --- /dev/null +++ b/myMailWeb/src/cn/hncu/filter/CharsetFilter.java @@ -0,0 +1,34 @@ +package cn.hncu.filter; + +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 CharsetFilter implements Filter{ + + private String charset=null; + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + charset = filterConfig.getInitParameter("charset"); + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + request.setCharacterEncoding(charset); + response.setContentType("text/html;charset="+charset); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + + } + +} diff --git a/myMailWeb/src/cn/hncu/login/dao/LoginDAO.java b/myMailWeb/src/cn/hncu/login/dao/LoginDAO.java new file mode 100644 index 0000000..f31f63e --- /dev/null +++ b/myMailWeb/src/cn/hncu/login/dao/LoginDAO.java @@ -0,0 +1,7 @@ +package cn.hncu.login.dao; + +import cn.hncu.domain.User; + +public interface LoginDAO { + public User login(User u); +} diff --git a/myMailWeb/src/cn/hncu/login/dao/LoginDaoJdbc.java b/myMailWeb/src/cn/hncu/login/dao/LoginDaoJdbc.java new file mode 100644 index 0000000..bafbafa --- /dev/null +++ b/myMailWeb/src/cn/hncu/login/dao/LoginDaoJdbc.java @@ -0,0 +1,24 @@ +package cn.hncu.login.dao; + +import java.sql.SQLException; + +import org.apache.commons.dbutils.QueryRunner; +import org.apache.commons.dbutils.handlers.BeanHandler; +import org.apache.commons.dbutils.handlers.BeanListHandler; + +import cn.hncu.domain.User; +import cn.hncu.pubs.C3p0Pool; + +public class LoginDaoJdbc implements LoginDAO{ + public User login(User u){ + String sql = "select * from users where name=? and pwd=? and active='1' "; + QueryRunner run = new QueryRunner(C3p0Pool.getDataSource()); + try { + User user = run.query(sql, new BeanHandler(User.class) , u.getName(),u.getPwd()); + return user; + } catch (SQLException e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/myMailWeb/src/cn/hncu/login/service/ILoginService.java b/myMailWeb/src/cn/hncu/login/service/ILoginService.java new file mode 100644 index 0000000..3d37248 --- /dev/null +++ b/myMailWeb/src/cn/hncu/login/service/ILoginService.java @@ -0,0 +1,7 @@ +package cn.hncu.login.service; + +import cn.hncu.domain.User; + +public interface ILoginService { + public User login(User u); +} diff --git a/myMailWeb/src/cn/hncu/login/service/LoginServiceImpl.java b/myMailWeb/src/cn/hncu/login/service/LoginServiceImpl.java new file mode 100644 index 0000000..359e011 --- /dev/null +++ b/myMailWeb/src/cn/hncu/login/service/LoginServiceImpl.java @@ -0,0 +1,14 @@ +package cn.hncu.login.service; + +import cn.hncu.domain.User; +import cn.hncu.login.dao.LoginDAO; +import cn.hncu.login.dao.LoginDaoJdbc; + +public class LoginServiceImpl implements ILoginService { + // 注入 + private LoginDAO dao = new LoginDaoJdbc(); + + public User login(User u) { + return dao.login(u); + } +} diff --git a/myMailWeb/src/cn/hncu/login/servlet/LoginServlet.java b/myMailWeb/src/cn/hncu/login/servlet/LoginServlet.java new file mode 100644 index 0000000..cd2eafd --- /dev/null +++ b/myMailWeb/src/cn/hncu/login/servlet/LoginServlet.java @@ -0,0 +1,56 @@ +package cn.hncu.login.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import cn.hncu.domain.User; +import cn.hncu.login.service.ILoginService; +import cn.hncu.login.service.LoginServiceImpl; + +public class LoginServlet extends HttpServlet { + //注入 + private ILoginService service = new LoginServiceImpl(); + + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + doPost(request, response); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + PrintWriter out = response.getWriter(); + String path = request.getContextPath()+"/index.jsp"; + + String name = request.getParameter("name"); + String pwd = request.getParameter("pwd"); + User user = new User(); + user.setName(name); + user.setPwd(pwd); + + // 防范一下(这里可用ajax在前台也防范一下) + if (name == null || name.trim().length() <= 0) { + out.println("用户名不能为空,请重新输入!"); + out.println("返回登录页
"); + return; + } + if (pwd == null || pwd.trim().length() <= 0) { + out.println("密码不能为空,请重新输入!"); + out.println("返回登录页
"); + return; + } + user = service.login(user); + if (user == null) { + request.getSession().setAttribute("error", "1"); + } else { + request.getSession().setAttribute("user", user); + } + response.sendRedirect(request.getContextPath() + "/index.jsp"); + } + +} diff --git a/myMailWeb/src/cn/hncu/pubs/C3p0Pool.java b/myMailWeb/src/cn/hncu/pubs/C3p0Pool.java new file mode 100644 index 0000000..83bc6a3 --- /dev/null +++ b/myMailWeb/src/cn/hncu/pubs/C3p0Pool.java @@ -0,0 +1,32 @@ +package cn.hncu.pubs; + +import java.sql.Connection; +import java.sql.SQLException; + +import javax.sql.DataSource; + +import com.mchange.v2.c3p0.ComboPooledDataSource; + +//我们的这个包装,只是为了把c3p0池做成让每个线程(客户端)获得的是同一个连接,方便做b/s框架下的事务 +public class C3p0Pool { + + private static DataSource pool; + private static ThreadLocal t = new ThreadLocal(); + static { + pool = new ComboPooledDataSource(); + } + + public static DataSource getDataSource() { + return pool; + } + + public static Connection getConnection() throws SQLException { + Connection con = t.get(); + if(con==null){ + con = pool.getConnection(); + t.set(con); + } + return con; + } + +} diff --git a/myMailWeb/src/cn/hncu/reg/dao/RegDAO.java b/myMailWeb/src/cn/hncu/reg/dao/RegDAO.java new file mode 100644 index 0000000..8f25a54 --- /dev/null +++ b/myMailWeb/src/cn/hncu/reg/dao/RegDAO.java @@ -0,0 +1,8 @@ +package cn.hncu.reg.dao; + +import cn.hncu.domain.User; + +public interface RegDAO { + public User reg(User user); + public int active(String acode); +} diff --git a/myMailWeb/src/cn/hncu/reg/dao/RegDaoJdbc.java b/myMailWeb/src/cn/hncu/reg/dao/RegDaoJdbc.java new file mode 100644 index 0000000..4afbdee --- /dev/null +++ b/myMailWeb/src/cn/hncu/reg/dao/RegDaoJdbc.java @@ -0,0 +1,59 @@ +package cn.hncu.reg.dao; + +import java.sql.SQLException; +import java.util.UUID; + +import org.apache.commons.dbutils.QueryRunner; +import org.apache.commons.dbutils.handlers.ScalarHandler; + +import cn.hncu.domain.User; +import cn.hncu.pubs.C3p0Pool; + +public class RegDaoJdbc implements RegDAO { + @Override + public User reg(User user) { + String sql = "insert into users(id,name,pwd,email,active,acode) values(?,?,?,?,?,?)"; + QueryRunner run = new QueryRunner(C3p0Pool.getDataSource()); + String id = UUID.randomUUID().toString().replaceAll("-", ""); + String acode = UUID.randomUUID().toString().replaceAll("-", ""); + try { + run.update(sql, id, user.getName(), user.getPwd(), user.getEmail(), + "0", acode); + user.setId(id); + user.setAcode(acode); + user.setActive("0"); + } catch (SQLException e) { + e.printStackTrace(); + return null; + } + return user; + } + + @Override + public int active(String acode) { + + QueryRunner run = new QueryRunner(C3p0Pool.getDataSource()); + + String sql = "select count(1) from users where acode=? and active='0'"; + + try { + int count =Integer.parseInt(""+run.query(sql, new ScalarHandler(), acode)); + if (count == 0) { + sql = "select count(1) from users where acode=? and active='1'"; + count = Integer.parseInt(""+run.query(sql, new ScalarHandler(), acode)); + if(count==1){ + return 1;//已经注册过了 + }else{ + return 0;//没有对应的acode + } + } else { + sql = "update users set active ='1' where acode=?"; + run.update(sql, acode); + return 2;//成功注册 + } + } catch (SQLException e) { + e.printStackTrace(); + return -1;//出异常 + } + } +} diff --git a/myMailWeb/src/cn/hncu/reg/sendMail/MySendMailThread.java b/myMailWeb/src/cn/hncu/reg/sendMail/MySendMailThread.java new file mode 100644 index 0000000..73301b1 --- /dev/null +++ b/myMailWeb/src/cn/hncu/reg/sendMail/MySendMailThread.java @@ -0,0 +1,105 @@ +package cn.hncu.reg.sendMail; + +import java.security.GeneralSecurityException; +import java.util.Properties; + +import javax.mail.Authenticator; +import javax.mail.Message.RecipientType; +import javax.mail.MessagingException; +import javax.mail.PasswordAuthentication; +import javax.mail.Session; +import javax.mail.Transport; +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; + +import com.sun.mail.util.MailSSLSocketFactory; + +import cn.hncu.domain.User; + +public class MySendMailThread extends Thread { + + private User user = null; + + public MySendMailThread(User user) { + this.user = user; + } + + @Override + public void run() { + + // 跟smtp服务器建立一个连接 + Properties p = new Properties(); + // 设置邮件服务器主机名 + p.setProperty("mail.host", "smtp.qq.com");// 指定邮件服务器,默认端口 25 + // 发送服务器需要身份验证 + p.setProperty("mail.smtp.auth", "true");// 要采用指定用户名密码的方式去认证 + // 发送邮件协议名称 + p.setProperty("mail.transport.protocol", "smtp"); + + // 开启SSL加密,否则会失败 + MailSSLSocketFactory sf = null; + try { + sf = new MailSSLSocketFactory(); + } catch (GeneralSecurityException e1) { + e1.printStackTrace(); + } + sf.setTrustAllHosts(true); + p.put("mail.smtp.ssl.enable", "true"); + p.put("mail.smtp.ssl.socketFactory", sf); + + // 开启debug调试,以便在控制台查看 + // session.setDebug(true);也可以这样设置 + // p.setProperty("mail.debug", "true"); + + // 创建session + Session session = Session.getDefaultInstance(p, new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + // 用户名可以用QQ账号也可以用邮箱的别名 + PasswordAuthentication pa = new PasswordAuthentication( + "chenhaoxiang0117", "jnjtrhojpxswbdab"); + // 后面的字符是授权码,用qq密码不行!! + return pa; + } + }); + + session.setDebug(true);// 设置打开调试状态 + + try { + // 声明一个Message对象(代表一封邮件),从session中创建 + MimeMessage msg = new MimeMessage(session); + // 邮件信息封装 + // 1发件人 + msg.setFrom(new InternetAddress("619699629@qq.com")); + // 2收件人 + msg.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail())); + // 3邮件内容:主题、内容 + msg.setSubject(user.getName() + ",欢迎注册***账号,请点击链接激活账号"); + + // StringBuilder是线程不安全的,但是速度快,这里因为只会有这个线程来访问,所以可以用这个 + StringBuilder sbd = new StringBuilder(); + sbd.append(user.getName() + "
欢迎!请确认此邮件地址以激活您的账号。
"); + sbd.append("立即激活
"); + sbd.append("或者点击下面链接:
"); + sbd.append("http://192.168.1.102:8080/myMailWeb/ActiveServlet?acode=" + + user.getAcode() + "
"); + sbd.append("这是一封自动发送的邮件;如果您并未要求但收到这封信件,您不需要进行任何操作。"); + + msg.setContent(sbd.toString(), "text/html;charset=utf-8");// 发html格式的文本 + + // 发送动作 + Transport.send(msg); + + System.out.println("给" + user.getEmail() + "发送邮件成功。"); + } catch (AddressException e) { + e.printStackTrace(); + } catch (MessagingException e) { + e.printStackTrace(); + } + + + } +} diff --git a/myMailWeb/src/cn/hncu/reg/service/IRegService.java b/myMailWeb/src/cn/hncu/reg/service/IRegService.java new file mode 100644 index 0000000..971c5f1 --- /dev/null +++ b/myMailWeb/src/cn/hncu/reg/service/IRegService.java @@ -0,0 +1,8 @@ +package cn.hncu.reg.service; + +import cn.hncu.domain.User; + +public interface IRegService { + public User reg(User user); + public int active(String acode); +} diff --git a/myMailWeb/src/cn/hncu/reg/service/RegServiceImpl.java b/myMailWeb/src/cn/hncu/reg/service/RegServiceImpl.java new file mode 100644 index 0000000..37156ae --- /dev/null +++ b/myMailWeb/src/cn/hncu/reg/service/RegServiceImpl.java @@ -0,0 +1,16 @@ +package cn.hncu.reg.service; +import cn.hncu.domain.User; +import cn.hncu.reg.dao.RegDAO; +import cn.hncu.reg.dao.RegDaoJdbc; +public class RegServiceImpl implements IRegService{ + //依赖注入 + private RegDAO dao = new RegDaoJdbc(); + @Override + public User reg(User user) { + return dao.reg(user); + } + @Override + public int active(String acode) { + return dao.active(acode); + } +} diff --git a/myMailWeb/src/cn/hncu/reg/servlet/ActiveServlet.java b/myMailWeb/src/cn/hncu/reg/servlet/ActiveServlet.java new file mode 100644 index 0000000..ebd6b02 --- /dev/null +++ b/myMailWeb/src/cn/hncu/reg/servlet/ActiveServlet.java @@ -0,0 +1,50 @@ +package cn.hncu.reg.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.sun.org.apache.bcel.internal.generic.NEW; + +import cn.hncu.reg.service.IRegService; +import cn.hncu.reg.service.RegServiceImpl; + +public class ActiveServlet extends HttpServlet { + + //依赖注入 + IRegService serivce = new RegServiceImpl(); + + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + PrintWriter out = response.getWriter(); + + String acode = request.getParameter("acode"); + + int count = serivce.active(acode); + + request.setAttribute("count", count); + request.getRequestDispatcher("/jsps/result.jsp").forward(request, response); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println(""); + out.println(""); + out.println(" A Servlet"); + out.println(" "); + out.println("不支持post方式访问!!!"); + out.println(" "); + out.println(""); + out.flush(); + out.close(); + } + +} diff --git a/myMailWeb/src/cn/hncu/reg/servlet/RegServlet.java b/myMailWeb/src/cn/hncu/reg/servlet/RegServlet.java new file mode 100644 index 0000000..1182713 --- /dev/null +++ b/myMailWeb/src/cn/hncu/reg/servlet/RegServlet.java @@ -0,0 +1,88 @@ +package cn.hncu.reg.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import cn.hncu.domain.User; +import cn.hncu.reg.sendMail.MySendMailThread; +import cn.hncu.reg.service.IRegService; +import cn.hncu.reg.service.RegServiceImpl; + +public class RegServlet extends HttpServlet { + //依赖注入 + private IRegService service = new RegServiceImpl(); + + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + PrintWriter out = response.getWriter(); + out.println(""); + out.println(""); + out.println(" A Servlet"); + out.println(" "); + out.println("请去注册页面注册!."); + out.println(" "); + out.println(""); + out.flush(); + out.close(); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + PrintWriter out = response.getWriter(); + String path = request.getContextPath()+"/index.jsp"; + + //收集参数 + String name = request.getParameter("name"); + String pwd = request.getParameter("pwd"); + String email = request.getParameter("email"); + + //防范一下(这里可用ajax在前台也防范一下) + if(name==null||name.trim().length()<=0){ + out.println("用户名不能为空,请重新输入!"); + out.println("返回登录页
"); + return; + } + if(pwd==null||pwd.trim().length()<=0){ + out.println("密码不能为空,请重新输入!"); + out.println("返回登录页
"); + return; + } + if(email==null||email.trim().length()<=0){ + out.println("邮箱不能为空,请重新输入!"); + out.println("返回登录页
"); + return; + } + if(email.indexOf("@")==-1){ + out.println("邮箱格式不对,请重新输入!"); + out.println("返回登录页
"); + return; + } + + //组织JavaBean + User user = new User(); + user.setName(name); + user.setPwd(pwd); + user.setEmail(email); + //调用service + user = service.reg(user); + + if(user!=null){ + //发送激活邮件 + //这里有一个小知识点,必须新开一个线程来发邮件,不能把发邮件的动作写在这里 + //如果写在这里,用户的前台显示会等待过长时间,不好! + new MySendMailThread(user).start(); + out.println("您已经注册成功,请去邮箱激活账号后再进行登录,如果没有收到邮件,请稍等!
"); + out.println("返回登录页
"); + + }else{ + out.println("很抱歉,服务器繁忙,注册失败,需要重新注册!"); + } + out.close(); + } +} + diff --git a/myMvcWeb/README.md b/myMvcWeb/README.md index 3e848bb..e62f67a 100644 --- a/myMvcWeb/README.md +++ b/myMvcWeb/README.md @@ -1,13 +1,13 @@ -�ո�ѧ����MVC�������Լ��ĸ��������д��һ��С��Ŀ�� -��ȫ����MVCģʽ��������һ��MVC������ʾ��ͼ�� +刚刚学完了MVC,根据自己的感悟和理解写了一个小项目。 +完全按照MVC模式,后面有一个MVC的理解示意图。 -��MVCģʽ�����������ϵ�˵Ĺ���ϵͳ�� +用MVC模式重新完成了联系人的管理系统: -�û����� -���û�ϵͳ���ṩ�û�ע�ᡢ��¼���ܣ�����û�е�¼���û���������ʹ���κι��ܡ� -���Բ�ѯ�����Ӻ�ɾ����ϵ����Ϣ�� -��ϸ��ƣ� -���ݽṹ��ơ� -����ģ����ơ� -��������ơ� -���������Ŀ��ܡ��������ܣ���ֹ�û��ظ��ύ��ע��͵�¼ʱʹ����֤�롣 \ No newline at end of file +用户需求: +多用户系统,提供用户注册、登录功能,对于没有登录的用户,不允许使用任何功能。 +可以查询、增加和删除联系人信息。 +详细设计: +数据结构设计。 +功能模块设计。 +工具类设计。 +搭建初步的项目框架、其他功能:防止用户重复提交、注册和登录时使用验证码。 \ No newline at end of file diff --git a/myMvcWeb2/README.md b/myMvcWeb2/README.md index f006c41..46fc7be 100644 --- a/myMvcWeb2/README.md +++ b/myMvcWeb2/README.md @@ -1,3 +1,3 @@ -����Ƕ�ǰ�漼����һ��С�ܽ�ɣ��õ��Ĵ�ż����У� -MVC��ܣ���ע�⣬Struts��ܵ�˼�룬��̬�������̹߳�������ThreadLocal��Connection����أ�Properties�ļ���ȡ��EL����ʽ��JSTL��JavaBean��Java����MySQL���ݿ⣬��ɾ�IJ�... +这个是对前面技术的一个小总结吧,用到的大概技术有: +MVC框架,加注解,Struts框架的思想,动态代理,线程管理对象ThreadLocal,Connection对象池,Properties文件读取,EL表达式,JSTL,JavaBean,Java访问MySQL数据库,增删改查... diff --git a/mysql_split_horizon/.idea/compiler.xml b/mysql_split_horizon/.idea/compiler.xml new file mode 100644 index 0000000..82c4d0e --- /dev/null +++ b/mysql_split_horizon/.idea/compiler.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/encodings.xml b/mysql_split_horizon/.idea/encodings.xml new file mode 100644 index 0000000..b26911b --- /dev/null +++ b/mysql_split_horizon/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__aopalliance_aopalliance_1_0.xml b/mysql_split_horizon/.idea/libraries/Maven__aopalliance_aopalliance_1_0.xml new file mode 100644 index 0000000..30ff5cb --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__aopalliance_aopalliance_1_0.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__ch_qos_logback_logback_classic_1_1_5.xml b/mysql_split_horizon/.idea/libraries/Maven__ch_qos_logback_logback_classic_1_1_5.xml new file mode 100644 index 0000000..d6d6d0d --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__ch_qos_logback_logback_classic_1_1_5.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__ch_qos_logback_logback_core_1_1_5.xml b/mysql_split_horizon/.idea/libraries/Maven__ch_qos_logback_logback_core_1_1_5.xml new file mode 100644 index 0000000..25940f5 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__ch_qos_logback_logback_core_1_1_5.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__com_fasterxml_classmate_1_1_0.xml b/mysql_split_horizon/.idea/libraries/Maven__com_fasterxml_classmate_1_1_0.xml new file mode 100644 index 0000000..727b8fe --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__com_fasterxml_classmate_1_1_0.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_annotations_2_6_5.xml b/mysql_split_horizon/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_annotations_2_6_5.xml new file mode 100644 index 0000000..73c91ed --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_annotations_2_6_5.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_core_2_6_5.xml b/mysql_split_horizon/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_core_2_6_5.xml new file mode 100644 index 0000000..df1db76 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_core_2_6_5.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_databind_2_6_5.xml b/mysql_split_horizon/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_databind_2_6_5.xml new file mode 100644 index 0000000..015d92d --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__com_fasterxml_jackson_core_jackson_databind_2_6_5.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__javax_validation_validation_api_1_1_0_Final.xml b/mysql_split_horizon/.idea/libraries/Maven__javax_validation_validation_api_1_1_0_Final.xml new file mode 100644 index 0000000..940ce73 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__javax_validation_validation_api_1_1_0_Final.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__junit_junit_4_12.xml b/mysql_split_horizon/.idea/libraries/Maven__junit_junit_4_12.xml new file mode 100644 index 0000000..d411041 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__junit_junit_4_12.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__mysql_mysql_connector_java_5_1_38.xml b/mysql_split_horizon/.idea/libraries/Maven__mysql_mysql_connector_java_5_1_38.xml new file mode 100644 index 0000000..c648589 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__mysql_mysql_connector_java_5_1_38.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_embed_tomcat_embed_core_8_0_32.xml b/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_embed_tomcat_embed_core_8_0_32.xml new file mode 100644 index 0000000..bc9b002 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_embed_tomcat_embed_core_8_0_32.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_embed_tomcat_embed_el_8_0_32.xml b/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_embed_tomcat_embed_el_8_0_32.xml new file mode 100644 index 0000000..1208bac --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_embed_tomcat_embed_el_8_0_32.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_embed_tomcat_embed_logging_juli_8_0_32.xml b/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_embed_tomcat_embed_logging_juli_8_0_32.xml new file mode 100644 index 0000000..7e3650f --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_embed_tomcat_embed_logging_juli_8_0_32.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_embed_tomcat_embed_websocket_8_0_32.xml b/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_embed_tomcat_embed_websocket_8_0_32.xml new file mode 100644 index 0000000..5f0bf6b --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_embed_tomcat_embed_websocket_8_0_32.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_tomcat_jdbc_8_0_32.xml b/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_tomcat_jdbc_8_0_32.xml new file mode 100644 index 0000000..9ffa329 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_tomcat_jdbc_8_0_32.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_tomcat_juli_8_0_32.xml b/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_tomcat_juli_8_0_32.xml new file mode 100644 index 0000000..96b9b35 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_apache_tomcat_tomcat_juli_8_0_32.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_hamcrest_hamcrest_core_1_3.xml b/mysql_split_horizon/.idea/libraries/Maven__org_hamcrest_hamcrest_core_1_3.xml new file mode 100644 index 0000000..f58bbc1 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_hamcrest_hamcrest_core_1_3.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_hamcrest_hamcrest_library_1_3.xml b/mysql_split_horizon/.idea/libraries/Maven__org_hamcrest_hamcrest_library_1_3.xml new file mode 100644 index 0000000..78dbe45 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_hamcrest_hamcrest_library_1_3.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_hibernate_hibernate_validator_5_2_4_Final.xml b/mysql_split_horizon/.idea/libraries/Maven__org_hibernate_hibernate_validator_5_2_4_Final.xml new file mode 100644 index 0000000..6c5e17f --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_hibernate_hibernate_validator_5_2_4_Final.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_jboss_logging_jboss_logging_3_3_0_Final.xml b/mysql_split_horizon/.idea/libraries/Maven__org_jboss_logging_jboss_logging_3_3_0_Final.xml new file mode 100644 index 0000000..186d87f --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_jboss_logging_jboss_logging_3_3_0_Final.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_mockito_mockito_core_1_10_19.xml b/mysql_split_horizon/.idea/libraries/Maven__org_mockito_mockito_core_1_10_19.xml new file mode 100644 index 0000000..a523703 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_mockito_mockito_core_1_10_19.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_objenesis_objenesis_2_1.xml b/mysql_split_horizon/.idea/libraries/Maven__org_objenesis_objenesis_2_1.xml new file mode 100644 index 0000000..7ab319b --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_objenesis_objenesis_2_1.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_slf4j_jcl_over_slf4j_1_7_16.xml b/mysql_split_horizon/.idea/libraries/Maven__org_slf4j_jcl_over_slf4j_1_7_16.xml new file mode 100644 index 0000000..d10913f --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_slf4j_jcl_over_slf4j_1_7_16.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_slf4j_jul_to_slf4j_1_7_16.xml b/mysql_split_horizon/.idea/libraries/Maven__org_slf4j_jul_to_slf4j_1_7_16.xml new file mode 100644 index 0000000..17682bb --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_slf4j_jul_to_slf4j_1_7_16.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_slf4j_log4j_over_slf4j_1_7_16.xml b/mysql_split_horizon/.idea/libraries/Maven__org_slf4j_log4j_over_slf4j_1_7_16.xml new file mode 100644 index 0000000..9956f99 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_slf4j_log4j_over_slf4j_1_7_16.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_slf4j_slf4j_api_1_7_16.xml b/mysql_split_horizon/.idea/libraries/Maven__org_slf4j_slf4j_api_1_7_16.xml new file mode 100644 index 0000000..3d1a710 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_slf4j_slf4j_api_1_7_16.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_1_3_3_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_1_3_3_RELEASE.xml new file mode 100644 index 0000000..55a145d --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_1_3_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_autoconfigure_1_3_3_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_autoconfigure_1_3_3_RELEASE.xml new file mode 100644 index 0000000..deda400 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_autoconfigure_1_3_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_1_3_3_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_1_3_3_RELEASE.xml new file mode 100644 index 0000000..e0d745d --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_1_3_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_jdbc_1_3_3_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_jdbc_1_3_3_RELEASE.xml new file mode 100644 index 0000000..463f08d --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_jdbc_1_3_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_logging_1_3_3_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_logging_1_3_3_RELEASE.xml new file mode 100644 index 0000000..0137f8b --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_logging_1_3_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_test_1_3_3_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_test_1_3_3_RELEASE.xml new file mode 100644 index 0000000..11b70cf --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_test_1_3_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_tomcat_1_3_3_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_tomcat_1_3_3_RELEASE.xml new file mode 100644 index 0000000..6a1c887 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_tomcat_1_3_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_validation_1_3_3_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_validation_1_3_3_RELEASE.xml new file mode 100644 index 0000000..edd79a7 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_validation_1_3_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_web_1_3_3_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_web_1_3_3_RELEASE.xml new file mode 100644 index 0000000..b33f9cc --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_boot_spring_boot_starter_web_1_3_3_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_aop_4_2_5_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_aop_4_2_5_RELEASE.xml new file mode 100644 index 0000000..7388c82 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_aop_4_2_5_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_beans_4_2_5_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_beans_4_2_5_RELEASE.xml new file mode 100644 index 0000000..6959be5 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_beans_4_2_5_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_context_4_2_5_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_context_4_2_5_RELEASE.xml new file mode 100644 index 0000000..d71e0a4 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_context_4_2_5_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_core_4_2_5_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_core_4_2_5_RELEASE.xml new file mode 100644 index 0000000..9c970d9 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_core_4_2_5_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_expression_4_2_5_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_expression_4_2_5_RELEASE.xml new file mode 100644 index 0000000..c9285e1 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_expression_4_2_5_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_jdbc_4_2_5_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_jdbc_4_2_5_RELEASE.xml new file mode 100644 index 0000000..3beb055 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_jdbc_4_2_5_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_test_4_2_5_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_test_4_2_5_RELEASE.xml new file mode 100644 index 0000000..ff922bd --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_test_4_2_5_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_tx_4_2_5_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_tx_4_2_5_RELEASE.xml new file mode 100644 index 0000000..2454e0b --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_tx_4_2_5_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_web_4_2_5_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_web_4_2_5_RELEASE.xml new file mode 100644 index 0000000..6646dba --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_web_4_2_5_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_webmvc_4_2_5_RELEASE.xml b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_webmvc_4_2_5_RELEASE.xml new file mode 100644 index 0000000..20be062 --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_springframework_spring_webmvc_4_2_5_RELEASE.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/libraries/Maven__org_yaml_snakeyaml_1_16.xml b/mysql_split_horizon/.idea/libraries/Maven__org_yaml_snakeyaml_1_16.xml new file mode 100644 index 0000000..3fbdbce --- /dev/null +++ b/mysql_split_horizon/.idea/libraries/Maven__org_yaml_snakeyaml_1_16.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/misc.xml b/mysql_split_horizon/.idea/misc.xml new file mode 100644 index 0000000..5755a99 --- /dev/null +++ b/mysql_split_horizon/.idea/misc.xml @@ -0,0 +1,13 @@ + + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/modules.xml b/mysql_split_horizon/.idea/modules.xml new file mode 100644 index 0000000..fb4ab7f --- /dev/null +++ b/mysql_split_horizon/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/mysql_split_horizon/.idea/workspace.xml b/mysql_split_horizon/.idea/workspace.xml new file mode 100644 index 0000000..db2c5f9 --- /dev/null +++ b/mysql_split_horizon/.idea/workspace.xml @@ -0,0 +1,556 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + DEFINITION_ORDER + + + + + + + + + + + + + + Android + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +