Struts2+EasyUI+Hibernate小实例
概述
这个实例主要是前台数据到后台数据的传递和后台数据到前台数据的传递,完成数据的新增,以及对新增数据的展示。下面是详细的过程:
Hibernate(数据库部分)
这里只是数据库的连接和数据库实体与物理表的映射。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 <hibernate-configuration> 6 <session-factory> 7 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> 8 <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> 9 <property name="connection.username">xiaoliu</property> 10 <property name="connection.password">hm123456</property> 11 <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> 12 <property name="show_sql">true</property> 13 <property name="hibernate.format_sql">true</property> 14 <mapping class="com.lt.entity.Student" /> 15 </session-factory> 16 </hibernate-configuration>
1 package com.lt.entity; 2 3 import javax.persistence.Column; 4 import javax.persistence.Entity; 5 import javax.persistence.Id; 6 import javax.persistence.Table; 7 8 @Entity 9 @Table 10 public class Student { 11 12 private String name; 13 @Id 14 private String noid; 15 private String password; 16 private String hobby; 17 public String getName() { 18 return name; 19 } 20 public void setName(String name) { 21 this.name = name; 22 } 23 public String getNoid() { 24 return noid; 25 } 26 public void setNoid(String noid) { 27 this.noid = noid; 28 } 29 public String getPassword() { 30 return password; 31 } 32 public void setPassword(String password) { 33 this.password = password; 34 } 35 public String getHobby() { 36 return hobby; 37 } 38 public void setHobby(String hobby) { 39 this.hobby = hobby; 40 } 41 42 }
1 package com.lt.dao; 2 3 4 5 import java.util.List; 6 7 import org.hibernate.HibernateException; 8 import org.hibernate.Session; 9 import org.hibernate.Transaction; 10 11 import com.lt.action.BasicAction; 12 import com.lt.entity.Student; 13 14 15 public class StudentDao extends BasicAction{ 16 17 public void addStudent(Student student){ 18 Session session = factory.openSession(); 19 Transaction transaction = session.beginTransaction(); 20 try { 21 session.save(student); 22 transaction.commit(); 23 System.out.println("success"); 24 } catch (Exception e) { 25 e.printStackTrace(); 26 transaction.rollback(); 27 }finally{ 28 29 session.close(); 30 } 31 32 } 33 34 public Student queryStudent(String noid){ 35 Session session = factory.openSession(); 36 Transaction transaction = session.beginTransaction(); 37 String sql = "from Student where noid = ?"; 38 Student list = null ; 39 try { 40 list = (Student) session.get(Student.class, noid); 41 transaction.commit(); 42 } catch (HibernateException e) { 43 transaction.rollback(); 44 // TODO Auto-generated catch block 45 e.printStackTrace(); 46 }finally{ 47 48 session.close(); 49 } 50 return list; 51 } 52 }
EasyUI(页面jsp文件)
这里对jsp的页面中的样式没有什么设计,主要是js功能的实现。
1 <%@ page language="java" contentType="text/html; charset=utf-8" 2 pageEncoding="ISO-8859-1"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 7 <link rel="stylesheet" type="text/css" href="resource/easyui.css"> 8 <link rel="stylesheet" type="text/css" href="resource/icon.css"> 9 <script type="text/javascript" src="resource/jquery.min.js"></script> 10 <script type="text/javascript" src="resource/jquery.easyui.min.js"></script> 11 <title>Add Student Information</title> 12 </head> 13 14 <body> 15 <script type="text/javascript"> 16 function lal(){ 17 $('#detilfrom').form('submit',{url:"addStudentInfo!addStudentInfo.action", 18 success: function(data){ 19 var json = eval('(' + data + ')'); 20 if(json.success=="success") 21 alert(123) 22 var noid = $("#noid").val(); 23 window.open("getStudentJsp.action?student.noid="+noid); 24 }} 25 ); 26 } 27 28 29 </script> 30 <form action="" id = "detilfrom"> 31 name:<input type="text" id="name" name="student.name" /><br> 32 noid:<input type="text" id="noid" name="student.noid" /><br> 33 password:<input type="text" name="student.password" /><br> 34 hobby:<input type ="text" name="student.hobby" /><br> 35 <input type="button" value="get" onclick="lal()" > 36 </form> 37 </body> 38 </html>
获得form对象,用EasyUI的form方法,提交表单,成功之后将页面转到展示新增的学生信息的页面。这里从前台传值到后台时使用Struts2的DomainModel将前台数据直接保存到Student实体中,在上述代码中name标签的命名要用实体(Student).属性的形式。在form方法中url要和struts配置文件中action名和方法相对应这样才不会报资源取不到的错误,同时在请求成功之后会执行success对应的方法;在后台获取值的时候,只需要定义一个Student实体,并且创建Student对象的set/get方法即可。下面为后台接收数据的代码(addStudentInfo方法):
package com.lt.action; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.lt.dao.StudentDao; import com.lt.entity.Student; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class StudentAction extends ActionSupport { private Map <String,Object>request; private Map <String,Object>session; private Map <String,Object>application; private Map<String,Object> s ; private Student student; StudentDao studentDao = new StudentDao(); public String getStudentInfo(){ s = new HashMap<String,Object>(); System.out.println(student.getNoid()); Student s1 = studentDao.queryStudent(student.getNoid()); System.out.println(s1.getName()); s.put("student", s1); return SUCCESS; } public String addStudentInfo(){ s = new HashMap<String,Object>(); studentDao.addStudent(student); s.put("success", "success"); return "success"; } public String getStudentJsp(){ System.out.println("通过ActionContext来访问request,session,application对象"); // 初始化 request = (Map<String,Object>)ActionContext.getContext().get("request"); session = ActionContext.getContext().getSession(); application = ActionContext.getContext().getApplication(); // 赋值 request.put("requestKey", student.getNoid()); session.put("sessionKey", "sessionValue"); application.put("applicationKey", "applicationValue"); System.out.println(student.getNoid()); return SUCCESS; } public Map<String, Object> getS() { return s; } public void setS(Map<String, Object> s) { this.s = s; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } }
Struts2配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app> 3 <welcome-file-list> 4 <welcome-file>addStudent.jsp</welcome-file> 5 </welcome-file-list> 6 <filter> 7 <filter-name>struts2</filter-name> 8 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> 9 </filter> 10 <filter-mapping> 11 <filter-name>struts2</filter-name> 12 <url-pattern>/*</url-pattern> 13 </filter-mapping> 14 </web-app>
在配置文件中package继承了struts-default,json-default,当后台要返回json格式的数据是,在result中指定type为json即可;这里的json传到前台是json字符串,还要在前台进行json格式转换。
在上面Action类中的addStudentInfo方法执行完成之后会来到struts.xml配置文件中找到action中name为addStudentInfo中result中name匹配的标签(success),成功之后会返回执行addStudent.jsp中的from方法success对应的方法,在这个方法中用eval('(' + data + ')')实现了json格式的转换,括弧必不可少。
到这里,就完成了一次前台数据到后台,后台数据到前台的传递
下面是获取新添加的数据的过程;
在上面addStudent.jsp中from方法success对应的方法定位到getStudentJsp.action时,程序又会去一次后台调用对应的getStudentJsp方法,在这个方法中将新添加的student的noid添加到requet域中(添加在其他的类似request域中也ok,但是要注意失不失效问题),供前台获取。
前台获取的页面如下:
1 <%@ page language="java" contentType="text/html; charset=utf-8" 2 pageEncoding="utf-8"%> 3 <%@taglib uri="/struts-tags" prefix="s" %> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 8 <link rel="stylesheet" type="text/css" href="resource/easyui.css"> 9 <link rel="stylesheet" type="text/css" href="resource/icon.css"> 10 <script type="text/javascript" src="resource/jquery.min.js"></script> 11 <script type="text/javascript" src="resource/jquery.easyui.min.js"></script> 12 <title>try to show view</title> 13 </head> 14 15 <body> 16 <script type="text/javascript"> 17 var detilfrom = $("#detilfrom") 18 $(function(){ 19 noid = ${requestScope.requestKey} 20 $.ajax({ 21 url : "getStudentInfo!getStudentInfo.action?"+"student.noid="+noid, 22 type : "post", 23 datatype : "json", 24 success : name 25 }); 26 }); 27 function lal(){ 28 $.ajax({ 29 url : "getStudentInfo!getStudentInfo.action", 30 type : "post", 31 datatype : "json", 32 success : name 33 }); 34 } 35 function name(data) { 36 $.each(data,function(key,value){ 37 alert("key="+key+";"+"value="+value); 38 }) 39 $("#name").val(data.name); 40 //data.student = eval(eval(data.stdent)); 41 $("#detilfrom").form('load',data.student); 42 } 43 44 </script> 45 <form action="" id = "detilfrom"> 46 name:<input type="text" id="name" name="name" /><br> 47 noid:<input type="text" id="noid" name="noid" /><br> 48 password:<input type="text" name="password" /><br> 49 hobby:<input type ="text" name="hobby" /><br> 50 try:<s:property value="#request.requestKey"/> 51 <input type="button" value="get" onclick="lal()"> 52 </form> 53 54 </body> 55 </html>
在这个页面里面获取后台的数据有俩个方式,一个是${requestScope.requestKey},第二个是利用<s:property value="#request.requestKey"/>标签。在页面进入之后会执行初始化方法,获取数据,展示新添加的学生信息。
在解析后台传递的json数据时,要注意json的key要和form表单的name一直。
到这里这个流程就完成了,里面需要注意的就是,前台往后台传递数据时,数据很多,可以利用Struts2的DomainModel将整个实体的数据传入后台;在后台前台传递数据的可以用request,application等传递数据,也可以传递json格式数据,但是前台取值的时候要注意json格式转换。
参考的文章:
http://blog.sina.com.cn/s/blog_4b6f8d150100p1oy.html
http://blog.csdn.net/cao478208248/article/details/36888477