目录
1. 首页的动态实现分析
网站的首页的实现必须是动态的,可以在后台管理维护。
CMS – 内容管理系统
思路:
1、 分析每个模块的共性
a) 链接
b) 图片
c) 标题
d) 子标题
2、 使用两张表来管理
a) 内容分类表,管理内容的大分类
b) 内容表,存储每个分类下的明细信息内容。
首页的内容需要动态管理,需要后台管理功能。
抽取首页展示内容的共性:
1、有一张图片
2、有一个连接
3、有一个标题
4、有链接的提示
5、价格
需要把内容进行分类,分类应该是一个树形结构。
在展示首页时,可以根据分类取内容信息,把内容展示到页面。
在后台管理内容及内容分类的系统就叫做cms系统。
2. Cms系统
先实现内容的分类管理再实现内容管理。
2.1. 首页大广告的展示流程
2.2 内容分类管理
2.2.1 需求分析
内容列表
新增节点
。。。。
使用右键菜单管理内容分类
2.2.2 页面展示
index.jsp
【/taotao-manager-web】—【/src/main/webapp/WEB-INF/jsp/】—【index.jsp】
content-category.jsp
【/taotao-manager-web】—【/src/main/webapp/WEB-INF/jsp/】—【content-category.jsp】
初始化树形视图的url:/content/category/list
参数是id,当前节点id属性,应该根据此id查询子节点列表。
返回值:包含id、text、state三个属性的json数据列表
Dao层
需要一张表存储内容数据:字段:标题、url、子标题、image、内容分类id等等
需要一张表存储内容的分类信息,树形结构的表。
内容分类表:
内容分类表:tb_content_category
Sql语句:
根据parentid查询节点列表
SELECT * FROM `tb_content_category` WHERE parent_id = 30;
单表查询可以实现逆向工程生成的代码。
数据库设计
需要一张表存储内容数据:字段:标题、url、子标题、image、内容分类id等等
需要一张表存储内容的分类信息,树形结构的表。
内容分类表:
内容表:
Service层
功能:接收parentid。根据parentid查询节点列表,返回返回一个EasyUI异步Tree要求的节点列表。每个节点包含三个属性id、text、state三个属性。可以使用EUTreeNode。
参数:id
返回值:List
EUTreeNode.java
【/taotao-common】—【/src/main/java】—【/com/taotao/common/pojo/】—【EUTreeNode.java】
package com.taotao.common.pojo;
//easyUI树形控件节点格式
public class EUTreeNode {
private long id;
private String text;
private String state;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
ContentCategoryService.java
【/taotao-manager-service】—【/src/main/java】—【/com/taotao/service/】—【ContentCategoryService.java】
package com.taotao.service;
import java.util.List;
import com.taotao.common.pojo.EUTreeNode;
import com.taotao.common.utill.TaotaoResult;
//内容分类管理
public interface ContentCategoryService {
List<EUTreeNode> getCategoryList(long parentId);
}
ContentCategoryServiceImpl.java
【/taotao-manager-service】—【/src/main/java】—【/com/taotao/service/impl/】—【ContentCategoryServiceImpl.java】
package com.taotao.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.taotao.common.pojo.EUTreeNode;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.mapper.TbContentCategoryMapper;
import com.taotao.pojo.TbContentCategory;
import com.taotao.pojo.TbContentCategoryExample;
import com.taotao.pojo.TbContentCategoryExample.Criteria;
import com.taotao.service.ContentCategoryService;
//内容分类管理
@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {
@Autowired
private TbContentCategoryMapper contentCategoryMapper;
@Override
public List<EUTreeNode> getCategoryList(long parentId) {
// 根据parentid查询节点列表
TbContentCategoryExample example = new TbContentCategoryExample();
Criteria criteria = example.createCriteria();
criteria.andParentIdEqualTo(parentId);
// 执行查询
List<TbContentCategory> list = contentCategoryMapper.selectByExample(example);
List<EUTreeNode> resultList = new ArrayList<>();
for (TbContentCategory tbContentCategory : list) {
// 创建一个节点
EUTreeNode node = new EUTreeNode();
node.setId(tbContentCategory.getId());
node.setText(tbContentCategory.getName());
node.setState(tbContentCategory.getIsParent() ? "closed" : "open");
resultList.add(node);
}
return resultList;
}
}
Controller
接收页面传递过来的parentid,根据parentid查询节点列表。返回List。需要响应json数据。
ContentCategoryController.java
【/taotao-manager-web】—【/src/main/java】—【/com/taotao/controller/】—【ContentCategoryController.java】
package com.taotao.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taotao.common.pojo.EUTreeNode;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.service.ContentCategoryService;
//内容分类管理
@Controller
@RequestMapping("/content/category")
public class ContentCategoryController {
@Autowired
private ContentCategoryService contentCategoryService;
@RequestMapping("/list")
@ResponseBody
public List<EUTreeNode> getContentCatList(@RequestParam(value = "id", defaultValue = "0") Long parentId) {
List<EUTreeNode> list = contentCategoryService.getCategoryList(parentId);
return list;
}
}
2.2.3 运行:
内容分类管理实际上是一个树形结构的管理,新增子节点、重命名、删除(级联删除所有的子节点)
2.3 内容分类添加
2.3.1. 需求分析
content-category.jsp
【/taotao-manager-web】—【/src/main/webapp/WEB-INF/jsp/】—【content-category.jsp】
请求的url:/content/category/create
内容分类表:tb_content_category
参数:
1、parentId父节点id
2、name:当前节点的名称
返回值:TaotaoResult。其中包含节点pojo对象。
2.3.2 Dao层
可以使用逆向工程生成的代码
2.3.3 Service层
功能:接收两个参数parentId父节点id、name:当前节点的名称。向tb_content_category表中添加一条记录。返回TaoTaoResult包含记录的pojo对象。
需要返回主键信息:(mapper貌似不用修改也能实现)
需要修改mapper文件,返回主键信息。
TbContentCategoryMapper.xml
【/taotao-manager-mapper】—【/src/main/java】—【/com/taotao/mapper/】—【TbContentCategoryMapper.xml】
<selectKey keyProperty="id" resultType="long" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
ContentCategoryService.java
【/taotao-manager-service】—【/src/main/java】—【/com/taotao/service/】—【ContentCategoryService.java】
package com.taotao.service;
import java.util.List;
import com.taotao.common.pojo.EUTreeNode;
import com.taotao.common.utill.TaotaoResult;
//内容分类管理
public interface ContentCategoryService {
List<EUTreeNode> getCategoryList(long parentId);
TaotaoResult insertContentCategory(long parentId, String name);
}
ContentCategoryServiceImpl.java
【/taotao-manager-service】—【/src/main/java】—【/com/taotao/service/impl/】—【ContentCategoryServiceImpl.java】
package com.taotao.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.taotao.common.pojo.EUTreeNode;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.mapper.TbContentCategoryMapper;
import com.taotao.pojo.TbContentCategory;
import com.taotao.pojo.TbContentCategoryExample;
import com.taotao.pojo.TbContentCategoryExample.Criteria;
import com.taotao.service.ContentCategoryService;
//内容分类管理
@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {
@Autowired
private TbContentCategoryMapper contentCategoryMapper;
@Override
public List<EUTreeNode> getCategoryList(long parentId) {
// 根据parentid查询节点列表
TbContentCategoryExample example = new TbContentCategoryExample();
Criteria criteria = example.createCriteria();
criteria.andParentIdEqualTo(parentId);
// 执行查询
List<TbContentCategory> list = contentCategoryMapper.selectByExample(example);
List<EUTreeNode> resultList = new ArrayList<>();
for (TbContentCategory tbContentCategory : list) {
// 创建一个节点
EUTreeNode node = new EUTreeNode();
node.setId(tbContentCategory.getId());
node.setText(tbContentCategory.getName());
node.setState(tbContentCategory.getIsParent() ? "closed" : "open");
resultList.add(node);
}
return resultList;
}
@Override
public TaotaoResult insertContentCategory(long parentId, String name) {
// 创建一个pojo
TbContentCategory contentCategory = new TbContentCategory();
contentCategory.setName(name);
contentCategory.setIsParent(false);
// '状态。可选值:1(正常),2(删除)',
contentCategory.setStatus(1);
contentCategory.setParentId(parentId);
contentCategory.setSortOrder(1);
contentCategory.setCreated(new Date());
contentCategory.setUpdated(new Date());
// 添加记录
contentCategoryMapper.insert(contentCategory);
// 查看父节点的isParent列是否为true,如果不是true改成true
TbContentCategory parentCat = contentCategoryMapper.selectByPrimaryKey(parentId);
// 判断是否为true
if (!parentCat.getIsParent()) {
parentCat.setIsParent(true);
// 更新父节点
contentCategoryMapper.updateByPrimaryKey(parentCat);
}
// 返回结果
return TaotaoResult.ok(contentCategory);
}
}
2.3.4 Controller
接收两个参数parentid、name。调用Service添加记录。返回TaotaoResult。应该返回json数据。
ContentCategoryController.java
【/taotao-manager-web】—【/src/main/java】—【/com/taotao/controller/】—【ContentCategoryController.java】
package com.taotao.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taotao.common.pojo.EUTreeNode;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.service.ContentCategoryService;
//内容分类管理
@Controller
@RequestMapping("/content/category")
public class ContentCategoryController {
@Autowired
private ContentCategoryService contentCategoryService;
@RequestMapping("/list")
@ResponseBody
public List<EUTreeNode> getContentCatList(@RequestParam(value = "id", defaultValue = "0") Long parentId) {
List<EUTreeNode> list = contentCategoryService.getCategoryList(parentId);
return list;
}
@RequestMapping("/create")
@ResponseBody
public TaotaoResult createContentCategory(Long parentId, String name) {
TaotaoResult result = contentCategoryService.insertContentCategory(parentId, name);
return result;
}
}
2.4 内容分类删除
2.4.1. 需求分析
content-category.jsp
【/taotao-manager-web】—【/src/main/webapp/WEB-INF/jsp/】—【content-category.jsp】
请求的url:
/content/category/delete/
参数:
1、parentId
2、Id
返回值:TaotaoResult
业务逻辑:
接收parentid、id两个参数。删除id对应的记录。需要判断parentid对应的记录下是否有子节点。如果没有子节点。需要把parentid对应的记录的isparent改成false。
注意:删除直接是物理删除。
2.3.2 Dao层
可以使用逆向工程生成的代码
2.3.3 Service层
ContentCategoryService.java
【/taotao-manager-service】—【/src/main/java】—【/com/taotao/service/】—【ContentCategoryService.java】
package com.taotao.service;
import java.util.List;
import com.taotao.common.pojo.EUTreeNode;
import com.taotao.common.utill.TaotaoResult;
//内容分类管理
public interface ContentCategoryService {
List<EUTreeNode> getCategoryList(long parentId);
TaotaoResult insertContentCategory(long parentId, String name);
TaotaoResult deleteContentCategory(Long id);
}
ContentCategoryServiceImpl.java
【/taotao-manager-service】—【/src/main/java】—【/com/taotao/service/impl/】—【ContentCategoryServiceImpl.java】
package com.taotao.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.taotao.common.pojo.EUTreeNode;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.mapper.TbContentCategoryMapper;
import com.taotao.pojo.TbContentCategory;
import com.taotao.pojo.TbContentCategoryExample;
import com.taotao.pojo.TbContentCategoryExample.Criteria;
import com.taotao.service.ContentCategoryService;
//内容分类管理
@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {
@Autowired
private TbContentCategoryMapper contentCategoryMapper;
@Override
public List<EUTreeNode> getCategoryList(long parentId) {
// 根据parentid查询节点列表
TbContentCategoryExample example = new TbContentCategoryExample();
Criteria criteria = example.createCriteria();
criteria.andParentIdEqualTo(parentId);
// 执行查询
List<TbContentCategory> list = contentCategoryMapper.selectByExample(example);
List<EUTreeNode> resultList = new ArrayList<>();
for (TbContentCategory tbContentCategory : list) {
// 创建一个节点
EUTreeNode node = new EUTreeNode();
node.setId(tbContentCategory.getId());
node.setText(tbContentCategory.getName());
node.setState(tbContentCategory.getIsParent() ? "closed" : "open");
resultList.add(node);
}
return resultList;
}
@Override
public TaotaoResult insertContentCategory(long parentId, String name) {
// 创建一个pojo
TbContentCategory contentCategory = new TbContentCategory();
contentCategory.setName(name);
contentCategory.setIsParent(false);
// '状态。可选值:1(正常),2(删除)',
contentCategory.setStatus(1);
contentCategory.setParentId(parentId);
contentCategory.setSortOrder(1);
contentCategory.setCreated(new Date());
contentCategory.setUpdated(new Date());
// 添加记录
contentCategoryMapper.insert(contentCategory);
// 查看父节点的isParent列是否为true,如果不是true改成true
TbContentCategory parentCat = contentCategoryMapper.selectByPrimaryKey(parentId);
// 判断是否为true
if (!parentCat.getIsParent()) {
parentCat.setIsParent(true);
// 更新父节点
contentCategoryMapper.updateByPrimaryKey(parentCat);
}
// 返回结果
return TaotaoResult.ok(contentCategory);
}
@Override
public TaotaoResult deleteContentCategory(Long id) {
// TODO Auto-generated method stub
TbContentCategory contentCategory = contentCategoryMapper.selectByPrimaryKey(id);
if (contentCategory.getIsParent()) {
List<EUTreeNode> list = getCategoryList(id);
// 递归删除
for (EUTreeNode tbcontentCategory : list) {
deleteContentCategory(tbcontentCategory.getId());
}
}
if (getCategoryList(contentCategory.getParentId()).size() == 1) {
TbContentCategory parentCategory = contentCategoryMapper.selectByPrimaryKey(contentCategory.getParentId());
parentCategory.setIsParent(false);
contentCategoryMapper.updateByPrimaryKey(parentCategory);
}
contentCategoryMapper.deleteByPrimaryKey(id);
return TaotaoResult.ok();
}
}
2.3.4 Controller
接收两个参数parentid、name。调用Service添加记录。返回TaotaoResult。应该返回json数据。
ContentCategoryController.java
【/taotao-manager-web】—【/src/main/java】—【/com/taotao/controller/】—【ContentCategoryController.java】
package com.taotao.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taotao.common.pojo.EUTreeNode;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.service.ContentCategoryService;
//内容分类管理
@Controller
@RequestMapping("/content/category")
public class ContentCategoryController {
@Autowired
private ContentCategoryService contentCategoryService;
@RequestMapping("/list")
@ResponseBody
public List<EUTreeNode> getContentCatList(@RequestParam(value = "id", defaultValue = "0") Long parentId) {
List<EUTreeNode> list = contentCategoryService.getCategoryList(parentId);
return list;
}
@RequestMapping("/create")
@ResponseBody
public TaotaoResult createContentCategory(Long parentId, String name) {
TaotaoResult result = contentCategoryService.insertContentCategory(parentId, name);
return result;
}
@RequestMapping("/delete")
@ResponseBody
public TaotaoResult deleteNode(Long id){
TaotaoResult result=contentCategoryService.deleteContentCategory(id);
return result;
}
}
2.5 内容分类重命名节点
2.3.1. 需求分析
content-category.jsp
【/taotao-manager-web】—【/src/main/webapp/WEB-INF/jsp/】—【content-category.jsp】
当编辑完成后会触发onAfterEdit事件
请求的url:/content/category/update
参数:id、name
返回值:返回TaotaoResult。Json格式
业务逻辑:根据id更新记录的name列即可。
2.3.2 Dao层
可以使用逆向工程生成的代码
2.3.3 Service层
ContentCategoryService.java
【/taotao-manager-service】—【/src/main/java】—【/com/taotao/service/】—【ContentCategoryService.java】
package com.taotao.service;
import java.util.List;
import com.taotao.common.pojo.EUTreeNode;
import com.taotao.common.utill.TaotaoResult;
//内容分类管理
public interface ContentCategoryService {
List<EUTreeNode> getCategoryList(long parentId);
TaotaoResult insertContentCategory(long parentId, String name);
TaotaoResult deleteContentCategory(Long id);
TaotaoResult updataContentCategory(Long id, String name);
}
ContentCategoryServiceImpl.java
【/taotao-manager-service】—【/src/main/java】—【/com/taotao/service/impl/】—【ContentCategoryServiceImpl.java】
package com.taotao.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.taotao.common.pojo.EUTreeNode;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.mapper.TbContentCategoryMapper;
import com.taotao.pojo.TbContentCategory;
import com.taotao.pojo.TbContentCategoryExample;
import com.taotao.pojo.TbContentCategoryExample.Criteria;
import com.taotao.service.ContentCategoryService;
//内容分类管理
@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {
@Autowired
private TbContentCategoryMapper contentCategoryMapper;
@Override
public List<EUTreeNode> getCategoryList(long parentId) {
// 根据parentid查询节点列表
TbContentCategoryExample example = new TbContentCategoryExample();
Criteria criteria = example.createCriteria();
criteria.andParentIdEqualTo(parentId);
// 执行查询
List<TbContentCategory> list = contentCategoryMapper.selectByExample(example);
List<EUTreeNode> resultList = new ArrayList<>();
for (TbContentCategory tbContentCategory : list) {
// 创建一个节点
EUTreeNode node = new EUTreeNode();
node.setId(tbContentCategory.getId());
node.setText(tbContentCategory.getName());
node.setState(tbContentCategory.getIsParent() ? "closed" : "open");
resultList.add(node);
}
return resultList;
}
@Override
public TaotaoResult insertContentCategory(long parentId, String name) {
// 创建一个pojo
TbContentCategory contentCategory = new TbContentCategory();
contentCategory.setName(name);
contentCategory.setIsParent(false);
// '状态。可选值:1(正常),2(删除)',
contentCategory.setStatus(1);
contentCategory.setParentId(parentId);
contentCategory.setSortOrder(1);
contentCategory.setCreated(new Date());
contentCategory.setUpdated(new Date());
// 添加记录
contentCategoryMapper.insert(contentCategory);
// 查看父节点的isParent列是否为true,如果不是true改成true
TbContentCategory parentCat = contentCategoryMapper.selectByPrimaryKey(parentId);
// 判断是否为true
if (!parentCat.getIsParent()) {
parentCat.setIsParent(true);
// 更新父节点
contentCategoryMapper.updateByPrimaryKey(parentCat);
}
// 返回结果
return TaotaoResult.ok(contentCategory);
}
@Override
public TaotaoResult deleteContentCategory(Long id) {
// TODO Auto-generated method stub
TbContentCategory contentCategory = contentCategoryMapper.selectByPrimaryKey(id);
if (contentCategory.getIsParent()) {
List<EUTreeNode> list = getCategoryList(id);
// 递归删除
for (EUTreeNode tbcontentCategory : list) {
deleteContentCategory(tbcontentCategory.getId());
}
}
if (getCategoryList(contentCategory.getParentId()).size() == 1) {
TbContentCategory parentCategory = contentCategoryMapper.selectByPrimaryKey(contentCategory.getParentId());
parentCategory.setIsParent(false);
contentCategoryMapper.updateByPrimaryKey(parentCategory);
}
contentCategoryMapper.deleteByPrimaryKey(id);
return TaotaoResult.ok();
}
@Override
public TaotaoResult updataContentCategory(Long id, String name) {
// 通过id查询节点对象
TbContentCategory contentCategory = contentCategoryMapper.selectByPrimaryKey(id);
// 判断节点重命名后的名称与原来的名称是否相同,若相同则不用更新
if (name != null && name.equals(contentCategory.getName())) {
return TaotaoResult.ok();
}
contentCategory.setName(name);
// 设置更新时间
contentCategory.setUpdated(new Date());
// 更新数据库表中的数据
contentCategoryMapper.updateByPrimaryKeySelective(contentCategory);
// 返回结果
return TaotaoResult.ok();
}
}
2.3.4 Controller
接收两个参数parentid、name。调用Service添加记录。返回TaotaoResult。应该返回json数据。
ContentCategoryController.java
【/taotao-manager-web】—【/src/main/java】—【/com/taotao/controller/】—【ContentCategoryController.java】
package com.taotao.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taotao.common.pojo.EUTreeNode;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.service.ContentCategoryService;
//内容分类管理
@Controller
@RequestMapping("/content/category")
public class ContentCategoryController {
@Autowired
private ContentCategoryService contentCategoryService;
@RequestMapping("/list")
@ResponseBody
public List<EUTreeNode> getContentCatList(@RequestParam(value = "id", defaultValue = "0") Long parentId) {
List<EUTreeNode> list = contentCategoryService.getCategoryList(parentId);
return list;
}
@RequestMapping("/create")
@ResponseBody
public TaotaoResult createContentCategory(Long parentId, String name) {
TaotaoResult result = contentCategoryService.insertContentCategory(parentId, name);
return result;
}
@RequestMapping("/delete")
@ResponseBody
public TaotaoResult deleteNode(Long id){
TaotaoResult result=contentCategoryService.deleteContentCategory(id);
return result;
}
@RequestMapping("/update")
@ResponseBody
public TaotaoResult updateNode(Long id,String name){
TaotaoResult result=contentCategoryService.updataContentCategory(id, name);
return result;
}
}
2.6 内容管理
内容管理表:
2.6.1. 内容列表
需求分析
请求url:/content/query/list
参数:page、rows、categoryId
content.jsp
【/taotao-manager-web】—【/src/main/webapp/WEB-INF/jsp/】—【content.jsp】
返回值:EUDataGridResult
Total、rows:内容pojo列表。
业务逻辑:
根据内容分类id查询内容列表。需要实现分页。返回EUDataGridResult
service层
ContentService.java
/taotao-manager-service/src/main/java/com/taotao/service/ContentService.java
package com.taotao.service;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.pojo.TbContent;
//内容管理
public interface ContentService {
// 内容列表显示
EUDataGridResult getContentList(long categoryId,int page,int rows);
}
ContentServiceImpl.java
【/taotao-manager-service】—【/src/main/java/】—【com/taotao/service/impl/】—【ContentServiceImpl.java】
package com.taotao.service.impl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.pojo.TbContentExample.Criteria;
import com.taotao.service.ContentService;
//内容管理
@Service
public class ContentServiceImpl implements ContentService {
@Autowired
private TbContentMapper contentMapper;
// 内容列表显示
@Override
public EUDataGridResult getContentList(long categoryId, int page, int rows) {
// 根据categoryId查询
TbContentExample example = new TbContentExample();
Criteria criteria = example.createCriteria();
criteria.andCategoryIdEqualTo(categoryId);
// 分页管理
PageHelper.startPage(page, rows);
List<TbContent> list = contentMapper.selectByExample(example);
EUDataGridResult result = new EUDataGridResult();
result.setRows(list);
PageInfo<TbContent> pageInfo = new PageInfo<>(list);
result.setTotal(pageInfo.getTotal());
return result;
}
}
controller层
ContentController.java
【/taotao-manager-web】—【/src/main/java/】—【com/taotao/controller/】-【ContentController.java】
package com.taotao.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.pojo.TbContent;
import com.taotao.service.ContentService;
//内容管理
@Controller
@RequestMapping("/content")
public class ContentController {
@Autowired
private ContentService contentService;
// 内容列表显示
@RequestMapping("/query/list")
@ResponseBody
public EUDataGridResult getContentList(long categoryId, int page, int rows) {
EUDataGridResult content=contentService.getContentList(categoryId,page,rows);
return content;
}
}
2.6.2. 内容添加
需求分析:
content.jsp
【/taotao-manager-web】—【/src/main/webapp/WEB-INF/jsp/】—【content.jsp】
common.js
【/taotao-manager-web】—【/src/main/webapp/WEB-INF/js/】—【common.js】
content-add.jsp
【/taotao-manager-web】—【/src/main/webapp/WEB-INF/jsp/】—【content-add.jsp】
图片上传初始化:common.js
【/taotao-manager-web】—【/src/main/webapp/WEB-INF/js/】—【common.js】
内容表单提交:content-add.jsp
【/taotao-manager-web】—【/src/main/webapp/WEB-INF/jsp/】—【content-add.jsp】
请求的url:/content/save
请求的方法:post
请求内容:表单中的内容。
返回的结果:TaotaoResult。
service层
接收表tb_content对应的pojo对象。把pojo对象插入到tb_content表中。
返回TaotaoResult。
ContentService.java
/taotao-manager-service/src/main/java/com/taotao/service/ContentService.java
package com.taotao.service;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.pojo.TbContent;
//内容管理
public interface ContentService {
// 内容列表显示
EUDataGridResult getContentList(long categoryId,int page,int rows);
// 內容添加
TaotaoResult insertContent(TbContent content);
}
ContentServiceImpl.java
【/taotao-manager-service】—【/src/main/java/】—【com/taotao/service/impl/】—【ContentServiceImpl.java】
package com.taotao.service.impl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.pojo.TbContentExample.Criteria;
import com.taotao.service.ContentService;
//内容管理
@Service
public class ContentServiceImpl implements ContentService {
@Autowired
private TbContentMapper contentMapper;
// 内容列表显示
@Override
public EUDataGridResult getContentList(long categoryId, int page, int rows) {
// 根据categoryId查询
TbContentExample example = new TbContentExample();
Criteria criteria = example.createCriteria();
criteria.andCategoryIdEqualTo(categoryId);
// 分页管理
PageHelper.startPage(page, rows);
List<TbContent> list = contentMapper.selectByExample(example);
EUDataGridResult result = new EUDataGridResult();
result.setRows(list);
PageInfo<TbContent> pageInfo = new PageInfo<>(list);
result.setTotal(pageInfo.getTotal());
return result;
}
// 內容添加
@Override
public TaotaoResult insertContent(TbContent content) {
// 补全pojo内容
content.setCreated(new Date());
content.setUpdated(new Date());
contentMapper.insert(content);
return TaotaoResult.ok();
}
}
HttpClientUtil.java
【/taotao-common】—【/src/main/java/】—【com/taotao/common/utill/】—【HttpClientUtil.java】
package com.taotao.common.utill;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
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;
}
}
controller层
ContentController.java
接收表单中的内容,使用pojo接收。要求pojo的属性要和表单中的name一致。调用Service插入内容信息。返回TaotaoResult。Json格式的数据。
【/taotao-manager-web】—【/src/main/java/】—【com/taotao/controller/】-【ContentController.java】
package com.taotao.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.pojo.TbContent;
import com.taotao.service.ContentService;
//内容管理
@Controller
@RequestMapping("/content")
public class ContentController {
@Autowired
private ContentService contentService;
// 内容列表显示
@RequestMapping("/query/list")
@ResponseBody
public EUDataGridResult getContentList(long categoryId, int page, int rows) {
EUDataGridResult content=contentService.getContentList(categoryId,page,rows);
return content;
}
// 內容添加
@RequestMapping("/save")
@ResponseBody
public TaotaoResult insertContent(TbContent content) {
TaotaoResult result = contentService.insertContent(content);
return result;
}
}
2.6.3. 修改内容
需求分析
content.jsp
【/taotao-manager-web】—【/src/main/webapp/WEB-INF/jsp/】—【content.jsp】
content-edit.jsp
【/taotao-manager-web】—【/src/main/webapp/WEB-INF/jsp/】—【content-edit.jsp】
service层
ContentService.java
/taotao-manager-service/src/main/java/com/taotao/service/ContentService.java
package com.taotao.service;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.pojo.TbContent;
//内容管理
public interface ContentService {
// 内容列表显示
EUDataGridResult getContentList(long categoryId,int page,int rows);
// 內容添加
TaotaoResult insertContent(TbContent content);
TaotaoResult updataContent(TbContent content);
}
ContentServiceImpl.java
【/taotao-manager-service】—【/src/main/java/】—【com/taotao/service/impl/】—【ContentServiceImpl.java】
package com.taotao.service.impl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.pojo.TbContentExample.Criteria;
import com.taotao.service.ContentService;
//内容管理
@Service
public class ContentServiceImpl implements ContentService {
@Autowired
private TbContentMapper contentMapper;
// 内容列表显示
@Override
public EUDataGridResult getContentList(long categoryId, int page, int rows) {
// 根据categoryId查询
TbContentExample example = new TbContentExample();
Criteria criteria = example.createCriteria();
criteria.andCategoryIdEqualTo(categoryId);
// 分页管理
PageHelper.startPage(page, rows);
List<TbContent> list = contentMapper.selectByExample(example);
EUDataGridResult result = new EUDataGridResult();
result.setRows(list);
PageInfo<TbContent> pageInfo = new PageInfo<>(list);
result.setTotal(pageInfo.getTotal());
return result;
}
// 內容添加
@Override
public TaotaoResult insertContent(TbContent content) {
// 补全pojo内容
content.setCreated(new Date());
content.setUpdated(new Date());
contentMapper.insert(content);
return TaotaoResult.ok();
}
@Override
public TaotaoResult updataContent(TbContent content) {
// 填充属性
content.setUpdated(new Date());
// 更新内容
contentMapper.updateByPrimaryKeyWithBLOBs(content);
// 返回结果
return TaotaoResult.ok();
}
}
controller层
【/taotao-manager-web】—【/src/main/java/】—【com/taotao/controller/】-【【ContentController.java】
package com.taotao.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.pojo.TbContent;
import com.taotao.service.ContentService;
//内容管理
@Controller
@RequestMapping("/content")
public class ContentController {
@Autowired
private ContentService contentService;
// 内容列表显示
@RequestMapping("/query/list")
@ResponseBody
public EUDataGridResult getContentList(long categoryId, int page, int rows) {
EUDataGridResult content=contentService.getContentList(categoryId,page,rows);
return content;
}
// 內容添加
@RequestMapping("/save")
@ResponseBody
public TaotaoResult insertContent(TbContent content) {
TaotaoResult result = contentService.insertContent(content);
return result;
}
@RequestMapping(value="/edit",method=RequestMethod.POST)
@ResponseBody
public TaotaoResult updateNode(TbContent content){
TaotaoResult result=contentService.updataContent(content);
return result;
}
}
2.6.4. 内容删除
需求分析
content.jsp
【/taotao-manager-web】—【/src/main/webapp/WEB-INF/jsp/】—【content.jsp】
service层
ContentService.java
/taotao-manager-service/src/main/java/com/taotao/service/ContentService.java
package com.taotao.service;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.pojo.TbContent;
//内容管理
public interface ContentService {
// 内容列表显示
EUDataGridResult getContentList(long categoryId,int page,int rows);
// 內容添加
TaotaoResult insertContent(TbContent content);
TaotaoResult deleteContent(String ids);
TaotaoResult updataContent(TbContent content);
}
ContentServiceImpl.java
【/taotao-manager-service】—【/src/main/java/】—【com/taotao/service/impl/】—【ContentServiceImpl.java】
package com.taotao.service.impl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.pojo.TbContentExample.Criteria;
import com.taotao.service.ContentService;
//内容管理
@Service
public class ContentServiceImpl implements ContentService {
@Autowired
private TbContentMapper contentMapper;
// 内容列表显示
@Override
public EUDataGridResult getContentList(long categoryId, int page, int rows) {
// 根据categoryId查询
TbContentExample example = new TbContentExample();
Criteria criteria = example.createCriteria();
criteria.andCategoryIdEqualTo(categoryId);
// 分页管理
PageHelper.startPage(page, rows);
List<TbContent> list = contentMapper.selectByExample(example);
EUDataGridResult result = new EUDataGridResult();
result.setRows(list);
PageInfo<TbContent> pageInfo = new PageInfo<>(list);
result.setTotal(pageInfo.getTotal());
return result;
}
// 內容添加
@Override
public TaotaoResult insertContent(TbContent content) {
// 补全pojo内容
content.setCreated(new Date());
content.setUpdated(new Date());
contentMapper.insert(content);
return TaotaoResult.ok();
}
@Override
public TaotaoResult updataContent(TbContent content) {
// 填充属性
content.setUpdated(new Date());
// 更新内容
contentMapper.updateByPrimaryKeyWithBLOBs(content);
// 返回结果
return TaotaoResult.ok();
}
@Override
public TaotaoResult deleteContent(String ids) {
String[] idList=ids.split(",");
for (String id : idList) {
contentMapper.deleteByPrimaryKey(Long.valueOf(id));
}
return TaotaoResult.ok();
}
}
controller层
【/taotao-manager-web】—【/src/main/java/】—【com/taotao/controller/】-【【ContentController.java】
package com.taotao.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taotao.common.pojo.EUDataGridResult;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.pojo.TbContent;
import com.taotao.service.ContentService;
//内容管理
@Controller
@RequestMapping("/content")
public class ContentController {
@Autowired
private ContentService contentService;
// 内容列表显示
@RequestMapping("/query/list")
@ResponseBody
public EUDataGridResult getContentList(long categoryId, int page, int rows) {
EUDataGridResult content=contentService.getContentList(categoryId,page,rows);
return content;
}
// 內容添加
@RequestMapping("/save")
@ResponseBody
public TaotaoResult insertContent(TbContent content) {
TaotaoResult result = contentService.insertContent(content);
return result;
}
@RequestMapping(value="/edit",method=RequestMethod.POST)
@ResponseBody
public TaotaoResult updateNode(TbContent content){
TaotaoResult result=contentService.updataContent(content);
return result;
}
@RequestMapping(value="/delete",method=RequestMethod.POST)
@ResponseBody
public TaotaoResult deleteContent(String ids){
TaotaoResult result=contentService.deleteContent(ids);
return result;
}
}
3. 展示商城首页大广告位
3.1. 页大广告方案
前端系统获取后端系统提供的接口,如何获取?
3.1.1. 方案1
jsonp跨域请求
需要当首页加载完毕后,大广告位就应该显示。没有触发事件。不是太合适。
优点:不需要二次请求,页面直接加载内容数据。减少门户系统的压力。
缺点:需要延迟加载。不利于seo优化。
3.1.1. 第二种方案:
优点:有利于seo优化。可以在taotao-portal中对数据进行加工。
缺点:系统直接需要调用服务查询内容信息。多了一次http请求。
系统直接服务的调用,需要使用httpclient来实现。Taotao-portal和taotao-rest是在同一个局域网内部。速度非常快,调用时间可以忽略不计。
展示首页内容功能,使用方案二实现。
3.2. 展示流程
3.3. 内容服务发布
3.3.1. 需求分析
根据内容的分类id查询内容列表,从tb_content表中查询。服务是一个restFul形式的服务。使用http协议传递json格式的数据。
3.3.2 Dao层
从tb_content表中查询,根据内容分类id查询。是单表查询。可以使用逆向工程生成的代码。
3.3.3. Service层
接收内容分类id,根据分类id查询分类列表。返回一个内容pojo列表。
参数:分类id
返回值:pojo列表
ContentService.java
【/taotao-rest】—【/src/main/java/】—【com/taotao/rest/service】—【/ContentService.java】
package com.taotao.rest.service;
import java.util.List;
import com.taotao.pojo.TbContent;
//内容服务发布
public interface ContentService {
List<TbContent> getContentList(long contentCid);
}
ContentServiceImpl.java
【/taotao-rest】—【/src/main/java/】—【com/taotao/rest/service】—【ContentServiceImpl.java】
package com.taotao.rest.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.pojo.TbContentExample.Criteria;
import com.taotao.rest.service.ContentService;
//内容服务发布
@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;
}
}
3.3.4. Controlle5r层
发布服务。接收查询参数。Restful风格内容分类id应该从url中取。
/rest/content/list/{contentCategoryId}
从url中取内容分类id,调用Service查询内容列表。返回内容列表。返回一个json格式的数据。可以使用TaotaoResult包装此列表。
导入ExceptionUtil.java工具类
ExceptionUtil.java
【/taotao-common】—【/src/main/java】—【/com/taotao/common/utill/】—【ExceptionUtil.java】
package com.taotao.common.utill;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ExceptionUtil {
/**
* 获取异常的堆栈信息
*
* @param t
* @return
*/
public static String getStackTrace(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
t.printStackTrace(pw);
return sw.toString();
} finally {
pw.close();
}
}
}
ContentController.java
【/taotao-rest】—【/src/main/java/】—【com/taotao/rest/controller/】—【ContentController.java】
package com.taotao.rest.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taotao.common.utill.ExceptionUtil;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.pojo.TbContent;
import com.taotao.rest.service.ContentService;
/**
* 内容服务发布
*/
@Controller
@RequestMapping("/content")
public class ContentController {
@Autowired
private ContentService contentService;
@RequestMapping("/list/{contentCategoryId}")
@ResponseBody
public TaotaoResult getContentList(@PathVariable Long contentCategoryId) {
try {
List<TbContent> list = contentService.getContentList(contentCategoryId);
return TaotaoResult.ok(list);
} catch (Exception e) {
e.printStackTrace();
return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
}
}
}
3.3.5测试
双击运行
http://127.0.0.1:8081/rest/content/list/89
3.3.6 Httpclient的使用
3.3.6.1. 什么是httpclient
HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
下载地址:
http://hc.apache.org/
3.3.6.2. 添加依赖
需要把httpclient的jar包添加到工程中。只需要在工程中添加httpclient的依赖。
【taotao-parent】—【pom.xml】
【/taotao-common】—【pom.xml】
3.3.6.3 使用方法
HttpClientTest.java
【/taotao-portal】—【/src/test/java】—【/com/taotao/httpclient/】—【HttpClientTest.java】
junit测试依赖添加到taotao-portal中
package com.taotao.httpclient;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class HttpClientTest {
// 1. 使用httpclient执行get请求
@Test
public void doGet() throws Exception {
// 创建一个httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建一个GET对象
HttpGet get = new HttpGet("http://www.sogou.com");
// 执行请求
CloseableHttpResponse response = httpClient.execute(get);
// 取响应的结果
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
HttpEntity entity = response.getEntity();
String string = EntityUtils.toString(entity, "utf-8");
System.out.println(string);
// 关闭httpclient
response.close();
httpClient.close();
}
// 2. 执行get请求带参数
@Test
public void doGetWithParam() throws Exception {
// 创建一个httpclient对象
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();
String string = EntityUtils.toString(entity, "utf-8");
System.out.println(string);
// 关闭httpclient
response.close();
httpClient.close();
}
// 3. 使用httpclient执行post请求
@Test
public void doPost() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建一个post对象
HttpPost post = new HttpPost("http://localhost:8082/httpclient/post.action");
// 执行post请求
CloseableHttpResponse response = httpClient.execute(post);
String string = EntityUtils.toString(response.getEntity());
System.out.println(string);
response.close();
httpClient.close();
}
// 4. 带参数post请求
@Test
public void doPostWithParam() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建一个post对象
HttpPost post = new HttpPost("http://localhost:8082/httpclient/post.action");
// 创建一个Entity。模拟一个表单
List<NameValuePair> kvList = new ArrayList<>();
kvList.add(new BasicNameValuePair("username", "张三"));
kvList.add(new BasicNameValuePair("password", "123"));
// 包装成一个Entity对象
StringEntity entity = new UrlEncodedFormEntity(kvList, "utf-8");
// 设置请求的内容
post.setEntity(entity);
// 执行post请求
CloseableHttpResponse response = httpClient.execute(post);
String string = EntityUtils.toString(response.getEntity());
System.out.println(string);
response.close();
httpClient.close();
}
}
使用httpclient执行get请求
执行get请求带参数
使用httpclient执行post请求
IndexController.java
【taotao-portal】项目中【/src/main/java】目录里的【/com/taotao/portal/controller】包下【IndexController.java】
/*
* /taotao-portal/src/test/java/com/taotao/httpclient/HttpClientTest.java 3.
* 3.使用httpclient执行post请求
*/
@RequestMapping(value = "httpclient/post", method = RequestMethod.POST)
@ResponseBody
public TaotaoResult testPost() {
return TaotaoResult.ok();
}
带参数post请求
IndexController.java
【taotao-portal】项目中【/src/main/java】目录里的【/com/taotao/portal/controller】包下【IndexController.java】
/*
* /taotao-portal/src/test/java/com/taotao/httpclient/HttpClientTest.java
* 4.带参数post请求
*/
@RequestMapping(value = "httpclient/post", method = RequestMethod.POST)
@ResponseBody
public String testPost(String username, String password) {
return "userneme:" + username + "\tpassword" + password;
}
Post乱码问题
IndexController.java
【taotao-portal】项目中【/src/main/java】目录里的【/com/taotao/portal/controller】包下【IndexController.java】
封装成工具类
其他项目也可能会用到httpclient,所以把工具类放到taotao-common中。
HttpClientUtil.java
【/taotao-common】—【/src/main/java/】—【com/taotao/common/utill/】—【HttpClientUtil.java】
4. 大广告位展示
4.1. 需求分析
需要创建一个json字符串传递给jsp:
index.jsp
【/taotao-portal】—【/src/main/webapp/WEB-INF/jsp/】—【index.jsp】
Json字符串如何传递给jsp:使用modelAndView对象把json字符串传递给jsp。
如何获得json字符串:获得一个广告位对应的内容列表,需要调用taotao-rest的服务。把列表转换成json数据格式要求的pojo对象列表。
需要使用httpclient调用taotao-rest的服务。
4.2. Dao层
没有
4.3. Service层
根据内容分类id查询分类的内容列表,需要使用httpclient调用taotao-rest的服务。得到一个json字符串。需要把字符串转换成java对象taotaoResult对象。从taotaoResult对象中取data属性,得到内容列表。把内容列表转换成jsp页面要求的json格式。返回一个json字符串。
参数:没有参数
返回值:json字符串。
ContentService.java
【/taotao-portal】—【/src/main/java/】—【com/taotao/portal/service/】—【ContentService.java】
package com.taotao.portal.service;
public interface ContentService {
String getContentList();
}
ContentServiceImpl.java
【/taotao-portal】—【/src/main/java/】—【com/taotao/portal/service/impl/】—【ContentServiceImpl.java】
package com.taotao.portal.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.taotao.common.utill.HttpClientUtil;
import com.taotao.common.utill.JsonUtils;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.pojo.TbContent;
import com.taotao.portal.service.ContentService;
/**
* 调用服务层服务,查询内容列表
*/
@Service
public class ContentServiceImpl implements ContentService {
@Value("${REST_BASE_URL}")
private String REST_BASE_URL;
@Value("${REST_INDEX_AD_URL}")
private String REST_INDEX_AD_URL;
@Override
public String getContentList() {
//调用服务层的服务
String result = HttpClientUtil.doGet(REST_BASE_URL + REST_INDEX_AD_URL);
//把字符串转换成TaotaoResult
try {
TaotaoResult taotaoResult = TaotaoResult.formatToList(result, TbContent.class);
//取内容列表
List<TbContent> list = (List<TbContent>) taotaoResult.getData();
List<Map> resultList = new ArrayList<>();
//创建一个jsp页码要求的pojo列表
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());
resultList.add(map);
}
return JsonUtils.objectToJson(resultList);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
resource.properties
【/taotao-portal】—【/src/main/resources/】—【resource/】—【resource.properties】
#服务层属性定义
#基础url
REST_BASE_URL=http://127.0.0.1:8081/rest
#首页大广告位url
REST_INDEX_AD_URL=/content/list/89
pom.xml
【/taotao-portal/】—【pom.xml】
4.4. Controller
展示首页返回一个逻辑视图,需要把首页大广告位的json数据传递给jsp。
IndexController.java
【taotao-portal】项目中【/src/main/java】目录里的【/com/taotao/portal/controller】包下【IndexController.java】
package com.taotao.portal.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taotao.common.utill.TaotaoResult;
import com.taotao.portal.service.ContentService;
@Controller
public class IndexController {
/**
* 显示主页
*/
// @RequestMapping("/index")
// public String showIndex(Model model) {
// return "index";
// }
/*
* 首页大广告位
*/
@Autowired
private ContentService contentService;
@RequestMapping("/index")
public String showIndex(Model model) {
String adJson = contentService.getContentList();
model.addAttribute("ad1", adJson);
return "index";
}
/*
* /taotao-portal/src/test/java/com/taotao/httpclient/HttpClientTest.java 3.
* 3.使用httpclient执行post请求
*/
// @RequestMapping(value = "httpclient/post", method = RequestMethod.POST)
// @ResponseBody
// public TaotaoResult testPost() {
// return TaotaoResult.ok();
// }
/*
* /taotao-portal/src/test/java/com/taotao/httpclient/HttpClientTest.java
* 4.带参数post请求
*/
// @RequestMapping(value = "httpclient/post", method = RequestMethod.POST)
// @ResponseBody
// public String testPost(String username, String password) {
// return "userneme:" + username + "\tpassword" + password;
// }
}