项目需求:
jsonp是从前台js的角度考虑,通过Ajax调用springMVC的接口。同一个ip、同一个网络协议、同一个端口,三者都满足就是同一个域,否则就是跨域问题了。首页广告需要一个轮播的效果,取后台数据json格式。上篇博客介绍了使用jsonp来解决跨域,现在有个新的方法来解决,那就是:ajax请求地址改为自己系统的后台地址,之后在自己的后台用HttpClient请求url。封装好的跨域请求url工具类。封装一个get一个POST即可。
两者的区别就在于,jsonp是基于客户端的跨域解决。而httpclient是基于服务端的跨域解决。
我现在有两个maven项目:
Taotao-portal(8082端口)
Taotao-rest(8081端口)
要使用httpclient需要在maven中引用(portal):
org.apache.httpcomponents
httpclient
org.apache.httpcomponents
httpclient
rest项目中写了个后台的服务调广告的数据,在portal项目中的service层来调用rest项目中的controller层提供的服务。
httpclient工作图解:
核心代码展示:
(portal项目)contentcontroller.java
@Controller
publicclassContentController {
@Autowired
privateContentService contentService;
//getdata
@RequestMapping("/content/{cid}")
@ResponseBody
publicTaotaoResult getConentList(@PathVariableLong cid){
try{
List list=contentService.getContentList(cid);
returnTaotaoResult.ok(list);
} catch(Exception e) {
e.printStackTrace();
returnTaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
}
}
}@Controller
public class ContentController {
@Autowired
private ContentService contentService;
//getdata
@RequestMapping("/content/{cid}")
@ResponseBody
public TaotaoResult getConentList(@PathVariable Long cid){
try {
List<TbContent> list=contentService.getContentList(cid);
return TaotaoResult.ok(list);
} catch (Exception e) {
e.printStackTrace();
return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
}
}
}
(portal项目)HttpClientUtil.java
packagecom.taotao.common.utils;
importjava.io.IOException;
importjava.net.URI;
importjava.util.ArrayList;
importjava.util.List;
importjava.util.Map;
importorg.apache.http.NameValuePair;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.CloseableHttpResponse;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.client.utils.URIBuilder;
importorg.apache.http.entity.ContentType;
importorg.apache.http.entity.StringEntity;
importorg.apache.http.impl.client.CloseableHttpClient;
importorg.apache.http.impl.client.HttpClients;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.util.EntityUtils;
publicclassHttpClientUtil {