商城项目实战28:内容管理
1.1. 内容列表
1.1.1. 需求
请求的url:
/content/query/list
响应的数据格式:
EasyUIResult
1.1.2. Mapper
使用逆向生成的mapper文件。
1.1.3. Service
@Service public class ContentServiceImpl implements ContentService {
@Autowired private TbContentMappercontentMapper; @Override public EasyUIResult getContentList(long catId, Integerpage, Integer rows) throws Exception { //根据category_id查询内容列表 TbContentExample example = new TbContentExample(); Criteria criteria = example.createCriteria(); criteria.andCategoryIdEqualTo(catId); //分页处理 PageHelper.startPage(page, rows); List<TbContent> list = contentMapper.selectByExampleWithBLOBs(example); //取分页信息 PageInfo<TbContent> pageInfo = new PageInfo<>(list); EasyUIResult result = new EasyUIResult(pageInfo.getTotal(),list); return result; }
} |
1.1.4. Controller
@Controller @RequestMapping("/content") public class ContentController { @Autowired private ContentServicecontentService; @RequestMapping("/query/list") @ResponseBody public EasyUIResult getContentList(LongcategoryId, Integer page, Integer rows) throws Exception { EasyUIResult result = contentService.getContentList(categoryId,page, rows); return result; } } |
1.2. 添加内容
1.2.1. 需求
点击新增按钮,打开content-add.jsp
点击提交按钮,使用ajax把表单中的数据提交给服务器。
1、请求的url:
/content/save
2、请求的参数
表单中的数据
3、响应的数据格式
TaotaoResult
1.2.2. Mapper
创建一个添加内容的mapper文件,实现向tb_content表中添加数据的功能。使用****生成。
1.2.3. Service
@Override public TaotaoResult addContent(TbContentcontent) throws Exception { //把图片信息保存至数据库 content.setCreated(new Date()); content.setUpdated(new Date()); //把内容信息添加到数据库 contentMapper.insert(content); return TaotaoResult.ok(); }
|
1.2.4. Controller
@RequestMapping("/save") @ResponseBody public TaotaoResult addContent(TbContentcontent) throws Exception { TaotaoResult result = contentService.addContent(content); return result; } |
1.3. 修改内容
...
1.4. 删除内容
...
2. 服务层发布服务
2.1. 需求
根据内容的分类ID查询内容列表。
请求的url:
/rest/content/category/{cid}
参数:categoryId
响应的数据格式:
TaoTaoResult
2.2. Mapper
创建一可以根据分类id查询内容列表的mapper。使用****生成的mapper即可。
2.3. Service
@Service public class ContentServiceImplimplements ContentService {
@Autowired private TbContentMappercontentMapper; @Override public TaotaoResult getContentList(long cid)throws Exception { TbContentExample example = new TbContentExample(); //添加条件 Criteria criteria = example.createCriteria(); criteria.andCategoryIdEqualTo(cid); List<TbContent> list = contentMapper.selectByExample(example); return TaotaoResult.ok(list); }
} |
2.4. Controller
@Controller @RequestMapping("/content") public class ContentController {
@Autowired private ContentServicecontentService; @RequestMapping("/category/{cid}") @ResponseBody public TaotaoResult getContentList(@PathVariable Longcid) { TaotaoResult result = null; try { result = contentService.getContentList(cid); } catch (Exception e) { e.printStackTrace(); return TaotaoResult.build(500,e.getMessage()); } return result; } }
|
3. 首页大广告方案
前端系统获取后端系统提供的接口,如何获取?
3.1. 方案1
jsonp跨域请求
优点:
1、 效率高,没有通过后台中转
2、 减少内网的带宽开销
缺点:
网页中无内容,不利于搜索引擎优化。
3.2. 方案二
通过后台java代码调用服务层
优点:
1、 网页中内容是变化的有利于搜索引擎优化
缺点:
1、 接口调用经过后台中转,效率较低,事实上可以忽略不计。
4. Httpclient
4.1. 什么是httpclient
HTTP 协议可能是现在 Internet上使用得最多、最重要的协议了,越来越多的
Java应用程序需要直接通过
HTTP协议来访问网络资源。虽然在
JDK的
java net包中已经提供了访问HTTP
协议的基本功能,但是对于大部分应用程序来说,JDK库本身提供的功能还不够丰富和灵活。HttpClient是
Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持
HTTP协议的客户端编程工具包,并且它支持
HTTP协议最新的版本和建议。
下载地址:
4.2. 功能介绍
以下列出的是 HttpClient 提供的主要的功能,要知道更多详细的功能可以参见 HttpClient 的主页。
(1)实现了所有 HTTP 的方法(GET,POST,PUT,HEAD等)
(2)支持自动转向
(3)支持 HTTPS 协议
(4)支持代理服务器等
4.3. 导入依赖
4.4. 执行GET请求
public class DoGET {
public static void main(String[]args) throws Exception {
// 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http GET请求 HttpGet httpGet = new HttpGet("http://www.baidu.com/");
CloseableHttpResponse response =null; try { // 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { String content = EntityUtils.toString(response.getEntity(),"UTF-8"); System.out.println("内容长度:" +content.length()); // FileUtils.writeStringToFile(new File("C:\\baidu.html"), content); } } finally { if (response !=null) { response.close(); } httpclient.close(); }
}
} |
4.5. 执行GET带参数
public class DoGETParam {
public static void main(String[]args) throws Exception {
// 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault();
// 定义请求的参数 URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd","java").build();
System.out.println(uri);
// 创建http GET请求 HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse response =null; try { // 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { String content = EntityUtils.toString(response.getEntity(),"UTF-8"); System.out.println(content); } } finally { if (response !=null) { response.close(); } httpclient.close(); }
}
} |
4.6. 执行post请求
public class DoPOST {
public static void main(String[]args) throws Exception {
// 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http POST请求 HttpPost httpPost = new HttpPost("http://www.oschina.net/");
CloseableHttpResponse response =null; try { // 执行请求 response = httpclient.execute(httpPost); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { String content = EntityUtils.toString(response.getEntity(),"UTF-8"); System.out.println(content); } } finally { if (response !=null) { response.close(); } httpclient.close(); }
}
} |
4.7. 带参数的post请求
public class DoPOSTParam {
public static void main(String[]args) throws Exception {
// 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http POST请求 HttpPost httpPost = new HttpPost("http://www.oschina.net/search");
// 设置2个post参数,一个是scope、一个是q List<NameValuePair> parameters =new ArrayList<NameValuePair>(0); parameters.add(new BasicNameValuePair("scope","project")); parameters.add(new BasicNameValuePair("q","java")); // 构造一个form表单式的实体 UrlEncodedFormEntity formEntity =new UrlEncodedFormEntity(parameters); // 将请求实体设置到httpPost对象中 httpPost.setEntity(formEntity);
CloseableHttpResponse response =null; try { // 执行请求 response = httpclient.execute(httpPost); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { String content = EntityUtils.toString(response.getEntity(),"UTF-8"); System.out.println(content); } } finally { if (response !=null) { response.close(); } httpclient.close(); }
}
} |
4.8. 封装HttpClient通用工具类
public class HttpClientUtil {
public static String doGet(Stringurl, 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 (IOExceptione) { e.printStackTrace(); } } return resultString; }
public static String doGet(Stringurl) { return doGet(url,null); }
public static String doPost(Stringurl, 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 (IOExceptione) { // TODO Auto-generated catch block e.printStackTrace(); } }
return resultString; }
public static String doPost(Stringurl) { return doPost(url,null); } }
|
5. 实现大广告位
5.1. 需求分析
在首页展示大广告位需要一个json数据来实现。
index.jsp
只需要生成此格式的json数据就可以了:
5.2. Mapper
取广告位信息,不需要mapper。
5.3. Service
调用服务层的服务根据内容分类id查询内容管理系统的内容。
需要一个描述数据结构的pojo类
public class ADItem {
private Integer height; private Integer width; private String src; private Integer heightB; private Integer widthB; private String srcB; private String alt; private String href; } |
@Service public class ADServiceImplimplements AdService {
@Value("${REST_BASE_URL}") private String REST_BASE_URL; @Value("${INDEX_AD1_URL}") private String INDEX_AD1_URL; @Override public String getAdItemList()throws Exception { //调用服务层的服务查询打广告位的数据 String result = HttpClientUtil.doGet(REST_BASE_URL +INDEX_AD1_URL); //把json数据转换成对象 TaotaoResult taotaoResult = TaotaoResult.formatToList(result, TbContent.class); List<ADItem> itemList = new ArrayList<>(); if (taotaoResult.getStatus() == 200 ) { List<TbContent> contentList = (List<TbContent>)taotaoResult.getData(); for (TbContent tbContent : contentList) { ADItem item = new ADItem(); item.setHeight(240); item.setWidth(670); item.setSrc(tbContent.getPic()); item.setHeightB(240); item.setWidth(550); item.setSrcB(tbContent.getPic2()); item.setAlt(tbContent.getTitleDesc()); item.setHref(tbContent.getUrl()); itemList.add(item); } } return JsonUtils.objectToJson(itemList); }
} |
5.4. Controller
@Controller public class PageController { @Autowired private AdService adService;
@RequestMapping("/index") public String showIndex(Modelmodel) throws Exception { String adResult = adService.getAdItemList(); model.addAttribute("ad1",adResult); return "index"; } } |
5.5. Jsp页面