CXF拦截器Interceptor实现自定义消息,并以json格式返回


一、在拦截器中组装要返回的自定义消息


//组装返回自定义信息类
resHeader.setRetCode(RetCode.IP_ERROR);
resHeader.setRetMessage("非准入IP地址!");
//将返回信息转换成json格式
String res = jsonObjectMapper.writeValueAsString(resHeader);
//调用工具类返回自定义消息
InterceptorUtils.resMessage(message, res);
//终止拦截链,不会往下执行到接口方法
message.getInterceptorChain().abort();
return;


二、调用InterceptorUtils工具类实现返回自定义消息


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.cxf.message.Message;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class InterceptorUtils {

	private static Logger logger = LoggerFactory
			.getLogger(InterceptorUtils.class);

	public static void resMessage(Message arg0, String message) {

		logger.info("返回请求拦截信息:" + message);

		try {

			HttpServletResponse response = (HttpServletResponse) arg0
					.get(AbstractHTTPDestination.HTTP_RESPONSE);

			ServletOutputStream out = response.getOutputStream();

			try {
				out.write(message.getBytes("utf-8"));
				out.flush();
				arg0.getInterceptorChain().doInterceptStartingAfter(arg0,
						"org.apache.cxf.jaxrs.interceptor.JAXRSOutInterceptor");
			} catch (Exception e) {
				e.printStackTrace();
			}
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}


三、拦截器配置



			
	
	
	 
	
		
		
			
		
		
		
			
		
	


四、返回信息样例

{"retCode":"4011","retMessage":"非准入IP地址!"}





你可能感兴趣的:(CXF拦截器Interceptor实现自定义消息,并以json格式返回)