hospital 基于反射的 在线医疗项目(三)
前言:
本片文章我们需要实现管理页的列表+分页功能,以及常见的增删改查和查询,我们就拿门诊医生管理为例,其他的和其相似,我就不写在这了。而且,我就不废话,直接说功能点。
一、门诊医生管理列表和分页实现
1.前端ajax请求
这里需要注意,我们把列表和搜索的功能写在了同样的方法list中,也就是说,list方法需要接收的参数是:第几页page,科室department,以及医生姓名name参数。即 doctor/ index.jsp:
doctor/ index.jsp代码:
function showList(page, department, name) {
$.ajax({
url: "${path}doctors/list?page=" + page + "&department=" + department + "&name=" + name,
type: "GET",
dataType: "json",
success: function (message) {
$("#doctor-table tr").remove();
console.log(message);
$("#current").text(message.count); // 共多少条记录
$("#pageTotal").text(message.countPage); // 页数
$("#firstPage").attr("page", 1);
$("#prePage").attr("page", message.prePage);
$("#nextPage").attr("page", message.nextPage);
$("#lastPage").attr("page", message.countPage);
var datas = message.pageList;
$.each(datas, function (index, item) {
card(item);
})
}
});
}
function card(item) {
var tr = "<tr>" +
/* "<th><input type='checkbox' value='" + item.did + "'" + "></th>" + */
"<th><label class='my_protocol'><input class='input_agreement_protocol' type='checkbox' value='" + item.did + "'" + " /><span></span></label></th>" +
"<td>" + item.did + "</td>" +
"<td>" + item.name + "</td>" +
"<td>" + item.phone + "</td>" +
"<td>" +"<span class='"+item.tag_color+"' style='padding: 6px;'>" + item.dname +"</span>"+ "</td>" +
"<td>" +
"<button type='button' class='btn btn-info' onclick='doctor_detail(" + item.did + ")' >详情</button>" +
"<button class='btn btn-warning' type='button' onclick='doctor_edit(" + item.did + ")' >修改</button>" +
"<button type='button' class='btn btn-danger' onclick='doctor_delete(" + item.did + ")'>删除</button>" +
"</td>" +
"</tr>";
$("#doctor-table").append($(tr));
}
2. 分页封装类Pages
我们需要封装一个分页的实体类Pages,而且是泛型的,其中的属性为:initSize,每页显示的条数(可以更改),count,总共的条数;countPage,共有多少页;currentPage,当前页;prePage,上一页;nextPage,下一页;pageList,页面数据。
完整代码如下:
import java.util.List;
/**
* Page:分页的实体类
* @author 段振彪
*
*/
public class Pages<T> {
private Integer initSize = 5; // 每页显示的条数
private Long count ; // 总共的条数
private Integer countPage ; //总共有多少页
private Integer currentPage ; // 当前页
private Integer prePage; // 上一页
private Integer nextPage; // 下一页
private List<T> pageList; // 页面的数据
public Pages() {
}
public Pages(Integer initSize, Long count, Integer currentPage, List<T> pageList) {
this.initSize = initSize;
this.count = count;
Long num = count / initSize;
this.countPage = (int)(count % initSize == 0 ? num : num + 1);
this.currentPage = currentPage < 0 ? 1: currentPage > countPage ? countPage : currentPage;
// 如果当前页大于1,则 上一页为当前页 -1 ,否则为1
this.prePage = currentPage > 1 ? currentPage -1 : 1;
// 如果当前页小于总页码,下一页为当前页+1,否则为总页码。
this.nextPage = currentPage < this.countPage ? currentPage +1 : this.countPage;
this.pageList = pageList;
}
public Integer getInitSize() {
return initSize;
}
public void setInitSize(Integer initSize) {
this.initSize = initSize;
}
public Long getCount() {
return count;
}
public void setCount(Long count) {
this.count = count;
}
public Integer getCountPage() {
return countPage;
}
public void setCountPage(Integer countPage) {
this.countPage = countPage;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getPrePage() {
return prePage;
}
public void setPrePage(Integer prePage) {
this.prePage = prePage;
}
public Integer getNextPage() {
return nextPage;
}
public void setNextPage(Integer nextPage) {
this.nextPage = nextPage;
}
public List<T> getPageList() {
return pageList;
}
public void setPageList(List<T> pageList) {
this.pageList = pageList;
}
@Override
public String toString() {
return "Pages [initSize=" + initSize + ", count=" + count + ", countPage=" + countPage + ", currentPage="
+ currentPage + ", prePage=" + prePage + ", nextPage=" + nextPage + ", pageList=" + pageList + "]";
}
}
3.list 方法
DoctorServlet.java
public void list(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
// 消息实体
Message message = new Message();
ObjectMapper mapper = new ObjectMapper();
String json = null;
// 当前页
String pageStr = request.getParameter("page");
if(pageStr == null || pageStr.length() == 0) {pageStr = "1";} // 如果接收不到page参数,默认返回第一页数据。
// 设置每页返回数据的大小Size
int SIZE = 5; // 暂时先设置为5;
int page = Integer.parseInt(pageStr);// 强转
// 科室
String department = request.getParameter("department");
// 医生的姓名
String docName = request.getParameter("name");
Doctor doctor = new Doctor(docName);
doctor.setDepartment(Integer.parseInt(department));
// 泛型为 Map<String, Object>
Pages<Map<String, Object>> pages = doctorService.doctorList(doctor,page,SIZE);
// 写response
json = mapper.writeValueAsString(pages);
response.getWriter().print(json);
}
DoctorService接口:(service.包下新建DoctorService接口类)
Pages<Map<String, Object>> doctorList(Doctor doctor, int page, int sIZE);
DoctorServiceImpl实现类:(service.Impl包下新建DoctorServiceImpl实现类)
DoctorDao doctorDao = new DoctorDaoImpl();
@Override
public Pages<Map<String, Object>> doctorList(Doctor doctor, int page, int sIZE) {
return doctorDao.doctorList( doctor, page, sIZE);
}
DoctorDao接口 :(dao包下新建DoctorDao接口类)
List<Map<String, Object>> selectDoctors(Doctor doctor, int start, int sIZE);
Pages<Map<String, Object>> doctorList(Doctor doctor, int page, int sIZE);
DoctorDaoImpl实现类:
// 获取资源连接
private QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
@Override
public Pages<Map<String, Object>> doctorList(Doctor doctor, int page, int sIZE) {
System.out.println("*******************************");
// 获取符合条件的医生总条数
Long count = getDoctorCount(doctor);
int start = (page - 1)*sIZE;
List<Map<String, Object>> ls = selectDoctors(doctor,start,sIZE);
Pages<Map<String, Object>> pages = new Pages<Map<String, Object>>(sIZE,count,page,ls);
return pages;
}
// 获取符合条件的医生总条数
private Long getDoctorCount(Doctor doctor) {
StringBuilder sb = new StringBuilder("select count(*) from doctor where 1=1 ");
String sql = contionSql(doctor,sb);
System.out.println(sql);
Long count = null ;
try {
count = qr.query(sql, new ScalarHandler<Long>());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}
/**
* 选择符合条件的医生列表
*/
@Override
public List<Map<String, Object>> selectDoctors(Doctor doctor, int start, int sIZE) {
StringBuilder sb = new StringBuilder("select * from doctor,department where 1=1 and doctor.department = department.id ");
String sql = contionSql(doctor,sb)+" order by -did " + " limit ?,?";
System.out.println("sql:"+sql);
List<Doctor> doctors = null;
List<Map<String, Object>> mapList = null;
try {
mapList = qr.query(sql, new MapListHandler(),start,sIZE);
} catch (SQLException e) {
System.out.println("selectDoctors方法出错:" );
}
System.out.println(mapList);
return mapList;
}
//Sql 字符串拼接
private String contionSql(Doctor doctor, StringBuilder sb) {
String name = doctor.getName();
if(name != null && name.trim() != "") {
sb.append(" and name like '%" + name + "%'");
}
int department = doctor.getDepartment();
if(department != 0) {
sb.append(" and department=" + department);
}
String sql = sb.toString();
return sql;
}
4.response返回数据的结构
当我们写完list逻辑之后,请求 http://localhost:8080/hospital/doctors/list?page=1&department=0&name= 返回的数据格式为:
其中,这个过程中 ,会有一个乱码问题,即我们直接访问后端数据接口时,返回的数据中文呈现乱码问题,而页面数据却正常显示,因为jsp页面中设置UTF-8,解决的办法为:在filter 包下创建一个EncodingFilter类:
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 编码过滤器 : 处理请求的乱码问题。
*/
@WebFilter("/*")
public class EncodingFilter implements Filter {
public EncodingFilter() {}
/**
* @see Filter#destroy()
*/
public void destroy() {
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
// 强转为HttpServletRequest对象
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
request.setCharacterEncoding("UTF-8");
// 设置编码格式,防止出现中文乱码。
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
5.前端分页逻辑
我们需要在分页的部分添加id定位点,绑定点击方法。
doctor/index.jsp页面添加
// 页面初始化加载:列表
$(function () {
var page = 1;
var department = $("#department option:selected").val();
var name = $("#name").val();
showList(page, department, name);
});
//首页
$("#firstPage").click(function () {
var page = $(this).attr("page");
var department = $("#department option:selected").attr("value");
var name = $("#name").val();
showList(1, department, name);
});
// 上一页:
$("#prePage").click(function () {
var page = $(this).attr("page");
var department = $("#department option:selected").attr("value");
var name = $("#name").val();
showList(page, department, name);
});
// 下一页:
$("#nextPage").click(function () {
var page = $(this).attr("page");
var department = $("#department option:selected").attr("value");
var name = $("#name").val();
showList(page, department, name);
});
// 最后一页
$("#lastPage").click(function () {
var page = $(this).attr("page");
var department = $("#department option:selected").attr("value");
var name = $("#name").val();
showList(page, department, name);
});
二、添加
1.前端ajax请求
添加按钮 触发方法,进入add.jsp,我们在add.jsp 页面中添加提交方法。
// 添加按钮,href 改变为 doctor/add.jsp
$("#newNav").click(function () {
window.location.href = "${path}doctor/add.jsp";
});
2.表单验证
表单验证和之前登陆注册的验证原理一样,使用的也是jQuery-validate插件。在这我就不贴代码了,代码地址:https://gitee.com/duanxiaobiao/hospital-jsp/blob/master/WebContent/doctor/add.jsp
3.添加和删除方法
public void add(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
String name = request.getParameter("name");
String cardno = request.getParameter("cardno");
String phone = request.getParameter("phone");
String sex = request.getParameter("sex");
String age = request.getParameter("age");
String birthday = request.getParameter("birthday");
String email = request.getParameter("email");
String department = request.getParameter("department");
String education = request.getParameter("education");
String remark = request.getParameter("remark");
int sexInt = Integer.parseInt(sex);
int ageInt = Integer.parseInt(age);
int departmentInt = Integer.parseInt(department);
int educationInt = Integer.parseInt(education);
Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(birthday);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Doctor doctor = new Doctor(name,cardno,phone,sexInt,ageInt,date,email,departmentInt,educationInt,remark);
System.out.println(doctor);
int result = doctorService.addDoctor(doctor);
Message message = new Message();
if(result == 1) {
System.out.println("添加成功");
message.setStatus_code(200);
message.setMessage("添加成功");
}else {
// 添加失败
System.out.println("添加失败.");
message.setStatus_code(100);
message.setMessage("添加失败");
}
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(message);
response.getWriter().print(json);
}
public void delete(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
System.out.println("delete方法被调用...............................................");
String id = request.getParameter("did");
System.out.println("DID:" + id);
Message message = new Message();
int result = doctorService.delete(id);
System.out.println(result);
if(result > 0) {
message.setStatus_code(200);
message.setMessage("操作成功!");
}else {
message.setStatus_code(100);
message.setMessage("操作失败!");
}
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(message);
response.getWriter().print(json);
}
DoctorService接口
int addDoctor(Doctor doctor);
int delete(String id);
DoctorServiceImpl实现类:
@Override
public int addDoctor(Doctor doctor) {
// TODO Auto-generated method stub
return doctorDao.addDoctor(doctor);
}
@Override
public int delete(String id) {
return doctorDao.delete(id);
}
DoctorDao 接口
int addDoctor(Doctor doctor);
int delete(String id);
DoctorDaoImpl实现类
@Override
public int addDoctor(Doctor doctor) {
String sql = "insert into doctor(name,cardno,phone,sex,age,birthday,email,department,education,remark)"
+ "values(?,?,?,?,?,?,?,?,?,?)";
int result = 0;
try {
result = qr.update(sql,doctor.getName(),doctor.getCardno(),doctor.getPhone(),
doctor.getSex(),doctor.getAge(),doctor.getBirthday(),doctor.getEmail(),doctor.getDepartment(),doctor.getEducation(),doctor.getRemark());
} catch (SQLException e) {
System.out.println(e);
}
return result;
}
@Override
public int delete(String id) {
String sql = "delete from doctor where did in (" + id + ")";
int result = 0;
try {
result = qr.update(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
删除点击事件:
注意消息提示需在index.jsp插入 :
<!--消息提示框 -->
<script type="text/javascript" src="../static/js/coco-message.js"></script>
// 删除
function doctor_delete(did) {
if (confirm("您确认要删除这条数据吗?")) {
$.ajax({
url: "${path}doctors/delete",
type: "post",
data: {"did": did},
dataType: "json",
success: function (message) {
// 删除成功的话
if (message.status_code == 200) {
cocoMessage.success("删除成功",30000);
location.reload();
} else {
cocoMessage.error("删除失败!",30000);
}
}, error: function () {
alert("异常")
cocoMessage.warning("异常!",30000);
}
});
} else {
console.log("用户取消了单条数据删除.");
}
}
三、修改
修改也是相同的逻辑,在这略了,累了。(有时间再补,再调整页面样式...)