[JAVA REST]REST请求

[java rest]rest请求

    • 01.说明
    • 02.前端AJAX优化
    • 03.后台的优化
    • 04.数据的处理

01.说明

本系列是对 阿发你好 JAVA教程做的个人笔记总结,如果小伙伴们有兴趣,请移步至阿发你好官网JAVA教程,保姆级视频教学,您值得拥有

02.前端AJAX优化

前端AJAX执行rest请求,代码如下:

$.ajax({
 	method: 'POST' ,  //和POST请求类似,只不过它向后台传输的是JSON数据
 	url: 'Handler1',
 	contentType: 'application/json' ,//指定格式
 	data : JSON.stringify(req) ,//将对象转换为JSON对象
 	processData : false,
 	success : function( ret ){	//后台返回值的处理	
 		console.log( ret );
 		if(ret.error == 0) alert('OK')
 	}
})	

我们不难发现,其中有固定的套路与格式,那么我们能不能将AJAX进行代码优化呢?
阿发老师提供了afquery.js

// 自定义的一些工具方法

var Af = {}

Af.rest = function(url, data, success, error){
	if(data == null) data = {}; // 若data为null,则发送一个默认JSON{}
	
	$.ajax({
		method: 'POST' ,  
		url: url ,
		contentType: 'application/json' ,  // HTTP请求中的 Content-Type
		data : JSON.stringify(data) ,      // HTTP请求正文 
		processData : false,               // 
		dataType: 'json',                  // HTTP应答按JSON处理
		success : success ,
		error : error ,
	})	
}

这样我们只需要简单的调用方法,填入参数就可以实现rest请求

//URL,数据对象,回调方法
Af.rest('Handler6', app.form, function(ret){
	if(ret.error== 0){
		alert( ret.data)
	}
})

03.后台的优化

package my;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import my.util.FastJSON;
import my.util.WebUtil;

@WebServlet("/Handler4")
public class Handler4 extends HttpServlet
{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		// 1 提取正文
		JSONObject json = null;
		try{
			String requestBody = WebUtil.requestBody(req, "UTF-8");
			json = JSON.parseObject(requestBody);
		} catch (Exception e)
		{
			json = new JSONObject();
		}

		// 2 处理
		JSONObject result = new JSONObject(true);
		result.put("error", 0);
		result.put("reason", "OK");

		try
		{
			// 处理请求
			Object data = this.handle(req, resp, json);
			if (data != null)
			{
				if (data instanceof JSON) // 本身就是 JSONObject 或 JSONArray
					result.put("data", data);
				else
					result.put("data", JSON.toJSON(data));
			}

		} catch (Exception e)
		{
			String reason = e.getMessage();
			if (reason == null)
				reason = e.getClass().getName();
			result.put("error", -1);
			result.put("reason", e.getMessage());
		}
		
		// 3 返回应答数据
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json");
		resp.getWriter().write(FastJSON.niceFormat( result ));
	}

	// 具体的业务处理
	public Object handle(HttpServletRequest request
			, HttpServletResponse response
			, JSONObject json)throws Exception
	{
		
		return "已成功处理"; 
	}

}

后台的代码也是具有套路和固定格式的,我们只需要在handle方法里做对应的处理就可以了,那么我们就可以使用抽象类的方法实现:

package my;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import my.util.FastJSON;
import my.util.WebUtil;

public abstract class RestServlet extends HttpServlet
{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		// 1 提取正文
		JSONObject json = null;
		try{
			String requestBody = WebUtil.requestBody(req, "UTF-8");
			json = JSON.parseObject(requestBody);
		} catch (Exception e)
		{
			json = new JSONObject();
		}

		// 2 处理
		JSONObject result = new JSONObject(true);
		result.put("error", 0);
		result.put("reason", "OK");

		try
		{
			// 处理请求
			Object data = this.handle(req, resp, json);
			if (data != null)
			{
				if (data instanceof JSON) // 本身就是 JSONObject 或 JSONArray
					result.put("data", data);
				else
					result.put("data", JSON.toJSON(data));
			}

		} catch (Exception e)
		{
			String reason = e.getMessage();
			if (reason == null)
				reason = e.getClass().getName();
			result.put("error", -1);
			result.put("reason", e.getMessage());
		}
		
		// 3 返回应答数据
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json");
		resp.getWriter().write(FastJSON.niceFormat( result ));
	}

	// 具体的业务处理
	protected abstract Object handle(HttpServletRequest request
			, HttpServletResponse response
			, JSONObject json)throws Exception;
}

然后在实际使用的时候,继承抽象类,实现handle方法即可:

package my;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import my.util.FastJSON;

@WebServlet("/Handler4")
public class Handler6 extends RestServlet
{

	@Override
	protected Object handle(HttpServletRequest request, HttpServletResponse response, JSONObject json) throws Exception
	{
		System.out.println("收到请求: " + FastJSON.niceFormat(json));
		
		return "已经保存数据";
	}

}

04.数据的处理

在前面代码中使用的数据处理方法.仅供参考

package my.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

public class WebUtil
{
	// 读取请求正文 
	// JavaIO技术较难,新人不宜深入研究。具体可以参考《网络通信篇》或《JavaIO公开课》
	public static String requestBody(HttpServletRequest req, String charset) throws IOException
	{
		ByteArrayOutputStream result = new ByteArrayOutputStream(1024*16);  
		
		InputStream inputStream = req.getInputStream();
        byte[] data = new byte[1024];  
        while (true)
        {
        	int n = inputStream.read(data); // n, 实际读取的字节数
        	if(n <= 0) break; // 读取完毕
        	
        	result.write(data, 0, n);  // 缓存起来      	
        	if(result.size() > 1024*1024) // 上限, 最多读取1M
        		break;
        }  
        
        return result.toString(charset);
	}
	
	// 
	public static int paramInt(HttpServletRequest req, String key, int defValue)
	{
		String str = req.getParameter(key);
		if(str == null || str.length()==0)
			return defValue;
		try {
			return Integer.valueOf(str);
		}catch(Exception e) {
			return defValue;
		}
	}
	
	public static long paramLong(HttpServletRequest req, String key, long defValue)
	{
		String str = req.getParameter(key);
		if(str == null || str.length()==0)
			return defValue;
		try {
			return Long.valueOf(str);
		}catch(Exception e) {
			return defValue;
		}
	}
	
	public static boolean paramBoolean(HttpServletRequest req, String key, boolean defValue)
	{
		String str = req.getParameter(key);
		if(str == null || str.length()==0)
			return defValue;
		try {
			return Boolean.valueOf(str);
		}catch(Exception e) {
			return defValue;
		}
	}
	
	public static String paramString(HttpServletRequest req, String key, String defValue)
	{
		String str = req.getParameter(key);
		if(str == null || str.length()==0)
			return defValue;
		
		return str;
	}
}

package my.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class FastJSON
{
	public static String niceFormat(Object j)
	{
		return JSON.toJSONString(j, SerializerFeature.PrettyFormat);
	}
	
	
	///
	
	public static int intValue(JSONObject j, String key, int defValue)
	{
		try {
			return j.getIntValue(key);
		}catch(Exception e) {
			return defValue;
		}
	}
	
	public static long longValue(JSONObject j, String key, long defValue)
	{
		try {
			return j.getLongValue(key);
		}catch(Exception e) {
			return defValue;
		}
	}
	
	public static boolean booleanValue(JSONObject j, String key, boolean defValue)
	{
		try {
			return j.getBooleanValue(key);
		}catch(Exception e) {
			return defValue;
		}
	}
	
	public static String stringValue(JSONObject j, String key, String defValue)
	{
		try {
			return j.getString(key);
		}catch(Exception e) {
			return defValue;
		}
	}
	
	public static double doubleValue(JSONObject j, String key, double defValue)
	{
		try {
			return j.getDoubleValue(key);
		}catch(Exception e) {
			return defValue;
		}
	}
	
	public static float floatValue(JSONObject j, String key, float defValue)
	{
		try {
			return j.getFloatValue(key);
		}catch(Exception e) {
			return defValue;
		}
	}	
}

你可能感兴趣的:(JAVA学习笔记,java,servlet,javascript)