JSP页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="/js/vue.js"></script>
<script type="text/javascript" src="/js/axios.min.js"></script>
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script type="text/javascript" src="/js/base.js"></script>
<link rel="stylesheet" href="/js/base.css">
<title>学生列表</title>
</head>
<body>
<div id="app">
姓名:<input v-model="query.name"><br>
年龄:<input v-model="query.age1">至<input v-model="query.age2"><br>
<!-- VUE绑定事件方法使用v-on或@ -->
<button @click="doquery">查询</button>
<button @click="doadd">添加</button>
<button @click="dodelete">删除</button>
<table>
<tr>
<th>选择</th>
<th>学生姓名</th>
<th>学生年龄</th>
<th>省份</th>
<th>地区</th>
<th>县市</th>
<th>日期</th>
<th>时间</th>
<th>操作</th>
</tr>
<tr v-for="s in studlist" @click="openbyid(s.id)">
<td><input type="checkbox" v-model="chkid" :value="s.id"></td>
<!-- VUE指令里面内容不可以使用{{}}
'javascript:openstuden('+s.id+')' 作为表达式计算
openstuden是Javascript方法,不是VUE定义的方法
在Javasript方法中调用VUE里定义的方法,必须VUE实例的名称,比如 vue.{prop|method}
在VUE定义的方法调用Javasript方法,直接调用方法名
-->
<td><a v-bind:href="'javascript:vue.openbyid('+s.id+')'">{{s.name}}</a></td>
<td>{{s.age}}</td>
<td>{{s.provinceName}}</td>
<td>{{s.cityName}}</td>
<td>{{s.countyName}}</td>
<td>{{s.dt}}</td>
<td>{{s.ts}}</td>
<td><a v-bind:href="'javascript:vue.dodeletesingle('+s.id+')'">删除</a></td>
</tr>
</table>
<!-- HTML内容绑定到DOM组件,使用VUE指令v-html -->
<div v-html='pagehtml'></div>
<!-- 添加学生DIV,根据VUE变量isshow是否为真决定是否显示
表单中输入域与VUE中student对象双向绑定,DOM组件回显由VUE决定`
-->
<div id="studiv" v-if="isshow">
<h3>添加学生</h3>
<!-- v-model实现双向绑定VUE指令 -->
姓名:<input v-model="student.name"><br>
年龄:<input v-model="student.age"><br>
<!-- 下列框选中使用v-model="student.province"
@change 定义选择事件触发的方法,等同v-on:change
-->
省份:<select v-model="student.province" @change="selectprovince">
<!-- 使用v-for展示下拉框全部内容 -->
<option v-for="p in provincelist" :value="p.code">{{p.name}}</option>
</select>
<br>
地区:<select v-model="student.city" @change="selectcity">
<option v-for="c in citylist" :value="c.code">{{c.name}}</option>
</select>
<br>
县市:<select v-model="student.county">
<option v-for="c in countylist" :value="c.code">{{c.name}}</option>
</select><br>
日期:<input v-model="student.dt"><br>
时间:<input v-model="student.ts"><br>
<br>
<button @click="dosave">添加</button>
<button @click="doclose">关闭</button>
</div>
</div>
<script>
var vue = new Vue({
el:'#app',
data:{
studlist:[],//学生列表对象-集合
provincelist:[],//所有省份集合
citylist:[],//选中省份之后对应地区集合
countylist:[],//选中地区之后对应县市集合
page:1,//默认显示当前页
rows:4,//每页显示记录数
total:0,//记录总行数
pagehtml:'',//分页HTML片段
chkid:[],//选择删除ID集合
student:{//添加或修改时用到的学生对象
id:'',//学生ID
name:'',//学生姓名
age:'',//学生年龄
province:'',//省份代码
city:'',//地区代码
county:'',//县市代码
dt:'',//日期
ts:''//时间
},
query:{//查询时封装查询对象
name:'',//查询姓名
age1:'',//查询年龄左区间
age2:''//查询年龄右区间
},
isshow:false
},
//VUE生命周期函数,beforeMount,mounted,beforeCreate,created,beforeUpate,updated,beforeDestory,destory
mounted:function(){
console.log("mounted...");
//this代表VUE实例,vue
this.doinitlist();
},
methods:{//VUE实例自定义方法,Key名字必须methods
//通过学生ID,获取学生对象
openbyid:function(id)
{
var _this = this;
axios.get('/findstudbyid?id='+id)
.then(function(result){
_this.student=result.data;
//显示学生修改/添加DIV
_this.isshow=true;
//调用VUE方法,初始化三级联动地址
_this.doloadaddress(_this.student.province,_this.student.city,
_this.student.county);
})
},
doinitlist:function()
{
var _this = this;
axios.get('/findstud?page='+_this.page+'&rows='+_this.rows)
.then(function(result){
_this.total = result.data.total;
_this.studlist = result.data.list;
//调用分页方法,返回分页HTML代码
_this.pagehtml = pagedivjs('vue.dopageload',_this.page,_this.rows,_this.total);
})
},
//用于分页显示的方法
dopageload:function(page,rows)
{
console.log('dopageload...');
var _this = this;
axios.get('/findstud?page='+page+'&rows='+rows)
.then(function(result){
_this.total = result.data.total;
_this.studlist = result.data.list;
//调用分页方法,返回分页HTML代码
console.log('page='+page);
_this.pagehtml = pagedivjs('vue.dopageload',page,rows,_this.total);
})
},
doadd:function()
{
this.student.name='';
console.log('doadd...');
//显示添加学生DIV
this.isshow = true;
//初始化地址,三个参数可以忽略
this.doloadaddress();
},
dodelete:function()
{
alert(this.chkid);
var _this = this;
axios.post('/deletestud?ids='+_this.chkid)
.then(function(result){
if(result.data)
{
alert("Delete Successfully");
//重新装载列表
_this.doinitlist();
}
})
},
dodeletesingle:function(id)
{
var _this = this;
axios.post('/deletestud?ids='+id)
.then(function(result){
if(result.data)
{
alert("Delete Successfully");
//重新装载列表
_this.doinitlist();
}
})
},
doquery:function(id)
{
var _this = this;
axios.post('/findstud',_this.query)
.then(function(result){
//this代表axios对象实例
//返回记录总数
_this.total = result.data.total;
//返回学生集合
_this.studlist = result.data.list;
//调用分页方法,返回分页HTML代码
_this.pagehtml = pagedivjs('vue.dopageload',_this.page,_this.rows,_this.total);
})
},
dosave:function()
{
console.log('dosave...');
var _this = this;
//将VUE对象student提交到后台
axios.post('/savestudent',_this.student)
.then(function(result){
if(result.data)
{
alert('Successfully');
//重新装载列表
_this.doinitlist();
//根据v-if关闭添加学生DIV层
_this.isshow = false;
}
else
alert('Failure');
})
},
doclose:function()
{
console.log('doclose...');
//根据v-if关闭添加学生DIV层
this.isshow = false;
},
selectprovince:function()//省份下列框选择事件
{
//选择地区,只输入省份Code
this.doloadaddress(this.student.province);
},
selectcity:function()//地区下列框选择事件
{
//选择县市,输入省份Code,地区Code
this.doloadaddress(this.student.province,this.student.city);
},
//初始化三级联动地址下列框
//province 省份代码 可空
//city 地区代码 可空
//county 县市代码 可空
doloadaddress:function(province,city,county)
{
console.log('doloadaddress...');
//定义_this记录VUE实例,应用axios中this代表
var _this = this;
//加载省份列表
axios.get('/getprovice')
.then(function(result){
_this.provincelist = result.data;
if(province != '' && province != null)
{
console.log('province...'+province);
_this.student.province = province;
}
else
{
//如果没有省份初始值,选择第一省份作为初始值
_this.student.province = result.data[0].code;
}
//根据省份Code,加载地区列表,发起请求,在下面语句中捕捉返回数据
return axios.get('/getcity?code='+_this.student.province);
})
.then(function(cityResult){
//捕捉地区列表数据
_this.citylist = cityResult.data;
if(city != '' && city != null)
{
console.log('city...'+city);
_this.student.city = city;
}
else
{
//如果没有地区初始值,选择第一地区作为初始值
_this.student.city = cityResult.data[0].code;
}
//根据地区Code,加载县市列表,发起请求,在下面语句中捕捉返回数据
return axios.get('/getcounty?code='+_this.student.city);
})
.then(function(countyResult){
//捕捉县市列表数据
_this.countylist = countyResult.data;
console.log('county...'+countyResult.data);
if(county != '' && county != null)
{
console.log('county...'+county);
_this.student.county = county;
}
else
{
//如果没有县市初始值,选择第一县市作为初始值
_this.student.county = countyResult.data[0].code;
}
})
}
}
})
</script>
</body>
</html>
Controller类
package com.test.ctrl;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.test.model.AddressInfo;
import com.test.model.StudentInfo;
import com.test.service.IAddressService;
@Controller
public class StudCtrl {
@Autowired
private IAddressService addsrv;
@RequestMapping("/studlist")
public String studlist()
{
return "studlist";
}
@RequestMapping("/getprovice")
@ResponseBody
public List<AddressInfo> getprovice()
{
// List<Map> list = new ArrayList<Map>();
// Map m1 = new HashMap();
// m1.put("code","001");
// m1.put("name", "北京");
// list.add(m1);
// Map m2 = new HashMap();
// m2.put("code","002");
// m2.put("name", "上海");
// list.add(m2);
// return list;
return addsrv.getProvince();
}
@RequestMapping("/getcity")
@ResponseBody
public List<AddressInfo> getcity(String code)
{
return addsrv.getCity(code);
}
@RequestMapping("/getcounty")
@ResponseBody
public List<AddressInfo> getcounty(String code)
{
return addsrv.getCounty(code);
}
@RequestMapping("/savestudent")
@ResponseBody
public Boolean savestudent(@RequestBody StudentInfo si) throws Exception
{
// InputStream is = req.getInputStream();
// byte[] content = FileCopyUtils.copyToByteArray(is);
// System.out.println(new String(content));
// JSONObject jsonObj = JSONObject.parseObject(new String(content));
// StudentInfo si = (StudentInfo)JSONObject.toJavaObject(jsonObj,StudentInfo.class);
System.out.println(si);
if(si.getId() != null)
addsrv.updateStudent(si);
else {
addsrv.saveStudent(si);
}
return true;
}
@RequestMapping("/findstudbyid")
@ResponseBody
public StudentInfo findstudbyid(Integer id) throws Exception
{
return addsrv.findStudentById(id);
}
@RequestMapping("/findstud")
@ResponseBody
public PageInfo findstud(Integer page,Integer rows,HttpServletRequest req) throws Exception
{
InputStream is = req.getInputStream();
byte[] content = FileCopyUtils.copyToByteArray(is);
System.out.println(new String(content));
JSONObject jsonObj = JSONObject.parseObject(new String(content));
Map map = (Map)JSONObject.toJavaObject(jsonObj,Map.class);
String name = null;
String age1 = null;
String age2 = null;
if(map != null)
{
name = (String)map.get("name");
age1 = (String)map.get("age1");
age2 = (String)map.get("age2");
}
return addsrv.findStudent(page, rows, name,age1,age2);
}
@RequestMapping("/deletestud")
@ResponseBody
public Boolean deletestud(String ids)
{
if(ids != null)
{
String[] dim = ids.split(",");
for(String s:dim)
{
addsrv.deleteStudent(new Integer(s));
}
}
return true;
}
}
数据库设计
create table t_student(
id int auto_increment primary key,
age int,
name varchar(50),
province varchar(10),
city varchar(10),
county varchar(10)
)
alter table t_student add dt date;
alter table t_student add ts datetime;
CREATE TABLE `t_address` (
`code` varchar(255) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `t_address` VALUES ('130000','河北省'),
('130100','石家庄市'),('130102','长安区'),
('130104','桥东区'),('130105','新华区'),
('320000','江苏省'),('320100','南京市'),
('320102','玄武区'),('320103','白下区'),
('320104','秦淮区'),('320200','苏州市'),('320201','中心区');
select s.*,p.name provinceName,c.name cityName,ct.name countyName from t_student s left join t_address p on s.province=p.code
left join t_address c on s.city=c.code
left join t_address ct on s.county=ct.code
insert into t_student(name,age,province,city,county) values('Java',20,'130000','130100','130102');
insert into t_student(name,age,province,city,county) values('C++',20,'130000','130100','130102');
insert into t_student(name,age,province,city,county) values('Android',20,'130000','130100','130102');
insert into t_student(name,age,province,city,county) values('Python',20,'130000','130100','130102');
Mapper接口
package com.test.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.test.model.AddressInfo;
import com.test.model.StudentInfo;
@Mapper
public interface AddressMapper {
public List<AddressInfo> getProvince();
public List<AddressInfo> getCity(@Param("code") String code);
public List<AddressInfo> getCounty(@Param("code") String code);
public void saveStudent(StudentInfo si);
public void updateStudent(StudentInfo si);
public List<StudentInfo> findStudent(@Param("name") String name,
@Param("age1") String age1,
@Param("age2") String age2);
public StudentInfo findStudentById(@Param("id") Integer id);
public void deleteStudent(@Param("id") Integer id);
}
接口定义
package com.test.service;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.github.pagehelper.PageInfo;
import com.test.model.AddressInfo;
import com.test.model.StudentInfo;
public interface IAddressService {
public List<AddressInfo> getProvince();
public List<AddressInfo> getCity(String code);
public List<AddressInfo> getCounty(String code);
public void updateStudent(StudentInfo si);
public void saveStudent(StudentInfo stud);
public PageInfo<StudentInfo> findStudent(Integer page,Integer rows,String name,String age1,String age2);
public StudentInfo findStudentById(Integer id);
public void deleteStudent(Integer id);
}
实现类
package com.test.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.test.mapper.AddressMapper;
import com.test.model.AddressInfo;
import com.test.model.StudentInfo;
import com.test.service.IAddressService;
@Service
public class AddressServiceImpl implements IAddressService{
@Autowired
private AddressMapper mapper;
@Override
public List<AddressInfo> getProvince() {
// TODO Auto-generated method stub
return mapper.getProvince();
}
@Override
public List<AddressInfo> getCity(String code) {
if(code != null)
{
String code2 = code.substring(0,2);
List<AddressInfo> citys = mapper.getCity(code2);
List<AddressInfo> resultCitys = new ArrayList<AddressInfo>();
for(AddressInfo city:citys)
{
if(!code.equals(city.getCode()))
resultCitys.add(city);
}
return resultCitys;
}
return null;
}
@Override
public List<AddressInfo> getCounty(String code) {
if(code != null)
{
String code2 = code.substring(0,4);
List<AddressInfo> countys = mapper.getCounty(code2);
List<AddressInfo> resultCountys = new ArrayList<AddressInfo>();
for(AddressInfo county:countys)
{
if(!code.equals(county.getCode()))
resultCountys.add(county);
}
return resultCountys;
}
return null;
}
@Override
public void saveStudent(StudentInfo stud) {
mapper.saveStudent(stud);
}
@Override
public PageInfo<StudentInfo> findStudent(Integer page,Integer rows,String name,
String age1,String age2) {
if(page == null)
page = 1;
if(rows == null)
rows = 4;
PageHelper.startPage(page, rows);
List<StudentInfo> result = mapper.findStudent(name,age1,age2);
PageInfo<StudentInfo> pInfo = new PageInfo<StudentInfo>(result);
return pInfo;
}
@Override
public StudentInfo findStudentById(Integer id) {
// TODO Auto-generated method stub
return mapper.findStudentById(id);
}
@Override
public void updateStudent(StudentInfo si) {
mapper.updateStudent(si);
}
@Override
public void deleteStudent(Integer id) {
mapper.deleteStudent(id);
}
}
Mapper XML
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.mapper.AddressMapper">
<select id="getProvince" resultType="com.test.model.AddressInfo">
select * from t_address where code like '%0000'
</select>
<select id="getCity" resultType="com.test.model.AddressInfo">
select * from t_address where code like '${code}%00'
</select>
<select id="getCounty" resultType="com.test.model.AddressInfo">
select * from t_address where code like '${code}%'
</select>
<insert id="saveStudent" parameterType="com.test.model.StudentInfo">
insert into t_student(name,age,province,city,county,dt,ts)
values(#{name},#{age},#{province},#{city},#{county},#{dt},#{ts})
</insert>
<delete id="deleteStudent">
delete from t_student where id=#{id}
</delete>
<update id="updateStudent" parameterType="com.test.model.StudentInfo">
update t_student set name=#{name},age=#{age},province=#{province},
city=#{city},county=#{county},dt=#{dt},ts=#{ts}
where id=#{id}
</update>
<select id="findStudent" resultType="com.test.model.StudentInfo">
select s.*,p.name provinceName,c.name cityName,ct.name countyName from t_student s left join t_address p on s.province=p.code
left join t_address c on s.city=c.code
left join t_address ct on s.county=ct.code
<where>
<if test="name != null and name!=''">
and s.name like '%${name}%'
</if>
<if test="age1 != null and age1!=''">
and s.age <![CDATA[>=]]> ${age1}
</if>
<if test="age2 != null and age2!=''">
and s.age <![CDATA[<=]]> ${age2}
</if>
</where>
</select>
<select id="findStudentById" resultType="com.test.model.StudentInfo">
select s.* from t_student s where s.id=#{id}
</select>
</mapper>
源代码
https://pan.baidu.com/s/10kT8fwbBzXM9criliwtyjQ
提取码 qv7a