JSONP请求控制

5 篇文章 0 订阅

Web.xml中配置Filter

<!-- JSONP请求控制 -->
	<filter> 
      <filter-name>jsonpFilter</filter-name> 
      <filter-class>JsonpFilter路径</filter-class> 
      <async-supported>true</async-supported>
   </filter> 
   <filter-mapping> 
      <filter-name>jsonpFilter</filter-name> 
      <url-pattern>/*</url-pattern> 
   </filter-mapping>

编写jsonpFilter

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.springframework.http.HttpStatus;

public final class JsonpFilter implements Filter {
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		if (request.getParameter("callback") != null) {
			ByteResponseWrapper brw = new ByteResponseWrapper((HttpServletResponse) response);
			chain.doFilter(request, brw);
			String out = new String(brw.getBytes());
			Map<String, Object> map = null;
			try {
				map = JsonTool.getMap4Json(out);
			} catch (JSONException ex) {

			}
			if (map != null) {
				((HttpServletResponse) response).setStatus(HttpStatus.OK.value());
				int status = brw.getStatus();
				if (status >= 200 && status < 300 || status == 304) {
					if (status == 304) {
						((HttpServletResponse) response).setStatus(HttpStatus.NOT_MODIFIED.value());
					}
					map.put("status", "success");
				} else {
					map.put("status", "error");
				}
				out = JSONObject.fromObject(map).toString();
			}
			out = request.getParameter("callback") + "(" + out;
			out += ")";
			response.setContentType("application/json; charset=utf-8");
			response.setContentLength(out.getBytes().length);
			response.getOutputStream().write(out.getBytes());
		} else {
			chain.doFilter(request, response);
		}
	}

	public void destroy() {
	}

	public void init(FilterConfig filterConfig) {
	}

	static class ByteResponseWrapper extends HttpServletResponseWrapper {
		private PrintWriter writer;
		private ByteOutputStream output;
		private int code = 200;

		public byte[] getBytes() {
			writer.flush();
			return output.getBytes();
		}

		public ByteResponseWrapper(HttpServletResponse response) {
			super(response);
			output = new ByteOutputStream();
			writer = new PrintWriter(output);
		}

		@Override
		public PrintWriter getWriter() {
			return writer;
		}

		@Override
		public ServletOutputStream getOutputStream() throws IOException {
			return output;
		}


		public int getStatus() {
			return code;
		}
		
	    public void sendRedirect(String location) throws IOException {
	    	code = HttpStatus.MOVED_TEMPORARILY.value();
	    	super.sendRedirect(location);
	    }
		
		@Override
		public void setStatus(int sc) {
			this.code = sc;
		}

		@Override
		public void setStatus(int sc, String message) {
			this.code = sc;
		}

		@Override
		public void sendError(int sc) throws IOException {
			this.code = sc;
		}

		@Override
		public void sendError(int sc, String msg) throws IOException {
			this.code = sc;
		}
	}

	static class ByteOutputStream extends ServletOutputStream {
		private ByteArrayOutputStream bos = new ByteArrayOutputStream();

		@Override
		public void write(int b) throws IOException {
			bos.write(b);
		}

		public byte[] getBytes() {
			return bos.toByteArray();
		}

		@Override
		public boolean isReady() {
			return false;
		}

		@Override
		public void setWriteListener(WriteListener arg0) {
			
		}
	}

	private static class JsonTool {
		public static Map getMap4Json(String jsonString) {
			JSONObject jsonObject = JSONObject.fromObject(jsonString);
			Iterator keyIter = jsonObject.keys();
			String key;
			Object value;
			Map valueMap = new HashMap();

			while (keyIter.hasNext()) {
				key = (String) keyIter.next();
				value = jsonObject.get(key);
				valueMap.put(key, value);
			}

			return valueMap;
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值