分类实现展示功能
效果
后台代码
CategoryDao
public interface CategoryDao { 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 { //1.调用service查询所有 List<Category> cs = service.findAll(); //2.序列化json返回 /* ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json;charset=utf-8"); mapper.writeValue(response.getOutputStream(),cs); */ writeValue(cs,response); } }
BaseServlet也可以在UserServlet编写
//直接将传入的对象序列化为json,并且写回客户端 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,返回 public String writeValueAsString(Object obj) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(obj); }标签:mapper,findAll,展示,public,939,936,new,response,ObjectMapper From: https://www.cnblogs.com/agzq/p/17167672.html