Menu

后台返回xml格式转json



 那么大家就要如此管理:commonMethodResponse是xml里面包车型客车竹签,具体哪些标签是足以拿走到文本的,可以加上打字与印刷语句看一下

概述

  那几个实例主假设前台数据到后台数据的传递和后台数据到前台数据的传递,达成数据的疯长,以及对新扩充多少的展现。下边是事无巨细的历程:

    图片 1

Hibernate(数据库部分)

  这里只是数据库的接连和数据库实体与物理表的投射。

图片 2图片 3

 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>

hibernate.cfg.xml文件配置

图片 4图片 5

 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 }

实体Student类

图片 6图片 7

 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方法,提交表单,成功之后将页面转到体现新扩大的学生信息的页面。这里从前台传值到后台时选取Struts二的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配置

图片 8struts.xml配置文件

图片 9图片 10

 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>

web.xml

  在布局文件中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格式的转移,括弧至关重要。

  到那边,就到位了3次前台数据到后台,后台数据到前台的传递

  上面是收获新加上的数额的历程;

  在上头addStudent.jsp中from方法success对应的法门定位到getStudentJsp.action时,程序又会去2回后台调用对应的getStudentJsp方法,在这些方法中校新加上的student的noid增加到requet域中(增添在其余的近乎request域中也ok,但是要留意失不失效难题),供前台获取。

前台获取的页面如下:

图片 11图片 12

 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>

main.jsp

  在这几个页面里面获取后台的数占领俩个艺术,3个是${requestScope.requestKey},第二个是使用<s:property
value=”#request.requestKey”/>标签。在页面进入之后会实施起先化方法,获取数据,呈现新增加长的学生音讯。

在条分缕析后台传递的json数据时,要专注json的key要和form表单的name一向。

  到那边那个流程就完了了,里面须要小心的便是,前台未来台传递数据时,数据大多,能够采取Struts贰的DomainModel将一切实体的数额传入后台;在后台前台传递数据的可以用request,application等传递数据,也足以传递json格式数据,可是前台取值的时候要专注json格式调换。

 

 

参考的作品:

  

  

 

  

事先后台做了1个xml格式的多寡重临给前端,这几个可愁坏了自个儿,可是未来照旧减轻了,尽管艺术有些笨,但未曾找到其它的办法,先将就着用吗。

  图片 13

 $(data).find('commonMethodResponse').each(function(){
                            GetData=JSON.parse($(this).children()[0].innerHTML);
                        });

 

  所以最后的结果便是我们所要的:

标签:,

发表评论

电子邮件地址不会被公开。 必填项已用*标注

相关文章

网站地图xml地图