Struts2 + Ajax + JSON 整合

AJAXBloger 2013-02-28

首先,我会想到以下两个问题:

1、Web端是如何通过Ajax发送异步请求的?又如何接收Server端响应的JSON数据?

2、Server端收到请求后,如何返回JSON数据?

一、使用Ajax发送异步请求,并接收Server端传回的响应数据:

先看JSP页面代码:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
	<head>
		<title>Struts+Ajax+JSON</title>
		<script type="text/javascript" src="ajax.js"></script>
	</head>
	<body>
		<h3>Struts2 + Ajax + JSON 整合</h3>
		<form action="json" method="get">
			username:<input type="text" id="username" name="user.username" /><br/>
			password:<input type="text" id="password" name="user.password" /><br/>
			<input type="button" onclick="getEmail()" value="查看Email"/><br />
		</form>
		<p>您的Email地址为:<span id="email"></span></p>
	</body>
</html>

   

前端实现Ajax的JS代码:

//创建XMLHttpRequest对象
function createXMLHttpRequest() {
	var xmlhttp;
	if(window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else {
		if(window.ActionXObject) {
			xmlhttp = new ActionXObject("Microsoft.XMLHTTP");
		} else {
			xmlhttp = new ActionXObject("Msxml2.XMLHTTP");
		}
	}
	return xmlhttp;
}

//发送GET请求
function sendGetRequest(url,callback){
	var xmlhttp = createXMLHttpRequest();
	xmlhttp.open("GET", url, true);
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				//获取服务器的响应数据
				var data = xmlhttp.responseText;
				callback(data);
			} 
		} 
	};
	xmlhttp.send(null);
}

//获取Email地址
function getEmail() {
	var username = document.getElementById("username").value;
	var password = document.getElementById("password").value;
	var url = "json?user.username=" + username + "&user.password=" + password; 
	sendGetRequest(url, function(data){
		var obj = eval("(" + data + ")");
		document.getElementById("email").innerHTML = obj.user.email;
	});
}

 二、使用Struts2处理异步请求并返回JSON数据:

Struts2中的Action代码:

package com.json.action;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import com.json.dto.User;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {
	
	private User user;

	//此方法的返回类型为void
	public void execute() throws IOException {
		//打印请求中的user参数
		System.out.println(user.getUsername() + ":" + user.getPassword());
		
		//---发送JSON数据---
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		user.setEmail("[email protected]");
		//创建JSON对象
		JSONObject json = new JSONObject();
		//把User对象放入Json对象中		
		json.accumulate("user", user);
		//把Json对象转成字符串并写入响应流
		out.print(json.toString());
		//可以打印JSON文本看一看
		System.out.print(json.toString());
		out.flush();
		out.close();
	}
	
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
}

Action中的User类的代码:

package com.json.dto;

public class User {
	private String username;
	private String password;
	private String email;
	
	public User() {}
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
}

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="user" extends="struts-default">
		<action name="json" 
			class="com.json.action.UserAction" method="execute">
		</action>
	</package>
</struts>

J2EE开发中使用JSON时需要导入以下5个jar包:

---------------------------------------

commons-lang-2.4.jar

commons-logging-1.1.1.jar

json-lib-2.4-jdk15.jar

ezmorph-1.0.6.jar

commons-collections-3.2.1.jar

---------------------------------------

已全部打包在附件内:

相关推荐

mmywcoco / 0评论 2020-06-06