@RequestParam(value = "city_code", required = false) String city_code,对于RequestParam注解,其实非常好用,这里就不多做解释,只是推广一下,固定个数的参数,用该注解更易于代码的维护。
ProvincialService类、CityService类就是两个单例,尽量把数据放置在内存当中,减少查询数据库的次数,稍候贴出来一个例子。
Option类就是单纯的封装前端option组件的关键属性,便于组件的通用化。
renderJson(response, JsonUtil.toJson(options));将数据json化后返回,稍候贴上详细代码。
④、ProvincialService.java
只贴出来代码例子,不做详细解释,毕竟不是本章重点。
package com.honzh.spring.service; import java.util.ArrayList; import java.util.List; import com.honzh.biz.database.entity.City; import com.honzh.biz.database.entity.Provincial; import com.honzh.biz.database.mapper.ProvincialMapper; import com.honzh.common.spring.SpringContextHolder; public class ProvincialService { private static Object lock = new Object(); private static ProvincialService config = null; private ProvincialService() { provincials = new ArrayList<Provincial>(); ProvincialMapper mapper = SpringContextHolder.getBean(ProvincialMapper.class); provincials.addAll(mapper.getProvincials()); } public static ProvincialService getInstance() { synchronized (lock) { if (null == config) { config = new ProvincialService(); } } return (config); } public Provincial getByProvincialcode(String provincial_code) { for (Provincial provincial : provincials) { if (provincial.getProcode().equals(provincial_code)) { return provincial; } } return null; } private List<Provincial> provincials = null; public List<Provincial> getProvincials() { return provincials; } public Provincial getProvincialByCitycode(String city_code) { City city = CityService.getInstance().getCityByCode(city_code); for (Provincial provincial : provincials) { if (provincial.getId().intValue() == city.getProid().intValue()) { return provincial; } } return null; } public Provincial getProvincialByCode(String province_code) { for (Provincial provincial : provincials) { if (provincial.getProcode().equals(province_code)) { return provincial; } } return null; } }
⑤、renderJson方法
/** * 如果出错的话,response直接返回404 */ protected void renderJson(HttpServletResponse response, Object responseObject) { PrintWriter out = null; try { if (responseObject == null) { response.sendError(404); return; } // 将实体对象转换为JSON Object转换 String responseStr = JsonUtil.toJson(responseObject); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); out = response.getWriter(); out.append(responseStr); logger.debug("返回是:" + responseStr); } catch (IOException e) { logger.error(e.getMessage()); logger.error(e.getMessage(), e); } finally { if (out != null) { out.close(); } } }
如果大家还想深入学习,可以点击jQuery级联菜单特效汇总、Javascript级联菜单特效汇总进行学习。
如果大家还想深入学习Bootstrap,可以点击这里进行学习,再为大家附两个精彩的专题:Bootstrap学习教程 Bootstrap实战教程