分类数据展示功能
分析:
代码实现:后台代码
CategoryDao:
public interface CategoryDao { /** * 查询所有 * @return */ public List<Category> findAll(); }
CategoryDaoImpl:
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)); } }
CategoryService:
public interface CategoryService { public List<Category> findAll(); }
CategoryServiceImpl:
public class CategoryServiceImpl implements CategoryService { private CategoryDao categoryDao = new CategoryDaoImpl(); @Override public List<Category> findAll() { return categoryDao.findAll(); } }
CategoryServlet:
@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); } }
在父类中添加两个方法:(方便一些操作)
BaseServlet:
/** * 直接将传入的对象序列化为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); }
代码实现:前台代码
header.html:
//查询分类数据 $.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); }); });标签:obj,findAll,return,案例,旅游网,new,response,public,黑马 From: https://www.cnblogs.com/wsfj/p/17153869.html