分类展示功能在逻辑上并不复杂:每当需要加载
查询商品分类内的功能需要面向数据库中的另一张表 tb_goods_type,为了区分不同类型的数据查询业务以及代码的维护性和扩展性。在开发时基于三层架构体系建立对应的GoodsTypeServlet 类、GoodsTypeService 接口和实现类、GoodsTypeDao 接口和实现类。
3.代码实现 3.1 后端 3.1.1 Servlet在 GoodsTypeServlet类中定义查询所有线路分类内容的主体逻辑
@WebServlet("/goodsType.do")
public class GoodsTypeServlet extends BaseServlet {
private ResultData resultData = new ResultData();
public String goodsTypeAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
IGoodsTypeService service = new GoodsTypeServiceImpl();
resultData.setFlag(false);
List lists = service.getGoodTypeByParent();
if (lists != null && lists.size() >= 1) {
resultData.setFlag(true);
resultData.setData(lists);
}
String json = JSON.toJSONString(resultData);
System.out.println(json);
//在响应中声明返回的是json格式字符
resp.setContentType("application/json;charset=utf-8");
return json;
}
public String getGoodsListByTypeId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String typeid = req.getParameter("typeid");
IGoodsService service = new GoodsServiceImpl();
resultData.setFlag(false);
List goods = service.getGoodsById(typeid);
if (goods != null && goods.size() >= 1) {
resultData.setFlag(true);
resultData.setData(goods);
}
String json = JSON.toJSONString(resultData);
System.out.println(json);
//在响应中声明返回的是json格式字符
resp.setContentType("application/json;charset=utf-8");
return json;
}
}
3.1.2 Service
在 GoodsTypeService 类中定义 GoodsTypeDaoImpl() 方法,定义旅游线路分类内容的具体查询业务逻辑
public class GoodsTypeServiceImpl implements IGoodsTypeService {
private IGoodsTypeDao goodsTypeDao=new GoodsTypeDaoImpl();
//.....
@Override
public List getGoodTypeByParent() {
List goodsTypes=new ArrayList<>();
List goodsTypes1=goodsTypeDao.getAllDatas();
if (goodsTypes1!=null){
for (GoodsType gt:goodsTypes1){
if (gt.getParent()==0){//从总的分类数据中做筛选
goodsTypes.add(gt);
}
}
return goodsTypes;
}
return null;
}
}
3.1.3 Dao
在 GoodsTypeDao 类中定义 getAllDatas() 方法,操作数据库查询 tb_goods_type 表中的所有内容
public class GoodsTypeDaoImpl implements IGoodsTypeDao {
private QueryRunner queryRunner = null;
public GoodsTypeDaoImpl() {
queryRunner = new QueryRunner();
}
//.....
@Override
public List getAllDatas() {
String sql = "select * from tb_goods_type ";
return queryBySql(sql, null);
}
@Override
public List queryBySql(String sql, Object... parms) {
List goodsTypes = null;
QueryRunner qrun = new QueryRunner(DBUtils.getDataSource());
try {
goodsTypes = qrun.query(sql, parms, new BeanListHandler<>(GoodsType.class));
} catch (SQLException e) {
e.printStackTrace();
}
return goodsTypes;
}
}
3.2 前端
后端程序执行顺利的话,返回的响应结果可以使用 FireFox 浏览器的自动 json 解析功能观察到以下效果。
前端在加载



