servlet中获取XMLHttpRequest提交的FormData参数

js代码

function SaveProgress(data) {
	var fd = new FormData(),
		xhr = new XMLHttpRequest();
	fd.append('data', data);
	xhr.open('post', '/zkvos', true);
	xhr.onreadystatechange = function() {
		if (xhr.status == 200) {
			if (xhr.readyState == 4) {
				console.log(xhr.responseText);
			}
		} else {
			console.log('server error');
		}
	}
	xhr.send(fd);
}

java代码

package com.study;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


@WebServlet("/zkvos")
public class StudyOnlineServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public StudyOnlineServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.getWriter().append("parameter error").append(request.getContextPath());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Map params = this.getParameters(request);
		String status = "";
		if (this.checkParam(params)) {
			String data = params.get("data");//通过参数名拿到参数值
			System.out.print(data);
		} else {
			status = "参数错误";
		}
		response.getWriter().print(status);
	}

	/**
	 * 获取FormData携带参数
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Map getParameters(HttpServletRequest request) {
		Map params = new HashMap<>();
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List items;
			items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					// item.getFieldName();// 参数名
					// item.getString();// 参数值
					params.put(item.getFieldName(), item.getString());
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		return params;
	}

	/**
	 * 检查参数是否完整
	 * 
	 * @param params
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private Boolean checkParam(Map params) {
		String[] paramNames = { "d", "u", "c", "h", "e", "t", "f" };
		for (String paramName : paramNames) {
			if (params.containsKey(paramName)) {
				if (params.get(paramName) == null)
					return false;
			} else {
				return false;
			}
		}
		return true;
	}
}


你可能感兴趣的:(笔记)