java学习笔记(12) —— Struts2 通过 xml /json 实现简单的业务处理

Posted cklovefan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java学习笔记(12) —— Struts2 通过 xml /json 实现简单的业务处理相关的知识,希望对你有一定的参考价值。

XML

1、引入dom4j-2.0.0.jar

2、引入jquery-1.8.2.js

3、新建common.js

getInfo = function(){
    $.post("getXmlAction.action",{name:$(‘#name‘).val()},function(ret,status){
        if("success" == status)
            var id = $(ret).find("id").text();
            var age = $(ret).find("age").text();
            var address = $(ret).find("address").text();
            var name = $(ret).find("name").text();
            
            var html = "<table>" +
                    "<tr>" +
                    "<th>" +id+age+address+name
                    "</th>"+
                    "</tr>" +
                    "</table>"
             $(‘body table:eq(0)‘).remove();
             $(‘#xmlbody‘).append(html);
    });
}

getJson = function(){
    $.post("getJsonAction.action",{name:$(‘#name‘).val()},function(ret,status){
        if("success" == status){
        
        }
    });
}

4、新建xmlTest.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.8.2.js"></script>
    <script type="text/javascript" src="scripts/common.js"></script>
  </head>
  
  <body id="xmlbody">
      <select id="name">
          <option value="james" selected="selected">james</option>
          <option value="currey">currey</option>
      </select>
      <input type="button" value="getInfo" onclick="getInfo();"/>
  </body>
</html>

5、修改struts.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" 
"http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>
    <package name="testSSH" extends="struts-default">
        
        <action name="getXmlAction" class="com.test.action.xml.GetXmlAction">

        </action>
    </package>
</struts>    

6、新建GetXmlAction.java

package com.test.action.xml;


import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.dom4j.*;
import org.dom4j.io.*;
import com.opensymphony.xwork2.ActionSupport;

public class GetXmlAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    
    private String name;
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String execute() throws Exception {
        person person1 = new person();
        person1.setAge(11);
        person1.setName("james");
        person1.setId(1);
        person1.setAddress("beijing");
        
        person person2 = new person();
        person2.setId(2);
        person2.setAddress("shanghai");
        person2.setAge(12);
        person2.setName("currey");
        
        //创建 xml 对象
        Document document = DocumentHelper.createDocument();
        //创建根元素
        Element rootElement = document.addElement("users");
        Element userElement = rootElement.addElement("user");
        Element idElement = userElement.addElement("Id");
        Element ageElement = userElement.addElement("age");
        Element addressElement = userElement.addElement("address");
        Element nameElement = userElement.addElement("name");
        if("james".equals(this.name)){
            idElement.setText(person1.getId()+"");    
            ageElement.setText(person1.getAge()+"");
            addressElement.setText(person1.getAddress());
            nameElement.setText(person1.getName());
        }else{
            idElement.setText(person2.getId()+"");    
            ageElement.setText(person2.getAge()+"");
            addressElement.setText(person2.getAddress());
            nameElement.setText(person2.getName());
        }
        HttpServletResponse response = ServletActionContext.getResponse();
        //设置返回类型
        response.setContentType("text/xml; charset=UTF-8 ");
        //清除浏览器缓存
        response.setHeader("Cache-Control", "no-cache");
        //定义输出流
        PrintWriter out = response.getWriter();
        //定义格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        //定义XMLWriter 对象,将document 对象,输出到客户端
        XMLWriter writer  = new XMLWriter(out,format);
        writer.write(document);
        out.flush();
        out.close();
        return null;
    }
}

 JSON

1、引入struts2-json-plugin.jar、json-lib.jar包

2、配置struts.xml

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" 
"http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>
  // 继承自json-default 而json-default继承自 struts-default
<package name="testSSH" extends="json-default"> //异步请求不定义返回值 <action name="getXmlAction" class="com.test.action.xml.GetXmlAction"></action>
     //异步请求返回值为SUCCESS,定义类型为json 即可,客户端到服务端序列化的过程交由core 处理
<action name="getJsonAction" class="com.test.action.json.GetJsonAction"> <result name="success" type="json">
         //排除 属性 name MyAge【指向别名】 <param name="excludeProperties">name,MyAge</param>
         // 只解析root
<param name="root">person</param> </result> </action> </package> </struts>

 

3、定义GetJsonAction.java

package com.test.action.json;

import org.apache.struts2.json.annotations.JSON;
import java.util.*;

import com.opensymphony.xwork2.ActionSupport;
import com.test.action.json.person;

public class GetJsonAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    
    //客户端传入的名称
    private String name;
    
    private int age;
    
    private String address; 
    
    private int id;
    
    private Date date;
    
    private person person = new person();
    
    public person getPerson() {
        return person;
    }

    public void setPerson(person person) {
        this.person = person;
    }

    @JSON(format = "yyyy-MM-dd")
    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
    @JSON(name = "MyAddress")
    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
    
    @JSON(serialize=false)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //将Action 的成员变量序列化成json对象
    @Override
    public String execute() throws Exception {
        person person1 = new person();
        person1.setAge(11);
        person1.setName("james");
        person1.setId(1);
        person1.setAddress("beijing");
        person1.setDate(new Date());
        
        person person2 = new person();
        person2.setId(2);
        person2.setAddress("shanghai");
        person2.setAge(12);
        person2.setName("currey");
        person2.setDate(new Date());
        
        if("james".equals(this.name)){
            this.id = person1.getId();
            this.age = person1.getAge();
            this.address = person1.getAddress();
            this.date = person1.getDate();
        }else{
            this.id = person2.getId();
            this.age = person2.getAge();
            this.address = person2.getAddress();
            this.date = person2.getDate();
        }
        
        return SUCCESS;
    }
}

4、定义person属性类

package com.test.action.json;
import java.util.*;

public class person {

    private int id;
    private String name;
    private int age;
    private String address;
    private Date date;
    
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    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 String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    
}

 

 5、引入jsonText.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.8.2.js"></script>
    <script type="text/javascript" src="scripts/common.js"></script>
  </head>
  
  <body id="xmlbody">
      <select id="name">
          <option value="james" selected="selected">james</option>
          <option value="currey">currey</option>
      </select>
      <input type="button" value="getInfo" onclick="getJson();"/>
  </body>
</html>

 

以上是关于java学习笔记(12) —— Struts2 通过 xml /json 实现简单的业务处理的主要内容,如果未能解决你的问题,请参考以下文章

struts2学习笔记——常见报错及解决方法汇总(持续更新)

java学习笔记 —— Struts2 国际化 [1]

Struts2-学习笔记系列(12)-set集合

java学习笔记(11) —— Struts2与Spring的整合

[原创]java WEB学习笔记70:Struts2 学习之路-- struts2拦截器源码分析,运行流程

[原创]java WEB学习笔记63:Struts2学习之路--主题