Json已经成为一种主流的数据传输格式,请求参数是整个RequestBody。
那么,拦截器中如何获取Json呢?
办法是:通过request.getInputStream。


RequestBody是流的形式读取,流读了一次就没有了,所以只能被调用一次。
在拦截器中读取后,Controller中,通过@RequestBody注解获取Json就会失败。
那么,问题来了,如何在拦截器中获取json后,同时可以在Controller再次获取呢?
办法是:在使用之前将流储存在一个能持续request生命周期的元素中。


下面是一个完整的通过例子,包含了如下知识点:
1、Spring拦截器的使用
2、注解方式判定是否被拦截
3、在拦截器中获取request中的Json格式参数
4、解决RequestBody只能读取一次的问题

一、创建一个自定义基础拦截器抽象类,以及用作拦截判定的注解。

package com.tcl.shbc.thirdbus.interceptor;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 自定义Base拦截器
 * @author Oliver
 * @version 20161214
 */
public abstract class BaseInterceptor extends HandlerInterceptorAdapter {

	public String failed;
	
	public String name;
	
	/**
	 * 自定义拦截逻辑
	 * 
	 * @param handler
	 * @return 是否拦截,false拦截,true:不拦截;
	 */
	public boolean isMyHandler(Object handler) {
		// 判断是否应该被拦截
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Interceptor interceptor = handlerMethod.getMethodAnnotation(Interceptor.class);
		// 只有被@Interceptor注解的类才会被拦截
		if (interceptor == null){
			return true;
		}
		failed = interceptor.failed();
		name = interceptor.name();

		return false;
	}

	/**
	 * 重写preHandle方法
	 */
	@Override
	public boolean preHandle(
			HttpServletRequest request,
			HttpServletResponse response,
			Object handler) throws Exception {
		if (!isMyHandler(handler)) {
			return doHandler(response, runHandler(request, response));
		}
		return super.preHandle(request, response, handler);
	}

	public abstract boolean runHandler(HttpServletRequest request, HttpServletResponse response);

	/**
	 * 根据运行结果做相应的处理
	 * 
	 * @param response
	 * @param isInterceptor
	 *         是否拦截,false拦截,true:不拦截;
	 * @return 是否拦截,false拦截,true:不拦截;
	 * @throws Exception
	 */
	public boolean doHandler(HttpServletResponse response, boolean isInterceptor) throws Exception {
		if (!isInterceptor) {
			if (!failed.equals("")) {
				// to do something
			}
			return false;
		}
		return true;
	}

	/**
	 * 自定义拦截器配套注解
	 * @author Oliver
	 * @version 20161214
	 */
	@Target(ElementType.METHOD)
	@Retention(RetentionPolicy.RUNTIME)
	public static @interface Interceptor {
		
		// 根据业务需求确定用途,也可省略,例如log打印,方法判定等
		public String name();
		
		// 根据业务需求确定用途,也可省略,例如指定失败跳转,或者失败后to do something
		public String failed() default "";
	}
}



二、创建具体拦截业务逻辑类

package com.tcl.shbc.thirdbus.invoke.interceptor;

import java.util.HashMap;
import java.util.Map;

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

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.tcl.shbc.thirdbus.contants.InvokeAuthProperties;
import com.tcl.shbc.thirdbus.contants.MessagesEnum;
import com.tcl.shbc.thirdbus.interceptor.BaseInterceptor;
import com.tcl.shbc.thirdbus.interceptor.MyHttpServletRequestWrapper;
import com.tcl.shbc.thirdbus.utils.GetRequestJsonUtils;
import com.tcl.shbc.thirdbus.utils.MD5Util;

public class AuthInterceptor extends BaseInterceptor{

	static Logger logger = LogManager.getLogger(AuthInterceptor.class);

	@Override
	public boolean runHandler(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			MyHttpServletRequestWrapper myWrapper= new MyHttpServletRequestWrapper(request);
			String jsonStr = GetRequestJsonUtils.getRequestJsonString(myWrapper);
			。。。
			return true;
		} catch (Exception e) {
			MessagesEnum.errorSet(response, MessagesEnum.ERROR_1101);
		}
		return false;
	}
}



三、创建获取request中json字符串的内容的工具类

package com.tcl.shbc.thirdbus.utils;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

public class GetRequestJsonUtils {
	/***
	 * 获取 request 中 json 字符串的内容
	 * 
	 * @param request
	 * @return : <code>byte[]</code>
	 * @throws IOException
	 */
	public static String getRequestJsonString(HttpServletRequest request)
			throws IOException {
		String submitMehtod = request.getMethod();
		// GET
		if (submitMehtod.equals("GET")) {
			return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
		// POST
		} else {
			return getRequestPostStr(request);
		}
	}

	/**	  
	 * 描述:获取 post 请求的 byte[] 数组
	 * <pre>
	 * 举例:
	 * </pre>
	 * @param request
	 * @return
	 * @throws IOException	  
	 */
	public static byte[] getRequestPostBytes(HttpServletRequest request)
			throws IOException {
		int contentLength = request.getContentLength();
		if(contentLength<0){
			return null;
		}
		byte buffer[] = new byte[contentLength];
		for (int i = 0; i < contentLength;) {

			int readlen = request.getInputStream().read(buffer, i,
					contentLength - i);
			if (readlen == -1) {
				break;
			}
			i += readlen;
		}
		return buffer;
	}

	/**	  
	 * 描述:获取 post 请求内容
	 * <pre>
	 * 举例:
	 * </pre>
	 * @param request
	 * @return
	 * @throws IOException	  
	 */
	public static String getRequestPostStr(HttpServletRequest request)
			throws IOException {
		byte buffer[] = getRequestPostBytes(request);
		String charEncoding = request.getCharacterEncoding();
		if (charEncoding == null) {
			charEncoding = "UTF-8";
		}
		return new String(buffer, charEncoding);
	}
}



四、重写HttpServletRequestWrapper方法

package com.tcl.shbc.thirdbus.interceptor;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.springframework.util.StreamUtils;

/**
 * 重写HttpServletRequestWrapper方法
 * @author Oliver
 * @version 20161214
 */
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
	private byte[] requestBody = null;

	public MyHttpServletRequestWrapper (HttpServletRequest request) {

		super(request);

		//缓存请求body
		try {
			requestBody = StreamUtils.copyToByteArray(request.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 重写 getInputStream()
	 */
	@Override
	public ServletInputStream getInputStream() throws IOException {
		if(requestBody == null){
			requestBody= new byte[0];
		}
		final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);
		return new ServletInputStream() {
			@Override
			public int read() throws IOException {
				return bais.read();
			}
		};
	}

	/**
	 * 重写 getReader()
	 */
	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}
}



五、创建一个实现Filter的类,重写doFilter方法,将ServletRequest替换为自定义的request类

package com.tcl.shbc.thirdbus.interceptor;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 创建一个实现Filter的类,重写doFilter方法,将ServletRequest替换为自定义的request类
 * @author Oliver
 * @version 20161214
 */
public class HttpServletRequestReplacedFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		ServletRequest requestWrapper = null;
		if(request instanceof HttpServletRequest) {
			requestWrapper = new MyHttpServletRequestWrapper((HttpServletRequest) request);
		}
		if(requestWrapper == null) {
			chain.doFilter(request, response);
		} else {
			chain.doFilter(requestWrapper, response);
		}	
	} 
	

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
}



六、在配置文件中添加<filter>

	<filter>
		<filter-name>requestFilter</filter-name>
		<filter-class>com.tcl.shbc.thirdbus.interceptor.HttpServletRequestReplacedFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>requestFilter</filter-name>
		<url-pattern>*.do</url-pattern>
	</filter-mapping>


GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e 4 个月前
8c391e04 7 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐