Spring集成CXF获取HttpServletRequest,HttpServletResponse
最近的项目中,在Spring继承CXF中要用到request来获取IP,所以先要获取到HttpServletRequest对象,具体方法如下:
1、配置文件:
1 <jaxrs:server id="aslRest" address="/"> 2 <jaxrs:inInterceptors> 3 <bean class="org.apache.cxf.interceptor.LoggingInInterceptor" /> 4 </jaxrs:inInterceptors> 5 6 <jaxrs:serviceBeans> 8 <ref bean="umpgServiceInf"/> 10 </jaxrs:serviceBeans> 11 12 <jaxrs:providers> 13 <bean class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider"/> 14 </jaxrs:providers> 15 16 </jaxrs:server>
2、代码实现:
1 package com.zat.asl.output.service.impl; 2 3 import com.alibaba.fastjson.JSONObject; 4 import com.alibaba.fastjson.parser.Feature; 5 import com.zat.asl.output.service.inf.UmpgServiceInf; 6 import com.zat.asl.output.service.inf.UmpgServiceProxyInf; 7 import com.zat.asl.service.AbstractService; 8 import com.zat.asl.util.AslUtils; 9 import org.apache.cxf.message.Message; 10 import org.apache.cxf.phase.PhaseInterceptorChain; 11 import org.apache.cxf.transport.http.AbstractHTTPDestination; 12 import org.apache.log4j.Logger; 13 import org.springframework.stereotype.Service; 14 import org.springframework.util.StringUtils; 15 16 import javax.annotation.Resource; 17 import javax.servlet.http.HttpServletRequest; 18 import javax.ws.rs.core.Response; 19 20 @Service("umpgServiceInf") 21 public class UmpgServiceImpl extends AbstractService implements UmpgServiceInf { 22 23 Logger logger = Logger.getLogger(UmpgServiceImpl.class); 24 @Resource(name="umpgServiceProxyInf") 25 private UmpgServiceProxyInf umpgServiceProxyInf; 26 27 @Override 28 public Response gateway(String request) { 29 String resp = null; 30 try{ 31 Message message = PhaseInterceptorChain.getCurrentMessage(); 32 HttpServletRequest httpServletRequest = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST); 33 String realIp = httpServletRequest.getHeader("X-Real-IP"); 35 logger.info("客户端真实IP>>>realIp=" + realIp + ",forwardedFor=" + forwardedFor); 36 37 String requestWithIp = request; 38 if (!StringUtils.isEmpty(realIp)) { 39 JSONObject reqJson = JSONObject.parseObject(request, Feature.OrderedField); 40 reqJson.put("clientRealIp", realIp); 41 requestWithIp = JSONObject.toJSONString(reqJson); 42 logger.info("原始的request=" + request); 43 logger.info("注入IP的request=" + requestWithIp); 44 } 45 resp = umpgServiceProxyInf.gateway(requestWithIp); 46 }catch(Exception e){ 47 logger.error(e.getMessage(),e); 48 return getErrorResponse(AslUtils.ASL_RESP_DATA_TYPE_JSON, AslUtils.ASL_RESPCODE_9999); 49 } 50 return getSuccessResponse(resp); 51 } 52 }