分类数据展示功能
分析:
代码实现:后台代码:
CategoryDao:
![复制代码](https://common.cnblogs.com/images/copycode.gif)
public interface CategoryDao { /** * 查询所有 * @return */ public List<Category> findAll(); }
![复制代码](https://common.cnblogs.com/images/copycode.gif)
CategoryDaoImpl:
![复制代码](https://common.cnblogs.com/images/copycode.gif)
public class CategoryDaoImpl implements CategoryDao { private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); @Override public List<Category> findAll() { String sql = "select * from tab_category"; return template.query(sql,new BeanPropertyRowMapper<Category>(Category.class)); } }
![复制代码](https://common.cnblogs.com/images/copycode.gif)
CategoryService:
public interface CategoryService { public List<Category> findAll(); }
CategoryServiceImpl:
![复制代码](https://common.cnblogs.com/images/copycode.gif)
public class CategoryServiceImpl implements CategoryService { private CategoryDao categoryDao = new CategoryDaoImpl(); @Override public List<Category> findAll() { return categoryDao.findAll(); } }
![复制代码](https://common.cnblogs.com/images/copycode.gif)
CategoryServlet:
![复制代码](https://common.cnblogs.com/images/copycode.gif)
@WebServlet("/category/*") public class CategoryServlet extends BaseServlet { private CategoryService service = new CategoryServiceImpl(); public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //调用service查询所有 List<Category> cs = service.findAll(); writeValue(cs,response); } }
![复制代码](https://common.cnblogs.com/images/copycode.gif)
在父类中添加两个方法:(方便一些操作)
BaseServlet:
![复制代码](https://common.cnblogs.com/images/copycode.gif)
/** * 直接将传入的对象序列化为json,并且写回客户端 * @param obj */ public void writeValue(Object obj,HttpServletResponse response) throws IOException { ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json;charset=utf-8"); mapper.writeValue(response.getOutputStream(),obj); } /** * 将传入的对象序列化为json,返回给调用者 * @param obj * @return */ public String writeValueAsString(Object obj) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(obj); }
![复制代码](https://common.cnblogs.com/images/copycode.gif)
代码实现:前台代码:
header.html:
![复制代码](https://common.cnblogs.com/images/copycode.gif)
//查询分类数据 $.get("category/findAll",{},function (data) { var lis = '<li class="nav-active"><a href="index.html">首页</a></li>'; //遍历数组 for (var i = 0; i <data.length; i++) { var li = '<li><a href="route_list.html">'+data[i].cname+'</a></li>'; lis+=li; } //拼接收藏排行榜的li lis+='<li><a href="favoriterank.html">收藏排行榜</a></li>'; //将lis字符串设置到ul的html中 $("#category").html(lis); }); });
![复制代码](https://common.cnblogs.com/images/copycode.gif)
标签:obj,findAll,return,案例,旅游网,new,response,public,黑马 From: https://www.cnblogs.com/yuzong/p/17123814.html