newstyles项目实战(十八)大广告位轮播图展示方案分析,内容服务发布及HttpClient使用

    广告位的展示有多种方案,这里列举了两种常用的方案进行展示:

1.json跨域请求:


需要当首页加载完毕后,大广告位就应该显示。没有触发事件,不是太合适。也就是说我们没有事件时,3的请求设置就不太合理。调用rest服务层的工作就依赖于事件的触发。
优点:不需要二次请求,页面直接加载内容数据。减少门户系统的压力。这样的话可以减少对protal系统的压力,因为大部分的工作都集中在rest服务层上。

缺点:当页面进行加载的时候,页面中的某些内容需要延迟加载。这样不利于seo优化。

2,第二种方案:


优点:有利于seo优化。可以在taotao-portal中对数据进行加工。系统直接服务的调用,需要使用httpclient来实现。Taotao-portal和taotao-rest是在同一个局域网内部。速度非常快,调用时间可以忽略不计。

缺点:系统直接需要调用服务查询内容信息。多了一次http请求。不过由于大部分都处在一个局域网内,其对应响应速度的影响不是太大。

所以在这里我们选择第二种方法,其主要的工作流程如下:



3.内容服务发布:

从上面的分析以及我们确定方案,需要我们更改下rest服务层,并且将门户所需要的服务进行发布:

Dao层:

从tb_content表中查询,根据内容分类id查询。是单表查询。可以使用逆向工程生成的代码。

Service层:

接收内容分类id,根据分类id查询分类列表。返回一个内容pojo列表。参数:分类id,也即,categoryId;返回值:pojo列表

@Service
public class ContentServiceImpl implements ContentService {
 
	@Autowired
	private TbContentMapper contentMapper;
	
	@Override
	public List<TbContent> getContentList(long contentCid) {

		//根据内容分类id查询列表
		TbContentExample example = new TbContentExample();
		Criteria criteria = example.createCriteria();
		criteria.andCategoryIdEqualTo(contentCid);
		List<TbContent> list = contentMapper.selectByExample(example);

		return list;
	}

}
Controller层:

发布服务。接收查询参数。Restful风格内容分类id应该从url中取。/rest/content/list/{contentCategoryId}
从url中取内容分类id,调用Service查询内容列表。返回内容列表。返回一个json格式的数据。可以使用NewstylesResult包装此列表。

@Controller
@RequestMapping("/content")
public class ContentController {

	@Autowired
	private ContentService contentService;
	
	@RequestMapping("/list/{contentCategoryId}")
	@ResponseBody
	public NewstylesResult getContentList(@PathVariable long contentCategoryId){
		try{
			List<TbContent> list = contentService.getContentList(contentCategoryId);
			return NewstylesResult.ok(list);
		}catch(Exception e){
			e.printStackTrace();
			return NewstylesResult.build(500, ExceptionUtil.getStackTrace(e));
		}
	}
}

到这里可以启动rest工程和manager工程,在浏览器输入:http://localhost:8081/rest/content/list/89

可以得到如下返回信息:


这说明我们的服务发布成功。

4.HttpClient的使用

HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。下载地址:http://hc.apache.org/

需要把httpclient的jar包添加到工程中。只需要在工程中添加httpclient的依赖。


使用方法:

下面就HttpClient中可能在本工程中用到的方法进行了测试,这些测试方法模拟在protal工程中发出请求等:

public class HttpClientTest {

	public void doGet() throws Exception{
		//创建一个httpClient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//创建一个GET对象
		HttpGet get = new HttpGet("http://www.sougou.com");
		//执行请求
		CloseableHttpResponse response = httpClient.execute(get);
		//相应结果
		int statusCode = response.getStatusLine().getStatusCode();
		System.out.println(statusCode);
		HttpEntity entity = response.getEntity();
		//将entity的内容读入到一个字符串里面
		String string = EntityUtils.toString(entity, "utf-8");
		System.out.println(string);
		//关闭请求
		response.close();
		httpClient.close();

	}
	//@Test
	public void doGetWithParam() throws Exception{
		
		//创建可关闭的对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//创建一个uri
		URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web");
		uriBuilder.addParameter("query", "花千骨");
		HttpGet get = new HttpGet(uriBuilder.build());
		//执行请求
		CloseableHttpResponse response = httpClient.execute(get);
		//相应结果
		int statusCode = response.getStatusLine().getStatusCode();
		System.out.println(statusCode);
		HttpEntity entity = response.getEntity();
		//将entity的内容读入到一个字符串里面
		String string = EntityUtils.toString(entity, "utf-8");
		System.out.println(string);
		//关闭请求
		response.close();
		httpClient.close();
	}
	
//	@Test
	public void doPost() throws Exception{
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//创建一个post对象
		HttpPost post = new HttpPost("http://localhost:8082/httpClient/post.html");
		//执行post请求
		CloseableHttpResponse response = httpClient.execute(post);
		String string = EntityUtils.toString(response.getEntity());
		System.out.println(string);
		response.close();
		httpClient.close();
	}
	
	
	public void test(){
		String REST_BASE_URL = "http://localhost:8081/rest/";
		String REST_INDEX_AD_URL = "content/list/89";
		String result = HttpClientUtil.doGet(REST_BASE_URL+REST_INDEX_AD_URL);
		System.out.println(result);
		//把字符串转换成NEWSTYLESRESULT
		try{
			NewstylesResult newstylesResult = NewstylesResult.formatToList(result, TbContent.class);
			//取出内容列表
			List<TbContent> list = (List<TbContent>) newstylesResult.getData();
			List<Map> reslultList = new ArrayList<>();
			//创建jsp页面要求的pojolist列表
			for (TbContent tbContent : list) {
				Map map = new HashMap<>();
				map.put("src", tbContent.getPic());
				map.put("height", 240);
				map.put("width", 670);
				map.put("srcB", tbContent.getPic2());
				map.put("widthB", 550);
				map.put("heightB", 240);
				map.put("href", tbContent.getUrl());
				map.put("alt", tbContent.getSubTitle());
				reslultList.add(map);
			}
			String sss = JsonUtils.objectToJson(reslultList);
			System.out.println(sss);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

HttpClientUtils代码如下:

public class HttpClientUtil {

	public static String doGet(String url, Map<String, String> param) {

		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();

			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);

			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static String doGet(String url) {
		return doGet(url, null);
	}

	public static String doPost(String url, Map<String, String> param) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建参数列表
			if (param != null) {
				List<NameValuePair> paramList = new ArrayList<>();
				for (String key : param.keySet()) {
					paramList.add(new BasicNameValuePair(key, param.get(key)));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
				httpPost.setEntity(entity);
			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return resultString;
	}

	public static String doPost(String url) {
		return doPost(url, null);
	}
	
	public static String doPostJson(String url, String json) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建请求内容
			StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return resultString;
	}
}
这样对于大广告位的准备工作就告一段落,下面着手处理打广告位的展示工作。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值