首先看一下项目结构.
配置文件Web.xml, spring-dao.xml, springmvc-servlet.xml, configuration.properties 等就是常规没有特殊的,具体内容可以看我上一篇博客.
首先看一下Mysql的表
省市区三张表,市通过p_id与省相连,区通过c_id与市相连.
通过Mybatis代码自动生成工具自动生成dao层和entity层.也就是
我们要做的是 在Province(后简称P)类中建立一个List字段,用来储存对应的City对象,然后再City(后简称C)类中建立一个List字段用来储存对应的Area(后简称A)对象.
P类,C类,A类属于接口,所以只需要定义方法即可. 具体如何实现,我们要在对应的Mapper.xml文件中写出来.
这样,只要通过数据库查出所有的P,也就同时能够查出City和Area.
在PMapper.java中建立 搜索所有P 的方法, 在CMapper.java中建立 根据pid搜索 的方法, 在AMapper.java中建立 根据cid搜索 的方法.如下图:
在P.xml中 添加这样的方法
select from provincedb
在C.xml文件中添加方法:
select from citydb where province_id = #{privince_id,jdbcType=INTEGER}
在A.xml文件中添加方法:
select from areadb where city_id = #{city_id,jdbcType=INTEGER}
这样,只要我们一搜索省份所有的信息,就能得到所对应的市区数据.
下面我们建立测试方法在controller层和service层的内容,以及前端
Controller层:
package com.test.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.test.entity.Province; import com.test.service.IndexServcie; @Controller @RequestMapping("/con") public class IndexController { @Autowired private IndexServcie service; @RequestMapping("/get") public String getPCA(HttpServletRequest req) { List list = service.getPCAs(); req.getSession().setAttribute("list", list); return "wel"; } }
service层:
package com.test.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.test.dao.ProvinceMapper; import com.test.entity.Province; @Service public class IndexServcie { @Autowired private ProvinceMapper dao; public List getPCAs() { return dao.selectProvinceAll(); } }
哦,对了.我这里是以一个空白页的jsp为起点,跳入到后台,后台获取数据后,在跳入另一个jsp页面中.
起始页index.jsp
Insert title here获取数据后的跳转的页面 wel.jsp
Insert title here-
${temp.provinceName }
-
${temp2.cityName }
${temp3.areaName }
效果如下:
测试结果还可以,至少是数据取回来了.接下来我们就根据具体的要求来处理数据.
这个方法不仅仅可以做 省市区三级联动 也可以做电商平台的商品类别之类的.
类似于这样的