AJAX版MVC三层架构

filters----全局过滤器

防止乱码

package com.qf.villagepro.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

//设置编码格式
@WebFilter(filterName = "CharacterSetFilter",value = "/*")
public class CharacterSetFilter implements Filter {
    public void destroy() {
    }
    //当拦截到请求时,就会执行doFileter里的方法
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //设置编码格式
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //对请求放行,放行后,就到下一个过滤器
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

登录-----放cookie和session

package com.qf.villagepro.filters;



import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",value = "/*")
public class LoginFilter implements Filter {


    public void destroy() {
    }
    //设置一个白名单
    //一个是登陆的html页面,一个是登录请求的servlet
    String[] ary = {"Login.html","LoginServlet"};
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //提升类型
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        //先设置flag为false
        boolean flag = false;


        //获取网址中的地址
        //localhost:8080 ----- /village_pro2105_war_exploded/Login.html
        String url = req.getRequestURI();

        //遍历数组
        for(String str:ary){
            //判断数组当中是否有url存在的地址,有的话返回true
            if (url.contains(str)) {
                flag=true;
                break;
            }
        }

        //获取cookie并循环遍历,找名字为Property的
        Cookie[] cookies = req.getCookies();

        //获取session
        HttpSession session = req.getSession();

        //当cookie不为空的情况下
        if (cookies!=null){
            //遍历cookie
            for (Cookie c:cookies){
                //如果说cooie中存在的名字和servlet中创建的cookie的那个名字一样
                if(c.getName().equals("Property")){

                    //那就给session赋值,
                    //赋的值是cokie里边的东西
                    //然后用session来判断
                    session.setAttribute("Login",c.getName());
                    break;
                }
            }
        }

        //创建对象得到的servlet
        //浏览器不关再打开,这个时候还需要session判断一下,所以要取值
        //得到的是个对象需要Object来接收
        Object obj =session.getAttribute("Login");

        //判断白名单也就是是否遍历到是的话,为true放行
        if (flag){
            //反放行
            chain.doFilter(req, res);
        }else{
            //obj不为空的时候放行
            //不为空就是有值,有值就是登陆过了
            //目的是为了,浏览器不关掉的情况下,复制网址,再次打开,依旧可以放行
            if (obj!= null){
                chain.doFilter(req, res);
            }else{
                //最后跳转登陆界面
                res.sendRedirect("Login.html");
            }
        }




    }

    public void init(FilterConfig config) throws ServletException {

    }


}



Util工具

增删改查 + 事务

package com.qf.villagepro.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.DbUtils;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtil {
    //声明局部线程类:保存自己的连接
    //类map集合  key是线程id  value 是connection对象
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
    //声明连接池对象:提升获取连接的效率
    private static DruidDataSource dataSource;

    static {
        InputStream inputStream = DbUtils.class.getResourceAsStream("/db.properties");
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
            //创建连接池对象
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        //到连接池中获取连接
        //第一步:先到局部线程类中获取自己原有的连接
        //第二步:判断是否获取到,如果获取到,则使用获取到的,如果没有获取到自己原来的连接,那么到连接池获取
        Connection connection = threadLocal.get();
        if (connection == null) {
            //没有获取到自己线程使用的connection对象

            try {
                //从连接池获取
                connection = dataSource.getConnection();
                //存入局部线程
                threadLocal.set(connection);
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        return connection;
    }

    //返回连接池对象
    public static DataSource getDataSource() {
        return dataSource;
    }
}

分页查询

package com.qf.villagepro.utils;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;

//写一个工具用来返回总页数
public class PageUtil {
    //第一个参数是表名  第二个参数是每页显示的记录数  第三个是主键
    public static int getTotalPages(String tableName,int pageSize,String key) throws SQLException {
        String sql="select count("+key+") totalcount from "+ tableName;
        QueryRunner queryRunner = new QueryRunner(com.qf.villagepro.utils.DBUtil.getDataSource());

        int totalCount = 0;
        //ScalarHandleru用来得到表总共有多少列,也就是总记录数,返回的是Long类型
        //总记录数
        Long l = queryRunner.query(sql,new ScalarHandler<Long>());
        totalCount = Integer.parseInt(l.toString());
        //如果能整除开返回的是第一个否则就是第二个
        int totalPages = totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
        return totalPages;
    }
}



登录-----非ajax

登录主要是四个东西来写,分别是登录的html  登录成功后跳转的html  登录的servlet 和 filter

登陆的html写登录文本框-------这个界面xml不拦截

跳转到servlet  ----- servlet之中有cookie和session 

网页登录有两种 一种是记住密码登录  一种是没记住密码登录

没记住密码登录-----直接把数据库中找到的值存放在session中,session的存在时间是浏览器关闭的时候,关闭之后没有值了没这样的话再打开浏览器登录就需要重新给session赋值

记住密码登录------是先点击记住密码的这个按钮,这个时候就把从数据库找到的值放进cookie中,然后再存放在session中,浏览器关闭之后再打开,cookie会发送给session,下次再登录session会去和cookie比较,cookie传的值给了session,session去比较一定是一样的,所以实现免密登录

无论是否记住密码cookie依旧传给session只不过是cookie传的值有没有你登录的账号和密码

每一次的跳转页面,cookie的值都会传给session,靠session来判断所以需要全局过滤器去给cookie和session赋值

cookie是服务器传给客户端的体积很小的纯文本文件。

客户端请求服务器,如果服务器需要记录该用户状态,就向客户端浏览器发一个cookie。

客户端浏览器会把cookie保存起来。当浏览器再请求该网站时,

浏览器把请求的网址连同该cookie一同提交给服务器。服务器检查该cookie,以此来辨认用户状态
 

entity

package com.qf.villagepro.entity;
//用户表----存储用户信息包含会员和管理员
public class Sys_User {
    private int id;
    private String userName;
    private String realName;
    private String passWord;
    private String phone;
    private String email;
    private String hireDate;
    private int type;
    private String img;
    private int available;

    public Sys_User(int id, String userName, String realName, String passWord,
                    String phone, String email, String hireDate, int type,
                    String img, int available) {
        this.id = id;
        this.userName = userName;
        this.realName = realName;
        this.passWord = passWord;
        this.phone = phone;
        this.email = email;
        this.hireDate = hireDate;
        this.type = type;
        this.img = img;
        this.available = available;
    }

    public Sys_User() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getHireDate() {
        return hireDate;
    }

    public void setHireDate(String hireDate) {
        this.hireDate = hireDate;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getImg() {
        return img;
    }

    public void setImg(String img) {
        this.img = img;
    }

    public int getAvailable() {
        return available;
    }

    public void setAvailable(int available) {
        this.available = available;
    }
}

dao

//接口
package com.qf.villagepro.dao;

import com.qf.villagepro.entity.Sys_User;

import java.sql.SQLException;

public interface Sys_UserDao {
    //添加-----没有实现
    int addUser(Sys_User sys_user) throws SQLException;

    //查询-----登录
    Sys_User Login(Sys_User sys_user) throws SQLException;

}





//具体实现的方法
package com.qf.villagepro.dao.impl;


import com.qf.villagepro.dao.Sys_UserDao;
import com.qf.villagepro.entity.Sys_User;
import com.qf.villagepro.utils.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class Sys_UserDaoImpl implements Sys_UserDao {
    //引入连接池对象
    QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());

    //添加
    @Override
    public int addUser(Sys_User sys_user) throws SQLException {
        String sql = "insert into sys_user(id,username,realname,password,phone,email,hiredate,type,img,available) values(?,?,?,?,?,?,?,?,?,?)";
        Object[] params = {sys_user.getId(),sys_user.getUserName(),
                           sys_user.getRealName(),sys_user.getPassWord(),
                           sys_user.getPhone(),sys_user.getEmail(),
                           sys_user.getHireDate(),sys_user.getType(),sys_user.getImg(),
                           sys_user.getAvailable()};

       int result = queryRunner.update(sql,params);
        return result;
    }

    //查询----登录
    @Override
    public Sys_User Login(Sys_User sys_user) throws SQLException {
        String sql = "select id,username,realname,password,phone,email,hiredate,type,img,available From sys_user where username=?";

        //查询一条的话是BeanHandler
        //查询多条是BeanList

        Sys_User s = null;

        s=queryRunner.query(sql,new BeanHandler<Sys_User>(Sys_User.class),sys_user.getUserName());
        return s;
    }
}

service

//接口
package com.qf.villagepro.service;

import com.qf.villagepro.entity.Sys_User;

import java.sql.SQLException;

public interface Sys_UserService {

    //添加
    boolean addUser(Sys_User sys_user) throws SQLException;
    //查询
    public Sys_User Login(Sys_User sys_user) throws SQLException;
}






//具体实现的方法
package com.qf.villagepro.service.impl;


import com.qf.villagepro.dao.Sys_UserDao;
import com.qf.villagepro.dao.impl.Sys_UserDaoImpl;
import com.qf.villagepro.entity.Sys_User;
import com.qf.villagepro.service.Sys_UserService;

import java.sql.SQLException;

public class Sys_UserServiceImpl implements Sys_UserService {
    Sys_UserDao sys_userDao = new Sys_UserDaoImpl();

    //添加
    @Override
    public boolean addUser(Sys_User sys_user) throws SQLException {
        int result = sys_userDao.addUser(sys_user);
        if(result==1){
            return true;
        }else {
            return false;
        }
    }

    //查询-----登录
    @Override
    public Sys_User Login(Sys_User sys_user) throws SQLException {
        Sys_User s = sys_userDao.Login(sys_user);
        //s是查到的账户

        if(s != null){
            //判断密码是否正确
            //前边是传值获取到的,后边是数据库查到的
            if(sys_user.getPassWord().equals(s.getPassWord())){
                return s;
            }else{
                return null;
            }
        }
        //为空的时候返回null
        return null;
    }
}

servlet层

package com.qf.villagepro.servlet;


import com.qf.villagepro.entity.Sys_User;
import com.qf.villagepro.service.Sys_UserService;
import com.qf.villagepro.service.impl.Sys_UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1获取表单标签
        String userName = request.getParameter("userName");
        String passWord = request.getParameter("passWord");
        String getResult = request.getParameter("autoLogin");
        Sys_User user = new Sys_User();
        user.setUserName(userName);
        user.setPassWord(passWord);
        //调用业务逻辑
        Sys_UserService userService = new Sys_UserServiceImpl();
        try {
            //把user传进去之后会返回一个对象 称为u
            Sys_User u =userService.Login(user);
            //不为空证明找到了
            if(u!=null){
                //说明登录成功,判断是否保存cookie
                //判断时候点击复选框
                if (getResult!=null){
                    //得到的值为on证明是点击了记住密码这个按钮
                    if (getResult.equals("on")){
                        //创建cookie,并起名,名字的key键是Peoperty 值是数据库的账户
                        //因为登录就是判断是否先等,所以登录成功证明表单数据的账户
                        //就是数据库的账户
                        //值存的是用户名
                        Cookie cookie = new Cookie("Property",u.getUserName());

                        //设置cookie的有效时间,一年
                        cookie.setMaxAge(60*60*24*365);

                        //将cookie返回给浏览器
                        response.addCookie(cookie);
                    }
                }


                //没点击记住密码按钮直接放在了session里边

                //登录成功的话获取session
                HttpSession session = request.getSession();

                //给session赋值----key为Login 存的值为u,数据路找到的对象
                session.setAttribute("Login",u);

                //然后转发,跳转界面
                response.sendRedirect("main.html");

            }else{
                //这样证明没有登陆成功,就返回重新登录这个界面
                response.sendRedirect("Login.html");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}

前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登陆界面</title>
</head>
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" type="text/javascript" charset="utf-8">
    //CDN引入,加速
</script>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>

<script>

</script>

<body>
    <form method="post" action="LoginServlet">
        <p>账户:<input type="text" name="userName" /></p>
        <p>密码:<input type="password" name="passWord"/></p>
        <p>自动登录:<input type="checkbox" name="autoLogin"/></p>
        <p><input type="submit" value="登录"/></p>
    </form>
</body>
</html>

登录成功之后跳转到的主页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <p><a href="finddept.html">小区主页</a></p>

</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

        <!--配置默认访问的页面-->
<welcome-file-list>
    <welcome-file>Login.html</welcome-file>
</welcome-file-list>
</web-app>

查询功能----查询是第一个要写的他决定着页面显示什么

entity类

package com.qf.villagepro.entity;
//小区表
public class Db_Community implements Serializable{
    private int id;
    private String communityNum;
    private String name;
    private String address;
    private double communityArea;
    private int buildingNum;
    private int roomNum;
    private String img;
    private int greeningRate;
    private String developerName;
    private String propertyName;
    private String hiredate;
    private int state;
    private int uid;

    public Db_Community(int id, String communityNum, String name,
                        String address, double communityArea, int buildingNum,
                        int roomNum, String img, int greeningRate,
                        String developerName, String propertyName,
                        String hiredate, int state, int uid) {
        this.id = id;
        this.communityNum = communityNum;
        this.name = name;
        this.address = address;
        this.communityArea = communityArea;
        this.buildingNum = buildingNum;
        this.roomNum = roomNum;
        this.img = img;
        this.greeningRate = greeningRate;
        this.developerName = developerName;
        this.propertyName = propertyName;
        this.hiredate = hiredate;
        this.state = state;
        this.uid = uid;
    }

    public Db_Community() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCommunityNum() {
        return communityNum;
    }

    public void setCommunityNum(String communityNum) {
        this.communityNum = communityNum;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public double getCommunityArea() {
        return communityArea;
    }

    public void setCommunityArea(double communityArea) {
        this.communityArea = communityArea;
    }

    public int getBuildingNum() {
        return buildingNum;
    }

    public void setBuildingNum(int buildingNum) {
        this.buildingNum = buildingNum;
    }

    public int getRoomNum() {
        return roomNum;
    }

    public void setRoomNum(int roomNum) {
        this.roomNum = roomNum;
    }

    public String getImg() {
        return img;
    }

    public void setImg(String img) {
        this.img = img;
    }

    public int getGreeningRate() {
        return greeningRate;
    }

    public void setGreeningRate(int greeningRate) {
        this.greeningRate = greeningRate;
    }

    public String getDeveloperName() {
        return developerName;
    }

    public void setDeveloperName(String developerName) {
        this.developerName = developerName;
    }

    public String getPropertyName() {
        return propertyName;
    }

    public void setPropertyName(String propertyName) {
        this.propertyName = propertyName;
    }

    public String getHiredate() {
        return hiredate;
    }

    public void setHiredate(String hiredate) {
        this.hiredate = hiredate;
    }

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }
}

Dao层



//接口


package com.qf.villagepro.dao;

import com.qf.villagepro.entity.Db_Community;

import java.sql.SQLException;
import java.util.List;

//小区
public interface Db_CommunityDao {
 
    //查询
    List<Db_Community> findCommunity() throws SQLException;


}



//继承的方法
package com.qf.villagepro.dao.impl;

import com.qf.villagepro.dao.Db_CommunityDao;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.utils.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class Db_CommunityDaoImpl implements Db_CommunityDao {
    private QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());


    //查询
    @Override
    public List<Db_Community> findCommunity() throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community";

        List<Db_Community> list = null;
        list = queryRunner.query(sql,new BeanListHandler<Db_Community>(Db_Community.class));
        return list;
    }


}

Service层



//接口


package com.qf.villagepro.service;

import com.qf.villagepro.entity.Db_Community;

import java.sql.SQLException;
import java.util.List;

public interface Db_CommunityService {
   
    //查询
    List<Db_Community> findCommunity() throws SQLException;

}








//实现方法
package com.qf.villagepro.service.impl;

import com.qf.villagepro.dao.Db_CommunityDao;
import com.qf.villagepro.dao.impl.Db_CommunityDaoImpl;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.service.Db_CommunityService;

import java.sql.SQLException;
import java.util.List;

public class Db_CommunityServiceImpl implements Db_CommunityService {
    private Db_CommunityDao db_communitydao = new Db_CommunityDaoImpl();


    //查询
    @Override
    public List<Db_Community> findCommunity() throws SQLException {
        return db_communitydao.findCommunity();
    }

 
}

servlet层

package com.qf.villagepro.servlet;

import com.alibaba.fastjson.JSON;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.service.Db_CommunityService;
import com.qf.villagepro.service.impl.Db_CommunityServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "findCommunityServlet",value = "/findCommunityByAJAX")
public class findCommunityServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取表单数据

        //调用业务逻辑
        Db_CommunityService db_communityService = new Db_CommunityServiceImpl();

        //创建json
        String json="";

        try {
            //将查询到的结果返回到list集合里
            List<Db_Community> list = db_communityService.findCommunity();
            //调用json方法 将list集合里的内容转换到json类型
            json = JSON.toJSONString(list);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        //输出json
        response.getWriter().print(json);
    }
}

前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>部门主页</title>
    <style>
        #community{
            text-align: center;
            border-collapse: collapse;
            width: 1500px;
        }

        #community td{
            border: 1px solid black;
        }
    </style>
    <script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
    <script>
        $(function(){
            initCommunity();
        });
        
        function initCommunity() {
            $.ajax({
                url:"findCommunityByAJAX",
                type:"get",
                dataType:"json",
                async:true,

                success:function (jsonData) {
                    setDataToTable(jsonData);
                }
            })
        }

        function setDataToTable(jsonData) {
            var table=$("#community")

            var th=$("<tr><td>序号</td><td>小区编号</td><td>小区名称</td><td>小区地址</td><td>小区面积</td><td>总栋数</td><td>总户数</td><td>小区图片</td><td>小区绿化率</td><td>开发商名称</td><td>物业名称</td><td>创建时间</td><td>状态</td><td>管理员ID</td><td>操作</td></tr>")
            table.append(th);

            for(var i=0; i<jsonData.length; i++){
                var community =jsonData[i];
                // 创建行
                var tr=$("<tr></tr>");
                table.append(tr);
                //创建列
                var td1=$("<td></td>");
                td1.text(community.id);
                tr.append(td1);

                var td2=$("<td></td>");
                td2.text(community.communityNum);
                tr.append(td2);

                var td3=$("<td></td>");
                td3.text(community.name);
                tr.append(td3);

                var td4=$("<td></td>");
                td4.text(community.address);
                tr.append(td4);

                var td5=$("<td></td>");
                td5.text(community.communityArea);
                tr.append(td5);

                var td6=$("<td></td>");
                td6.text(community.buildingNum);
                tr.append(td6);

                var td7=$("<td></td>");
                td7.text(community.roomNum);
                tr.append(td7);

                var td8=$("<td></td>");
                td8.text(community.img);
                tr.append(td8);

                var td9=$("<td></td>");
                td9.text(community.greeningRate);
                tr.append(td9);

                var td10=$("<td></td>");
                td10.text(community.developerName);
                tr.append(td10);

                var td11=$("<td></td>");
                td11.text(community.propertyName);
                tr.append(td11);

                var td12=$("<td></td>");
                td12.text(community.hiredate);
                tr.append(td12);

                var td13=$("<td></td>");
                td13.text(community.state);
                tr.append(td13);

                var td14=$("<td></td>");
                td14.text(community.uid);
                tr.append(td14);

                var td15=$("<td></td>");
                tr.append(td15);

                var deleteA=$("<a href='#'>删除</a>");
                var editA=$("<a href='#'>修改</a>");

                td15.append(deleteA);
                td15.append($(""));
                td15.append(editA);
            }



        }
    </script>
</head>
<body>

    <table id="community">
        <tr>

        </tr>
    </table>
</body>
</html>



删除功能----删除功能可以与查询在同一个页面下进行

Dao层

//接口方法

package com.qf.villagepro.dao;

import com.qf.villagepro.entity.Db_Community;

import java.sql.SQLException;
import java.util.List;

//小区
public interface Db_CommunityDao {
 
    //查询
    List<Db_Community> findCommunity() throws SQLException;
    //删除
    int deleteCommunity(int id) throws SQLException;
    

}



//实现的方法
package com.qf.villagepro.dao.impl;

import com.qf.villagepro.dao.Db_CommunityDao;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.utils.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class Db_CommunityDaoImpl implements Db_CommunityDao {
    private QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
  


    //查询
    @Override
    public List<Db_Community> findCommunity() throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community";

        List<Db_Community> list = null;
        list = queryRunner.query(sql,new BeanListHandler<Db_Community>(Db_Community.class));
        return list;
    }

    //删除
    @Override
    public int deleteCommunity(int id) throws SQLException {
        String sql = "delete from db_community where id=?";
        return queryRunner.update(sql,id);
    }


}

Service层

//接口

package com.qf.villagepro.service;

import com.qf.villagepro.entity.Db_Community;

import java.sql.SQLException;
import java.util.List;

public interface Db_CommunityService {

    //查询
    List<Db_Community> findCommunity() throws SQLException;


    //删除
    boolean deleteCommunity(int id) throws SQLException;
}






//实现的方法
package com.qf.villagepro.service.impl;

import com.qf.villagepro.dao.Db_CommunityDao;
import com.qf.villagepro.dao.impl.Db_CommunityDaoImpl;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.service.Db_CommunityService;

import java.sql.SQLException;
import java.util.List;

public class Db_CommunityServiceImpl implements Db_CommunityService {
    private Db_CommunityDao db_communitydao = new Db_CommunityDaoImpl();



    //查询
    @Override
    public List<Db_Community> findCommunity() throws SQLException {
        return db_communitydao.findCommunity();
    }

    //删除
    @Override
    public boolean deleteCommunity(int id) throws SQLException {
    int result = db_communitydao.deleteCommunity(id);
        return result==1;
    }
}

Servlet层

package com.qf.villagepro.servlet;

import com.qf.villagepro.service.Db_CommunityService;
import com.qf.villagepro.service.impl.Db_CommunityServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "DeleteCommunityServlet",value = "/deleteCommunityByAJAX")
public class DeleteCommunityServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //获取表单数据
       //id指的是url?后边的id
        int id = Integer.parseInt(request.getParameter("id"));

        //调整业务逻辑
        Db_CommunityService db_communityService = new Db_CommunityServiceImpl();
        String meg="";
        try {
            boolean result = db_communityService.deleteCommunity(id);
            if(result){
                meg="success";
            }else{
                meg="failed";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            meg="failed";
        }

        //响应结果
        response.getWriter().print(meg);
    }
}

前端----在原有查询的基础上加入empty移除和闭包然后ajax发出请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>部门主页</title>
    <style>
        #community{
            text-align: center;
            border-collapse: collapse;
            width: 1500px;
        }

        #community td{
            border: 1px solid black;
        }
    </style>
    <script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
    <script>
        $(function(){
            initCommunity();
        });
        
        function initCommunity() {
            $.ajax({
                url:"findCommunityByAJAX",
                type:"get",
                dataType:"json",
                async:true,

                success:function (jsonData) {
                    setDataToTable(jsonData);
                }
            })
        }

        function setDataToTable(jsonData) {
            var table=$("#community")

            //把表格里的内容删除
            table.empty();

            var th=$("<tr><td>序号</td><td>小区编号</td><td>小区名称</td><td>小区地址</td><td>小区面积</td><td>总栋数</td><td>总户数</td><td>小区图片</td><td>小区绿化率</td><td>开发商名称</td><td>物业名称</td><td>创建时间</td><td>状态</td><td>管理员ID</td><td>操作</td></tr>")
            table.append(th);

            

            for(var i=0; i<jsonData.length; i++){
                var community =jsonData[i];
                // 创建行
                var tr=$("<tr></tr>");
                table.append(tr);
                //创建列
                var td1=$("<td></td>");
                td1.text(community.id);
                tr.append(td1);

                var td2=$("<td></td>");
                td2.text(community.communityNum);
                tr.append(td2);

                var td3=$("<td></td>");
                td3.text(community.name);
                tr.append(td3);

                var td4=$("<td></td>");
                td4.text(community.address);
                tr.append(td4);

                var td5=$("<td></td>");
                td5.text(community.communityArea);
                tr.append(td5);

                var td6=$("<td></td>");
                td6.text(community.buildingNum);
                tr.append(td6);

                var td7=$("<td></td>");
                td7.text(community.roomNum);
                tr.append(td7);

                var td8=$("<td></td>");
                td8.text(community.img);
                tr.append(td8);

                var td9=$("<td></td>");
                td9.text(community.greeningRate);
                tr.append(td9);

                var td10=$("<td></td>");
                td10.text(community.developerName);
                tr.append(td10);

                var td11=$("<td></td>");
                td11.text(community.propertyName);
                tr.append(td11);

                var td12=$("<td></td>");
                td12.text(community.hiredate);
                tr.append(td12);

                var td13=$("<td></td>");
                td13.text(community.state);
                tr.append(td13);

                var td14=$("<td></td>");
                td14.text(community.uid);
                tr.append(td14);

                var td15=$("<td></td>");
                tr.append(td15);

                var deleteA=$("<a href='#'>删除</a>");
                var editA=$("<a href='#'>修改</a>");


                //解决闭包问题-----删除
                (function (index) {
                    var d=jsonData[index];
                    deleteA.click(function () {
                    //发出ajax请求
                        var result = confirm("确定要删除此条数据吗?")
                       if(result){
                           $.ajax({
                               url: "deleteCommunityByAJAX?id="+d.id,
                               type: "get",
                               //传回的不是数据而是success或者failed
                               dataType: "text",
                               async: true,
                               success:function (result) {
                                   if(result=="success"){
                                       //再次调用查询的方法
                                        initCommunity();
                                   }else{
                                        alert("删除失败!")
                                   }
                               }
                           })
                       }
                    })
                })(i)

                td15.append(deleteA);
                td15.append($(""));
                td15.append(editA);
            }



        }
    </script>
</head>
<body>
    <form>
        小区编号<input type="text" name="id"/>
        小区名称<input type="text" name="communityNum"/>
        <input type="button" onclick="queryCommunity" value="查询"/>
        <input type="button" onclick="addCommunity" value="添加">
    </form>
<hr/>
    <table id="community">
        <tr>

        </tr>
    </table>
</body>
</html>


添加

Dao层

//接口
package com.qf.villagepro.dao;

import com.qf.villagepro.entity.Db_Community;

import java.sql.SQLException;
import java.util.List;

//小区
public interface Db_CommunityDao {
    //添加
    int addDb_Community(Db_Community db_community) throws SQLException;
    //查询
    List<Db_Community> findCommunity() throws SQLException;
    //删除
    int deleteCommunity(int id) throws SQLException;
    
 
}






//实现的方法
package com.qf.villagepro.dao.impl;

import com.qf.villagepro.dao.Db_CommunityDao;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.utils.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class Db_CommunityDaoImpl implements Db_CommunityDao {
    private QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
    //添加
    @Override
    public int addDb_Community(Db_Community db_community) throws SQLException {
        String sql="insert into db_community(id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        Object[] params = {db_community.getId(),db_community.getCommunityNum(),
                           db_community.getName(),db_community.getAddress(),
                db_community.getCommunityArea(),db_community.getBuildingNum(),
                db_community.getRoomNum(),db_community.getImg(),
                db_community.getGreeningRate(),db_community.getDeveloperName(),
                db_community.getPropertyName(),db_community.getHiredate(),
                db_community.getState(),db_community.getUid()};
        int result = queryRunner.update(sql,params);
        return result;
    }


    //查询
    @Override
    public List<Db_Community> findCommunity() throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community";

        List<Db_Community> list = null;
        list = queryRunner.query(sql,new BeanListHandler<Db_Community>(Db_Community.class));
        return list;
    }

    //删除
    @Override
    public int deleteCommunity(int id) throws SQLException {
        String sql = "delete from db_community where id=?";
        return queryRunner.update(sql,id);
    }

 
}

Service层

//接口
package com.qf.villagepro.service;

import com.qf.villagepro.entity.Db_Community;

import java.sql.SQLException;
import java.util.List;

public interface Db_CommunityService {
    //添加
    boolean addDb_Community(Db_Community db_community) throws SQLException;
    //查询
    List<Db_Community> findCommunity() throws SQLException;

    //删除
    boolean deleteCommunity(int id) throws SQLException;
}





//具体实现的方法
package com.qf.villagepro.service.impl;

import com.qf.villagepro.dao.Db_CommunityDao;
import com.qf.villagepro.dao.impl.Db_CommunityDaoImpl;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.service.Db_CommunityService;

import java.sql.SQLException;
import java.util.List;

public class Db_CommunityServiceImpl implements Db_CommunityService {
    private Db_CommunityDao db_communitydao = new Db_CommunityDaoImpl();

    //添加
    @Override
    public boolean addDb_Community(Db_Community db_community) throws SQLException {
        int result = db_communitydao.addDb_Community(db_community);
        if(result == 1){
            return true;
        }else{
            return false;
        }

    }

    //查询
    @Override
    public List<Db_Community> findCommunity() throws SQLException {
        return db_communitydao.findCommunity();
    }

    //删除
    @Override
    public boolean deleteCommunity(int id) throws SQLException {
    int result = db_communitydao.deleteCommunity(id);
        return result==1;
    }
}

Servlet层----servlet层用于给单击添加之后跳转的页面 

package com.qf.villagepro.servlet;

import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.service.Db_CommunityService;
import com.qf.villagepro.service.impl.Db_CommunityServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

//value的addCommunityByAJAX是传递给adddept的
@WebServlet(name = "AddCommunityServlet",value = "/addCommunityByAJAX")
public class AddCommunityServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //获取表单数据
        Db_Community db_community = new Db_Community();

        //""里边的名字是adddept的name
        db_community.setId(Integer.parseInt(request.getParameter("id")));
        db_community.setCommunityNum(request.getParameter("communityNum"));
        db_community.setName(request.getParameter("name"));
        db_community.setAddress(request.getParameter("address"));
        db_community.setCommunityArea(Double.parseDouble(request.getParameter("communityArea")));
        db_community.setBuildingNum(Integer.parseInt(request.getParameter("buildingNum")));
        db_community.setRoomNum(Integer.parseInt(request.getParameter("roomNum")));
        db_community.setImg(request.getParameter("img"));
        db_community.setGreeningRate(Integer.parseInt(request.getParameter("greeningRate")));
        db_community.setDeveloperName(request.getParameter("developerName"));
        db_community.setPropertyName(request.getParameter("propertyName"));
        db_community.setHiredate(request.getParameter("hireDate"));
        db_community.setState(Integer.parseInt(request.getParameter("state")));
        db_community.setUid(Integer.parseInt(request.getParameter("uid")));
    //调用业务逻辑
        Db_CommunityService db_communityService = new Db_CommunityServiceImpl();
        boolean result = false;
        try {
            result = db_communityService.addDb_Community(db_community);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if(result){
            response.getWriter().print("success");
        }else{
            response.getWriter().print("failed");
        }
        //响应结果
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

前端

在前端原有界面的基础上添加一个添加部门的按钮 并且添加一个onclick事件

在事件中使用location.href跳转到一个新的html页面中 在这个页面里调用上边这个servlet

并且在这里写text文本框 name就是servlet的name

//原有界面


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>部门主页</title>
    <style>
        #community{
            text-align: center;
            border-collapse: collapse;
            width: 1500px;
        }

        #community td{
            border: 1px solid black;
        }
    </style>
    <script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
    <script>
        $(function(){
            initCommunity();
        });
        
        function initCommunity() {
            $.ajax({
                url:"findCommunityByAJAX",
                type:"get",
                dataType:"json",
                async:true,

                success:function (jsonData) {
                    setDataToTable(jsonData);
                }
            })
        }

        function setDataToTable(jsonData) {
            var table=$("#community")

            //把表格里的内容删除
            table.empty();

            var th=$("<tr><td>序号</td><td>小区编号</td><td>小区名称</td><td>小区地址</td><td>小区面积</td><td>总栋数</td><td>总户数</td><td>小区图片</td><td>小区绿化率</td><td>开发商名称</td><td>物业名称</td><td>创建时间</td><td>状态</td><td>管理员ID</td><td>操作</td></tr>")
            table.append(th);



            for(var i=0; i<jsonData.length; i++){
                var community =jsonData[i];
                // 创建行
                var tr=$("<tr></tr>");
                table.append(tr);
                //创建列
                var td1=$("<td></td>");
                td1.text(community.id);
                tr.append(td1);

                var td2=$("<td></td>");
                td2.text(community.communityNum);
                tr.append(td2);

                var td3=$("<td></td>");
                td3.text(community.name);
                tr.append(td3);

                var td4=$("<td></td>");
                td4.text(community.address);
                tr.append(td4);

                var td5=$("<td></td>");
                td5.text(community.communityArea);
                tr.append(td5);

                var td6=$("<td></td>");
                td6.text(community.buildingNum);
                tr.append(td6);

                var td7=$("<td></td>");
                td7.text(community.roomNum);
                tr.append(td7);

                var td8=$("<td></td>");
                td8.text(community.img);
                tr.append(td8);

                var td9=$("<td></td>");
                td9.text(community.greeningRate);
                tr.append(td9);

                var td10=$("<td></td>");
                td10.text(community.developerName);
                tr.append(td10);

                var td11=$("<td></td>");
                td11.text(community.propertyName);
                tr.append(td11);

                var td12=$("<td></td>");
                td12.text(community.hiredate);
                tr.append(td12);

                var td13=$("<td></td>");
                td13.text(community.state);
                tr.append(td13);

                var td14=$("<td></td>");
                td14.text(community.uid);
                tr.append(td14);

                var td15=$("<td></td>");
                tr.append(td15);

                var deleteA=$("<a href='#'>删除</a>");
                var editA=$("<a href='#'>修改</a>");


                //解决闭包问题-----删除
                (function (index) {
                    var d=jsonData[index];
                    deleteA.click(function () {
                    //发出ajax请求
                        var result = confirm("确定要删除此条数据吗?")
                       if(result){
                           $.ajax({
                               url: "deleteCommunityByAJAX?id="+d.id,
                               type: "get",
                               //传回的不是数据而是success或者failed
                               dataType: "text",
                               async: true,
                               success:function (result) {
                                   if(result=="success"){
                                       //再次调用查询的方法
                                        initCommunity();
                                   }else{
                                        alert("删除失败!")
                                   }
                               }
                           })
                       }
                    })
                })(i)

                td15.append(deleteA);
                td15.append($(""));
                td15.append(editA);
            }
        }

        //添加部门
       function addCommunity(){
        location.href="adddept.html";
       }
    </script>
</head>
<body>
    <form>
        小区编号<input type="text" name="id"/>
        小区名称<input type="text" name="communityNum"/>
        <input type="button" onclick="queryCommunity()" value="查询"/>
        <input type="button" onclick="addCommunity()" value="添加部门">
    </form>
<hr/>
    <table id="community">
        <tr>

        </tr>
    </table>
</body>
</html>

跳转的新界面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加部门</title>
    <script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
    <script>
        function save(){
        //获取数据,传递给java的servlet
            var data=$("#community").serialize();
        //发出ajax请求,把数据给请求的servlet---service----dao  插入到数据库中
            $.ajax({
                //接收的是servlet的
                url:"addCommunityByAJAX",
                type:"post",
                //表单序列化单独加data
                data:data,
                async:true,
                dataType:"text",
                success:function (meg) {
                //匿名函数接收的是servlet里print的结果
                //meg是servlet里边的
                    if(meg=="success"){
                        location.href="finddept.html";
                    }else{
                        alert("输入错误")
                    }
                }
            })
        }
    </script>
</head>
<body>
    <form id="community">
        <p>部门编号:<input type="text" name="id"/></p>
        <p>小区编号:<input type="text" name="communityNum"/></p>
        <p>小区名称:<input type="text" name="name"/></p>
        <p>小区地址:<input type="text" name="address"/></p>
        <p>小区面积:<input type="text" name="communityArea"/></p>
        <p>总栋数:<input type="text" name="buildingNum"/></p>
        <p>总户数:<input type="text" name="roomNum"></p>
        <p>小区图片:<input type="text" name="img"/></p>
        <p>小区绿化率:<input type="text" name="greeningRate"/></p>
        <p>开发商名称:<input type="text" name="developerName"/></p>
        <p>物业名称:<input type="text" name="propertyName"/></p>
        <p>创建时间:<input type="text" name="hireDate"></p>
        <p>状态:<input type="text" name="state"/></p>
        <p>管理员ID:<input type="text" name="uid"/></p>
        <p><input type="button" value="保存部门" onclick="save()"/></p>
    </form>
</body>
</html>



模糊查询

Dao层


//接口

package com.qf.villagepro.dao;

import com.qf.villagepro.entity.Db_Community;

import java.sql.SQLException;
import java.util.List;

//小区
public interface Db_CommunityDao {
    //添加
    int addDb_Community(Db_Community db_community) throws SQLException;
    //查询
    List<Db_Community> findCommunity() throws SQLException;
    //删除
    int deleteCommunity(int id) throws SQLException;
    
    //模糊查询
    List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException;
}




//具体实现的方法
package com.qf.villagepro.dao.impl;

import com.qf.villagepro.dao.Db_CommunityDao;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.utils.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class Db_CommunityDaoImpl implements Db_CommunityDao {
    private QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
    //添加
    @Override
    public int addDb_Community(Db_Community db_community) throws SQLException {
        String sql="insert into db_community(id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        Object[] params = {db_community.getId(),db_community.getCommunityNum(),
                           db_community.getName(),db_community.getAddress(),
                db_community.getCommunityArea(),db_community.getBuildingNum(),
                db_community.getRoomNum(),db_community.getImg(),
                db_community.getGreeningRate(),db_community.getDeveloperName(),
                db_community.getPropertyName(),db_community.getHiredate(),
                db_community.getState(),db_community.getUid()};
        int result = queryRunner.update(sql,params);
        return result;
    }


    //查询
    @Override
    public List<Db_Community> findCommunity() throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community";

        List<Db_Community> list = null;
        list = queryRunner.query(sql,new BeanListHandler<Db_Community>(Db_Community.class));
        return list;
    }

    //模糊查询
    @Override
    public List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community where communityNum like ? and name like ?";
        return queryRunner.query(sql,new BeanListHandler<Db_Community>(Db_Community.class),db_community.getCommunityNum(),db_community.getName());
    }

    //删除
    @Override
    public int deleteCommunity(int id) throws SQLException {
        String sql = "delete from db_community where id=?";
        return queryRunner.update(sql,id);
    }




}

Service层

//接口
package com.qf.villagepro.service;

import com.qf.villagepro.entity.Db_Community;

import java.sql.SQLException;
import java.util.List;

public interface Db_CommunityService {
    //添加
    boolean addDb_Community(Db_Community db_community) throws SQLException;
    //查询
    List<Db_Community> findCommunity() throws SQLException;
    //模糊查询
    List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException;
    //删除
    boolean deleteCommunity(int id) throws SQLException;
}








//具体实现的方法
package com.qf.villagepro.service.impl;

import com.qf.villagepro.dao.Db_CommunityDao;
import com.qf.villagepro.dao.impl.Db_CommunityDaoImpl;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.service.Db_CommunityService;

import java.sql.SQLException;
import java.util.List;

public class Db_CommunityServiceImpl implements Db_CommunityService {
   private Db_CommunityDao db_communitydao = new Db_CommunityDaoImpl();

    //添加
    @Override
    public boolean addDb_Community(Db_Community db_community) throws SQLException {
        int result = db_communitydao.addDb_Community(db_community);
        if(result == 1){
            return true;
        }else{
            return false;
        }

    }

    //查询
    @Override
    public List<Db_Community> findCommunity() throws SQLException {
        return db_communitydao.findCommunity();
    }

    //模糊查询
    @Override
    public List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException {
        db_community.setCommunityNum("%" + db_community.getCommunityNum() + "%");
        db_community.setName("%" + db_community.getName() + "%");
        return db_communitydao.findCommunityByCondition(db_community);
    }

    //删除
    @Override
    public boolean deleteCommunity(int id) throws SQLException {
    int result = db_communitydao.deleteCommunity(id);
        return result==1;
    }
}

Servlet层

package com.qf.villagepro.servlet;

import com.alibaba.fastjson.JSON;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.service.Db_CommunityService;
import com.qf.villagepro.service.impl.Db_CommunityServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "FindCommunityConditionServlet",value = "/findCommunityConditionByAJAX")
public class FindCommunityConditionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取表单数据
        Db_Community db_community = new Db_Community();
        db_community.setCommunityNum(request.getParameter("communityNum"));
        db_community.setName(request.getParameter("name"));
        //调用业务逻辑
        Db_CommunityService db_communityService = new Db_CommunityServiceImpl();
        List<Db_Community> list = null;
        //调用模糊查询的方法
        try {
            list = db_communityService.findCommunityByCondition(db_community);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        //转换成json
        String json = JSON.toJSONString(list);
        response.getWriter().print(json);
    }
}

前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>部门主页</title>
    <style>
        #community{
            text-align: center;
            border-collapse: collapse;
            width: 1500px;
        }

        #community td{
            border: 1px solid black;
        }
    </style>
    <script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
    <script>
        $(function(){
            initCommunity();
        });
        
        function initCommunity() {
            $.ajax({
                url:"findCommunityByAJAX",
                type:"get",
                dataType:"json",
                async:true,

                success:function (jsonData) {
                    setDataToTable(jsonData);
                }
            })
        }

        function setDataToTable(jsonData) {
            var table=$("#community")

            //把表格里的内容删除
            table.empty();

            var th=$("<tr><td>序号</td><td>小区编号</td><td>小区名称</td><td>小区地址</td><td>小区面积</td><td>总栋数</td><td>总户数</td><td>小区图片</td><td>小区绿化率</td><td>开发商名称</td><td>物业名称</td><td>创建时间</td><td>状态</td><td>管理员ID</td><td>操作</td></tr>")
            table.append(th);



            for(var i=0; i<jsonData.length; i++){
                var community =jsonData[i];
                // 创建行
                var tr=$("<tr></tr>");
                table.append(tr);
                //创建列
                var td1=$("<td></td>");
                td1.text(community.id);
                tr.append(td1);

                var td2=$("<td></td>");
                td2.text(community.communityNum);
                tr.append(td2);

                var td3=$("<td></td>");
                td3.text(community.name);
                tr.append(td3);

                var td4=$("<td></td>");
                td4.text(community.address);
                tr.append(td4);

                var td5=$("<td></td>");
                td5.text(community.communityArea);
                tr.append(td5);

                var td6=$("<td></td>");
                td6.text(community.buildingNum);
                tr.append(td6);

                var td7=$("<td></td>");
                td7.text(community.roomNum);
                tr.append(td7);

                var td8=$("<td></td>");
                td8.text(community.img);
                tr.append(td8);

                var td9=$("<td></td>");
                td9.text(community.greeningRate);
                tr.append(td9);

                var td10=$("<td></td>");
                td10.text(community.developerName);
                tr.append(td10);

                var td11=$("<td></td>");
                td11.text(community.propertyName);
                tr.append(td11);

                var td12=$("<td></td>");
                td12.text(community.hiredate);
                tr.append(td12);

                var td13=$("<td></td>");
                td13.text(community.state);
                tr.append(td13);

                var td14=$("<td></td>");
                td14.text(community.uid);
                tr.append(td14);

                var td15=$("<td></td>");
                tr.append(td15);

                var deleteA=$("<a href='#'>删除</a>");
                var editA=$("<a href='#'>修改</a>");


                //解决闭包问题-----删除
                (function (index) {
                    var d=jsonData[index];
                    deleteA.click(function () {
                    //发出ajax请求
                        var result = confirm("确定要删除此条数据吗?")
                       if(result){
                           $.ajax({
                               url: "deleteCommunityByAJAX?id="+d.id,
                               type: "get",
                               //传回的不是数据而是success或者failed
                               dataType: "text",
                               async: true,
                               success:function (result) {
                                   if(result=="success"){
                                       //再次调用查询的方法
                                        initCommunity();
                                   }else{
                                        alert("删除失败!")
                                   }
                               }
                           })
                       }
                    })
                })(i)

                td15.append(deleteA);
                td15.append($(""));
                td15.append(editA);
            }
        }



        //模糊查询
        function queryCommunity() {
            var condition=$('#formCommunity').serialize();
            $.ajax({

                url:"findCommunityConditionByAJAX?"+condition,
                type:"get",
                dataType:"json",
                success:function (jsonData) {
                    setDataToTable(jsonData);
                }
            })

        }



        //添加部门
       function addCommunity(){
        location.href="adddept.html";
       }
    </script>
</head>
<body>
    <form id="formCommunity">
        小区编号<input type="text" name="communityNum"/>
        小区名称<input type="text" name="name"/>
        <input type="button" onclick="queryCommunity()" value="查询"/>
        <input type="button" onclick="addCommunity()" value="添加部门">
    </form>
<hr/>

    <table id="community">
        <tr>

        </tr>
    </table>

</body>
</html>

修改

修改不同于以上他的dao层要写两个方法,一个是修改语句,一个是针对于修改的查询语句,修改的查询语句只需要找到这个语句的key键就可以,并不用每一个都查,查到之后的目的是用来找到对用的值,通过前端来进行回显,然后修改语句的目的是用来进行修改对应的值,写修改语句的时候除非特殊要求,要不轻易不会修改key键,key键的name那里可以用hidden来将其进行隐藏,让其能显现但是不能修改,写两个servlet先是针对于修改的查询的servlet再是修改的servlet

针对于前端-----就是页面的跳转,通过查询的界面,给修改的按钮添加事件,然后跳转到另一个界面,在这个界面当中我们主要做的调用servlet和响应ajax,第一个写的是针对于修改的查询的servlet,第二个写的是修改的servlet

dao层

//接口


package com.qf.villagepro.dao;

import com.qf.villagepro.entity.Db_Community;

import java.sql.SQLException;
import java.util.List;

//小区
public interface Db_CommunityDao {
    //添加
    int addDb_Community(Db_Community db_community) throws SQLException;
    //查询
    List<Db_Community> findCommunity() throws SQLException;
    //删除
    int deleteCommunity(int id) throws SQLException;

    //修改
    int editCommunity(Db_Community db_community) throws SQLException;
    //针对修改创建的查询---一次修改等于一次查询 + 一次添加
    //只查询一条所以不用List集合接收 只用数据类型接收就可以了
    Db_Community findEditCommunityByNo(int id) throws SQLException;

    //模糊查询
    List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException;
}




//实际调用的方法
package com.qf.villagepro.dao.impl;

import com.qf.villagepro.dao.Db_CommunityDao;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.utils.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class Db_CommunityDaoImpl implements Db_CommunityDao {
    private QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
    //添加
    @Override
    public int addDb_Community(Db_Community db_community) throws SQLException {
        String sql="insert into db_community(id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        Object[] params = {db_community.getId(),db_community.getCommunityNum(),
                           db_community.getName(),db_community.getAddress(),
                db_community.getCommunityArea(),db_community.getBuildingNum(),
                db_community.getRoomNum(),db_community.getImg(),
                db_community.getGreeningRate(),db_community.getDeveloperName(),
                db_community.getPropertyName(),db_community.getHiredate(),
                db_community.getState(),db_community.getUid()};
        int result = queryRunner.update(sql,params);
        return result;
    }


    //查询
    @Override
    public List<Db_Community> findCommunity() throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community";

        List<Db_Community> list = null;
        list = queryRunner.query(sql,new BeanListHandler<Db_Community>(Db_Community.class));
        return list;
    }

    //模糊查询
    @Override
    public List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community where communityNum like ? and name like ?";
        return queryRunner.query(sql,new BeanListHandler<Db_Community>(Db_Community.class),db_community.getCommunityNum(),db_community.getName());
    }

    //删除
    @Override
    public int deleteCommunity(int id) throws SQLException {
        String sql = "delete from db_community where id=?";
        return queryRunner.update(sql,id);
    }

    //修改
    @Override
    public int editCommunity(Db_Community db_community) throws SQLException {
        String sql = "update db_community set communityNum=?,name=?,address=?,communityArea=?,buildingNum=?,roomNum=?,img=?,greeningRate=?,developerName=?,propertyName=?,hiredate=?,state=?,uid=? where id=?";
        Object[] params = {db_community.getCommunityNum(), db_community.getName(),
                db_community.getAddress(),db_community.getCommunityArea(),
                db_community.getBuildingNum(),db_community.getRoomNum(),
                db_community.getImg(),db_community.getGreeningRate(),
                db_community.getDeveloperName(),db_community.getPropertyName(),
                db_community.getHiredate(),db_community.getState(),
                db_community.getUid(),db_community.getId()};
        return queryRunner.update(sql,params);
    }

    //针对于修改创建的查询
    @Override
    public Db_Community findEditCommunityByNo(int id) throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community where id=?";
//        communityId与参数communityId相同
        //因为只修改了一条所以不用BeanList 用BeanHandler
        return queryRunner.query(sql,new BeanHandler<Db_Community>(Db_Community.class),id);
    }


}

service层

//接口
package com.qf.villagepro.service;

import com.qf.villagepro.entity.Db_Community;

import java.sql.SQLException;
import java.util.List;

public interface Db_CommunityService {
    //添加
    boolean addDb_Community(Db_Community db_community) throws SQLException;
    //查询
    List<Db_Community> findCommunity() throws SQLException;
    //模糊查询
    List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException;
    //删除
    boolean deleteCommunity(int id) throws SQLException;
    //修改
    boolean editCommunity(Db_Community db_community) throws SQLException;
    //针对于修改创建的查询
    Db_Community findEditCommunityByNo(int id) throws SQLException;
}




//具体实现的方法
package com.qf.villagepro.service.impl;

import com.qf.villagepro.dao.Db_CommunityDao;
import com.qf.villagepro.dao.impl.Db_CommunityDaoImpl;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.service.Db_CommunityService;

import java.sql.SQLException;
import java.util.List;

public class Db_CommunityServiceImpl implements Db_CommunityService {
   private Db_CommunityDao db_communitydao = new Db_CommunityDaoImpl();

    //添加
    @Override
    public boolean addDb_Community(Db_Community db_community) throws SQLException {
        int result = db_communitydao.addDb_Community(db_community);
        if(result == 1){
            return true;
        }else{
            return false;
        }

    }

    //查询
    @Override
    public List<Db_Community> findCommunity() throws SQLException {
        return db_communitydao.findCommunity();
    }

    //模糊查询
    @Override
    public List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException {
        db_community.setCommunityNum("%" + db_community.getCommunityNum() + "%");
        db_community.setName("%" + db_community.getName() + "%");
        return db_communitydao.findCommunityByCondition(db_community);
    }

    //删除
    @Override
    public boolean deleteCommunity(int id) throws SQLException {
    int result = db_communitydao.deleteCommunity(id);
        return result==1;
    }

    //修改
    @Override
    public boolean editCommunity(Db_Community db_community) throws SQLException {
        int result = db_communitydao.editCommunity(db_community);
        return result==1;
    }

    //针对于修改创建的查询
    @Override
    public Db_Community findEditCommunityByNo(int id) throws SQLException {
        return db_communitydao.findEditCommunityByNo(id);
    }
    
}

Servlet层

package com.qf.villagepro.servlet;

import com.alibaba.fastjson.JSON;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.service.Db_CommunityService;
import com.qf.villagepro.service.impl.Db_CommunityServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;


//针对于修改的查询
@WebServlet(name = "EditCommunityServlet",value = "/EditCommunityServletByAJAX")
public class EditCommunityServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取表单数据
        int id = Integer.parseInt(request.getParameter("id"));
        Db_Community db_community = null;

        //调用业务逻辑
        Db_CommunityService db_communityService = new Db_CommunityServiceImpl();
        try {
            db_community=db_communityService.findEditCommunityByNo(id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        //响应结果
        String json = JSON.toJSONString(db_community);
        response.getWriter().print(json);
    }
}







//修改
package com.qf.villagepro.servlet;

import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.service.Db_CommunityService;
import com.qf.villagepro.service.impl.Db_CommunityServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

//执行的是修改语句
@WebServlet(name = "EditAddCommunityServlet",value = "/EditAddCommunityServletByAJAX")
public class EditAddCommunityServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //获取表单数据
        Db_Community db_community = new Db_Community();

        db_community.setId(Integer.parseInt(request.getParameter("id")));
        db_community.setCommunityNum(request.getParameter("communityNum"));
        db_community.setName(request.getParameter("name"));
        db_community.setAddress(request.getParameter("address"));
        db_community.setCommunityArea(Double.parseDouble(request.getParameter("communityArea")));
        db_community.setBuildingNum(Integer.parseInt(request.getParameter("buildingNum")));
        db_community.setRoomNum(Integer.parseInt(request.getParameter("roomNum")));
        db_community.setImg(request.getParameter("img"));
        db_community.setGreeningRate(Integer.parseInt(request.getParameter("greeningRate")));
        db_community.setDeveloperName(request.getParameter("developerName"));
        db_community.setPropertyName(request.getParameter("propertyName"));
        db_community.setHiredate(request.getParameter("hireDate"));
        db_community.setState(Integer.parseInt(request.getParameter("state")));
        db_community.setUid(Integer.parseInt(request.getParameter("uid")));
    //调用业务逻辑
        Db_CommunityService db_communityService = new Db_CommunityServiceImpl();
        String meg = "";

        try {
            boolean result =db_communityService.editCommunity(db_community);
            if(result){
                meg="success";
            }else{
                meg="failed";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            meg="failed";
        }
        //响应结果
        response.getWriter().print(meg);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>部门主页</title>
    <style>
        #community{
            text-align: center;
            border-collapse: collapse;
            width: 1500px;
        }

        #community td{
            border: 1px solid black;
        }
    </style>
    <script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
    <script>
        $(function(){
            initCommunity();
        });
        
        function initCommunity() {
            $.ajax({
                url:"findCommunityByAJAX",
                type:"get",
                dataType:"json",
                async:true,

                success:function (jsonData) {
                    setDataToTable(jsonData);
                }
            })
        }

        function setDataToTable(jsonData) {
            var table=$("#community")

            //把表格里的内容删除
            table.empty();

            var th=$("<tr><td>序号</td><td>小区编号</td><td>小区名称</td><td>小区地址</td><td>小区面积</td><td>总栋数</td><td>总户数</td><td>小区图片</td><td>小区绿化率</td><td>开发商名称</td><td>物业名称</td><td>创建时间</td><td>状态</td><td>管理员ID</td><td>操作</td></tr>")
            table.append(th);



            for(var i=0; i<jsonData.length; i++){
                var community =jsonData[i];
                // 创建行
                var tr=$("<tr></tr>");
                table.append(tr);
                //创建列
                var td1=$("<td></td>");
                td1.text(community.id);
                tr.append(td1);

                var td2=$("<td></td>");
                td2.text(community.communityNum);
                tr.append(td2);

                var td3=$("<td></td>");
                td3.text(community.name);
                tr.append(td3);

                var td4=$("<td></td>");
                td4.text(community.address);
                tr.append(td4);

                var td5=$("<td></td>");
                td5.text(community.communityArea);
                tr.append(td5);

                var td6=$("<td></td>");
                td6.text(community.buildingNum);
                tr.append(td6);

                var td7=$("<td></td>");
                td7.text(community.roomNum);
                tr.append(td7);

                var td8=$("<td></td>");
                td8.text(community.img);
                tr.append(td8);

                var td9=$("<td></td>");
                td9.text(community.greeningRate);
                tr.append(td9);

                var td10=$("<td></td>");
                td10.text(community.developerName);
                tr.append(td10);

                var td11=$("<td></td>");
                td11.text(community.propertyName);
                tr.append(td11);

                var td12=$("<td></td>");
                td12.text(community.hiredate);
                tr.append(td12);

                var td13=$("<td></td>");
                td13.text(community.state);
                tr.append(td13);

                var td14=$("<td></td>");
                td14.text(community.uid);
                tr.append(td14);

                var td15=$("<td></td>");
                tr.append(td15);

                var deleteA=$("<a href='#'>删除</a>");
                var editA=$("<a href='#'>修改</a>");


                
                
                
                // //给修改按钮添加事件
                // //修改
                (function (index) {
                    var d=jsonData[index];
                    editA.click(function(){
                    location.href="editCommunity.html?id="+d.id;
                    })
                })(i);

                
                
                
                //解决闭包问题-----删除
                (function(index) {
                    var d=jsonData[index];
                    deleteA.click(function(){
                    //发出ajax请求
                        var result = confirm("确定要删除此条数据吗?")
                       if(result){
                           $.ajax({
                               url: "deleteCommunityByAJAX?id="+d.id,
                               type: "get",
                               //传回的不是数据而是success或者failed
                               dataType: "text",
                               async: true,
                               success:function (result) {
                                   if(result=="success"){
                                       //再次调用查询的方法
                                        initCommunity();
                                   }else{
                                        alert("删除失败!");
                                   }
                               }
                           })
                       }
                    })
                })(i)

                td15.append(deleteA);
                td15.append($(""));
                td15.append(editA);
            }
        }



        //模糊查询
        function queryCommunity() {
            var condition=$('#formCommunity').serialize();
            $.ajax({

                url:"findCommunityConditionByAJAX?"+condition,
                type:"get",
                dataType:"json",
                success:function (jsonData) {
                    setDataToTable(jsonData);
                }
            })

        }



        //添加部门
       function addCommunity(){
        location.href="adddept.html";
       }
    </script>
</head>
<body>
    <form id="formCommunity">
        小区编号<input type="text" name="communityNum"/>
        小区名称<input type="text" name="name"/>
        <input type="button" onclick="queryCommunity()" value="查询"/>
        <input type="button" onclick="addCommunity()" value="添加部门">
    </form>
<hr/>

    <table id="community">
        <tr>

        </tr>
    </table>

</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>修改部门信息</title>
    <script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
    <script>

        $(function(){
            initValue();
        });

        function initValue(){
            //获取到主键在url里
            var url=location.href;
            //lastIndexOf()是截取到()里的值的那一位
            //本例指的就是(=)中的=
            //+1是往后移一位
            var id=url.substr(url.lastIndexOf("=")+1);

            //发出ajax请求,根据id,获得对象,然后回显
            $.ajax({
                url:"EditCommunityServletByAJAX?id="+id,
                type:"get",
                //显示对象传json
                dataType:"json",
                success:function (db_community) {
                //回显
                    $("#id").val(db_community.id);
                    $("#communityNum").val(db_community.communityNum);
                    $("#name").val(db_community.name);
                    $("#address").val(db_community.address);
                    $("#communityArea").val(db_community.communityArea);
                    $("#buildingNum").val(db_community.buildingNum);
                    $("#roomNum").val(db_community.roomNum);
                    $("#img").val(db_community.img);
                    $("#greeningRate").val(db_community.greeningRate);
                    $("#developerName").val(db_community.developerName);
                    $("#propertyName").val(db_community.propertyName);
                    $("#hireDate").val(db_community.hireDate);
                    $("#state").val(db_community.state);
                    $("#uid").val(db_community.uid);
                }
            })
        }
    
        function save() {
        //获取表单数据
            var data=$("#community").serialize();
            $.ajax({
                url:"EditAddCommunityServletByAJAX",
                //这里需要用post而不是get
                //get只提交少量数据不安全
                //而且post方式请求数据不需要加?&
                type:"post",
                data:data, //通过data属性,把数据提交到对应的url中
                dataType:"text",
                success:function (result) {
                if(result=="success"){
                    location.href="finddept.html";
                }else{
                    alert("修改部门信息失败!")
                }
                }
            })
        }
    </script>
</head>
<body>
    <form id="community">
        <p>序号:<input type="text" name="id" id="id"/></p>
        <p>小区编号:<input type="text" name="communityNum" id="communityNum"/></p>
        <p>小区名称:<input type="text" name="name" id="name"/></p>
        <p>小区地址:<input type="text" name="address" id="address"/></p>
        <p>小区面积:<input type="text" name="communityArea" id="communityArea"/></p>
        <p>总栋数:<input type="text" name="buildingNum" id="buildingNum"/></p>
        <p>总户数:<input type="text" name="roomNum" id="roomNum"></p>
        <p>小区图片:<input type="text" name="img" id="img"/></p>
        <p>小区绿化率:<input type="text" name="greeningRate" id="greeningRate"/></p>
        <p>开发商名称:<input type="text" name="developerName" id="developerName"/></p>
        <p>物业名称:<input type="text" name="propertyName" id="propertyName"/></p>
        <p>创建时间:<input type="text" name="hireDate" id="hireDate"></p>
        <p>状态:<input type="text" name="state" id="state"/></p>
        <p>管理员ID:<input type="text" name="uid" id="uid"/></p>
        <p><input type="submit" value="保存部门" onclick="save()"/></p>
    </form>
</body>
</html>

分页查询

分页查询要先写分页工具,然后dao层写一个查询的方法与上边的查询不同的是加限制---limit  以及工具是在servlet层调用的,对于前端来说,前端可以把查询取消了,因为有分页查询了就不需要查询了

dao层

//接口
package com.qf.villagepro.dao;

import com.qf.villagepro.entity.Db_Community;

import java.sql.SQLException;
import java.util.List;

//小区
public interface Db_CommunityDao {
    //添加
    int addDb_Community(Db_Community db_community) throws SQLException;
    //查询
    List<Db_Community> findCommunity() throws SQLException;
    //删除
    int deleteCommunity(int id) throws SQLException;

    //修改
    int editCommunity(Db_Community db_community) throws SQLException;
    //针对修改创建的查询---一次修改等于一次查询 + 一次添加
    //只查询一条所以不用List集合接收 只用数据类型接收就可以了
    Db_Community findEditCommunityByNo(int id) throws SQLException;

    //模糊查询
    List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException;

    //分页查询
    //参数一:currentPage  代表当前页
    //参数二:pageSize     代表每页显示的记录数(每页几条)
    List<Db_Community> findCommunityByPage(int currentPage,int pageSize) throws SQLException;
}





//实现的具体方法
package com.qf.villagepro.dao.impl;

import com.qf.villagepro.dao.Db_CommunityDao;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.utils.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class Db_CommunityDaoImpl implements Db_CommunityDao {
    private QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
    //添加
    @Override
    public int addDb_Community(Db_Community db_community) throws SQLException {
        String sql="insert into db_community(id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        Object[] params = {db_community.getId(),db_community.getCommunityNum(),
                           db_community.getName(),db_community.getAddress(),
                db_community.getCommunityArea(),db_community.getBuildingNum(),
                db_community.getRoomNum(),db_community.getImg(),
                db_community.getGreeningRate(),db_community.getDeveloperName(),
                db_community.getPropertyName(),db_community.getHiredate(),
                db_community.getState(),db_community.getUid()};
        int result = queryRunner.update(sql,params);
        return result;
    }


    //查询
    @Override
    public List<Db_Community> findCommunity() throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community";

        List<Db_Community> list = null;
        list = queryRunner.query(sql,new BeanListHandler<Db_Community>(Db_Community.class));
        return list;
    }

    //模糊查询
    @Override
    public List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community where communityNum like ? and name like ?";
        return queryRunner.query(sql,new BeanListHandler<Db_Community>(Db_Community.class),db_community.getCommunityNum(),db_community.getName());
    }


    //删除
    @Override
    public int deleteCommunity(int id) throws SQLException {
        String sql = "delete from db_community where id=?";
        return queryRunner.update(sql,id);
    }

    //修改
    @Override
    public int editCommunity(Db_Community db_community) throws SQLException {
        String sql = "update db_community set communityNum=?,name=?,address=?,communityArea=?,buildingNum=?,roomNum=?,img=?,greeningRate=?,developerName=?,propertyName=?,hiredate=?,state=?,uid=? where id=?";
        Object[] params = {db_community.getCommunityNum(), db_community.getName(),
                db_community.getAddress(),db_community.getCommunityArea(),
                db_community.getBuildingNum(),db_community.getRoomNum(),
                db_community.getImg(),db_community.getGreeningRate(),
                db_community.getDeveloperName(),db_community.getPropertyName(),
                db_community.getHiredate(),db_community.getState(),
                db_community.getUid(),db_community.getId()};
        return queryRunner.update(sql,params);
    }

    //针对于修改创建的查询
    @Override
    public Db_Community findEditCommunityByNo(int id) throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community where id=?";
//        communityId与参数communityId相同
        //因为只修改了一条所以不用BeanList 用BeanHandler
        return queryRunner.query(sql,new BeanHandler<Db_Community>(Db_Community.class),id);
    }


    //分页
    @Override
    //第一个参数是第几页也就是当前页
    //第二个参数是每页多少条数据
    public List<Db_Community> findCommunityByPage(int currentPage, int pageSize) throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community limit ?,?";
        //第一个参数是从哪开始截取 同时就正好可以理解为从第几页开始查询
        //第二个参数是往后查多少个 同时就正好可以理解为每页多少个
        //数组是针对于?使用的
        Object[] ary = {(currentPage-1)*pageSize,pageSize};
        List<Db_Community> list = null;
        //查询的是多条使用的是BeanListHandler
        list = queryRunner.query(sql,new BeanListHandler<Db_Community>(Db_Community.class),ary);
        return list;
    }

}

service层


//接口
package com.qf.villagepro.service;

import com.qf.villagepro.entity.Db_Community;

import java.sql.SQLException;
import java.util.List;

public interface Db_CommunityService {
    //添加
    boolean addDb_Community(Db_Community db_community) throws SQLException;
    //查询
    List<Db_Community> findCommunity() throws SQLException;
    //模糊查询
    List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException;
    //删除
    boolean deleteCommunity(int id) throws SQLException;
    //修改
    boolean editCommunity(Db_Community db_community) throws SQLException;
    //针对于修改创建的查询
    Db_Community findEditCommunityByNo(int id) throws SQLException;
    //分页查询
    List<Db_Community> findCommunityByPage(int currentPage,int pageSize) throws SQLException;
}





//具体实现的方法
package com.qf.villagepro.service.impl;

import com.qf.villagepro.dao.Db_CommunityDao;
import com.qf.villagepro.dao.impl.Db_CommunityDaoImpl;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.service.Db_CommunityService;

import java.sql.SQLException;
import java.util.List;

public class Db_CommunityServiceImpl implements Db_CommunityService {
   private Db_CommunityDao db_communitydao = new Db_CommunityDaoImpl();

    //添加
    @Override
    public boolean addDb_Community(Db_Community db_community) throws SQLException {
        int result = db_communitydao.addDb_Community(db_community);
        if(result == 1){
            return true;
        }else{
            return false;
        }

    }

    //查询
    @Override
    public List<Db_Community> findCommunity() throws SQLException {
        return db_communitydao.findCommunity();
    }

    //模糊查询
    @Override
    public List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException {
        db_community.setCommunityNum("%" + db_community.getCommunityNum() + "%");
        db_community.setName("%" + db_community.getName() + "%");
        return db_communitydao.findCommunityByCondition(db_community);
    }

    //删除
    @Override
    public boolean deleteCommunity(int id) throws SQLException {
    int result = db_communitydao.deleteCommunity(id);
        return result==1;
    }

    //修改
    @Override
    public boolean editCommunity(Db_Community db_community) throws SQLException {
        int result = db_communitydao.editCommunity(db_community);
        return result==1;
    }

    //针对于修改创建的查询
    @Override
    public Db_Community findEditCommunityByNo(int id) throws SQLException {
        return db_communitydao.findEditCommunityByNo(id);
    }

    //分页查询
    @Override
    public List<Db_Community> findCommunityByPage(int currentPage, int pageSize) throws SQLException {
        return db_communitydao.findCommunityByPage(currentPage,pageSize);
    }

}

servlet层

package com.qf.villagepro.servlet;

import com.alibaba.fastjson.JSON;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.service.Db_CommunityService;
import com.qf.villagepro.service.impl.Db_CommunityServiceImpl;
import com.qf.villagepro.utils.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "QueryCommunityByPageServlet",value = "/QueryCommunityByPageAJAX")
public class QueryCommunityByPageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //获取表单数据
    int currentPage=Integer.parseInt(request.getParameter("currentPage"));
    int pageSize=Integer.parseInt(request.getParameter("pageSize"));
    //调用业务逻辑
        Db_CommunityService db_communityService = new Db_CommunityServiceImpl();
        List<Db_Community> list = null;

        try {
            list = db_communityService.findCommunityByPage(currentPage,pageSize);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        //new map 对象
        //第一个是key用来起名
        //第二个是value用来存list
        Map<String,Object> map = new HashMap<String,Object>();
        //存list并给key起名为data
        map.put("data",list);

        try {
            //分了多少页
            int totalPages= PageUtil.getTotalPages("db_community",pageSize,"id");
            //分了多少页也放进map集合里,并起名totalPages
            map.put("totalPages",totalPages);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        //响应结果
        String json = JSON.toJSONString(map);
        response.getWriter().print(json);
    }
}

前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>部门主页</title>
    <style>
        #community{
            text-align: center;
            border-collapse: collapse;
            width: 1500px;
        }

        #community td{
            border: 1px solid black;
        }
    </style>
    <script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
    <script>

        //定义全局变量

        //起始页
        var currentPage=1;
        //每页几条
        var pageSize=3;
        //总页数
        var totalPage;


        //全局显示
        $(function(){
            //分页
            initMain();
            changePage();
        });




        //分页
        function initMain() {
            //发出ajax请求
            $.ajax({
                url:"QueryCommunityByPageAJAX?currentPage="+currentPage+"&pageSize="+pageSize,
                type:"get",
                dataType:"json",
                async:false,
                success:function (jsonData) {
                //给总页数赋值  totalPages是QueryDeptByPageServletAJAX中map集合里的totalPages
                //将后端值的总页数给赋出来
                totalPage=jsonData.totalPages;
                //data指的是key值
                setDataToTable(jsonData.data)
                }
            })
        }

        //分页判断
        function first(a) {
            if(a.innerText=="首页"){
                currentPage=1;
            }else if(a.innerText=="上一页"){
                if(currentPage>1){
                    currentPage--;
                }else{
                    currentPage=1;
                }
            }else if(a.innerText=="下一页"){
                if(currentPage<totalPage){
                    currentPage++;
                }else{
                    currentPage=totalPage;
                }
            }else{
                currentPage=totalPage;
            }
            //继续调映请求响应数据 确保翻页之后也就可以点击
            initMain();
            changePage();
        }



        //改变当前页,总页数
        function changePage() {
            //后去cSpan
            var cSpan=$("#cSpan");
            //给cSpan赋值
            cSpan.text(currentPage);
            var tSpan=$("#tSpan");
            tSpan.text(totalPage);
        }






        


        // //查询
        //有分页查询了就不需要原先的查询了,就可以不需要这个了
        // function initCommunity() {
        //     $.ajax({
        //         url:"findCommunityByAJAX",
        //         type:"get",
        //         dataType:"json",
        //         async:true,
        //
        //         success:function (jsonData) {
        //             setDataToTable(jsonData);
        //         }
        //     })
        // }










        //动态创建表格
        function setDataToTable(jsonData) {
            var table=$("#community")
            //把表格里的内容删除
            table.empty();

            var th=$("<tr><td>序号</td><td>小区编号</td><td>小区名称</td><td>小区地址</td><td>小区面积</td><td>总栋数</td><td>总户数</td><td>小区图片</td><td>小区绿化率</td><td>开发商名称</td><td>物业名称</td><td>创建时间</td><td>状态</td><td>管理员ID</td><td>操作</td></tr>")
            table.append(th);



            for(var i=0; i<jsonData.length; i++){
                var community =jsonData[i];
                // 创建行
                var tr=$("<tr></tr>");
                table.append(tr);
                //创建列
                var td1=$("<td></td>");
                td1.text(community.id);
                tr.append(td1);

                var td2=$("<td></td>");
                td2.text(community.communityNum);
                tr.append(td2);

                var td3=$("<td></td>");
                td3.text(community.name);
                tr.append(td3);

                var td4=$("<td></td>");
                td4.text(community.address);
                tr.append(td4);

                var td5=$("<td></td>");
                td5.text(community.communityArea);
                tr.append(td5);

                var td6=$("<td></td>");
                td6.text(community.buildingNum);
                tr.append(td6);

                var td7=$("<td></td>");
                td7.text(community.roomNum);
                tr.append(td7);

                var td8=$("<td></td>");
                td8.text(community.img);
                tr.append(td8);

                var td9=$("<td></td>");
                td9.text(community.greeningRate);
                tr.append(td9);

                var td10=$("<td></td>");
                td10.text(community.developerName);
                tr.append(td10);

                var td11=$("<td></td>");
                td11.text(community.propertyName);
                tr.append(td11);

                var td12=$("<td></td>");
                td12.text(community.hiredate);
                tr.append(td12);

                var td13=$("<td></td>");
                td13.text(community.state);
                tr.append(td13);

                var td14=$("<td></td>");
                td14.text(community.uid);
                tr.append(td14);

                var td15=$("<td></td>");
                tr.append(td15);

                var deleteA=$("<a href='#'>删除</a>");
                var editA=$("<a href='#'>修改</a>");












                // //给修改按钮添加事件
                // //修改
                (function (index) {
                    var d=jsonData[index];
                    editA.click(function(){
                    location.href="editCommunity.html?id="+d.id;
                    })
                })(i);



                //解决闭包问题-----删除
                (function(index) {
                    var d=jsonData[index];
                    deleteA.click(function(){
                    //发出ajax请求
                        var result = confirm("确定要删除此条数据吗?")
                       if(result){
                           $.ajax({
                               url: "deleteCommunityByAJAX?id="+d.id,
                               type: "get",
                               //传回的不是数据而是success或者failed
                               dataType: "text",
                               async: true,
                               success:function (result) {
                                   if(result=="success"){
                                       //再次调用查询的方法
                                        initCommunity();
                                   }else{
                                        alert("删除失败!");
                                   }
                               }
                           })
                       }
                    })
                })(i)

                
                //创建按钮
                td15.append(deleteA);
                td15.append($(""));
                td15.append(editA);
            }
        }







        //模糊查询
        function queryCommunity() {
            var condition=$('#formCommunity').serialize();
            $.ajax({

                url:"findCommunityConditionByAJAX?"+condition,
                type:"get",
                dataType:"json",
                success:function (jsonData) {
                    setDataToTable(jsonData);
                }
            })

        }











        //添加小区
       function addCommunity(){
        location.href="adddept.html";
       }



    </script>
</head>
<body>
    <form id="formCommunity">
        小区编号<input type="text" name="communityNum"/>
        小区名称<input type="text" name="name"/>
        <input type="button" onclick="queryCommunity()" value="查询"/>
        <input type="button" onclick="addCommunity()" value="添加部门">
    </form>
<hr/>

    <table id="community">
        <tr>

        </tr>
    </table>

    <hr/>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="#" onclick="first(this)">首页</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="#" onclick="first(this)">上一页</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="#" onclick="first(this)">下一页</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="#" onclick="first(this)">末页</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    当前第<span id="cSpan"></span>页/共<span id="tSpan"></span>页&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

</body>
</html>

批量删除

dao层

//接口
package com.qf.villagepro.dao;

import com.qf.villagepro.entity.Db_Community;

import java.sql.SQLException;
import java.util.List;

//小区
public interface Db_CommunityDao {
    //添加
    int addDb_Community(Db_Community db_community) throws SQLException;
    //查询
    List<Db_Community> findCommunity() throws SQLException;
    //删除
    int deleteCommunity(int id) throws SQLException;

    //修改
    int editCommunity(Db_Community db_community) throws SQLException;
    //针对修改创建的查询---一次修改等于一次查询 + 一次添加
    //只查询一条所以不用List集合接收 只用数据类型接收就可以了
    Db_Community findEditCommunityByNo(int id) throws SQLException;

    //模糊查询
    List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException;

    //分页查询
    //参数一:currentPage  代表当前页
    //参数二:pageSize     代表每页显示的记录数(每页几条)
    List<Db_Community> findCommunityByPage(int currentPage,int pageSize) throws SQLException;

    //批量删除
    int deleteCommunityLotsOf(String ids) throws SQLException;
}





//具体实现的方法
package com.qf.villagepro.dao.impl;

import com.qf.villagepro.dao.Db_CommunityDao;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.utils.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class Db_CommunityDaoImpl implements Db_CommunityDao {
    private QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());
    //添加
    @Override
    public int addDb_Community(Db_Community db_community) throws SQLException {
        String sql="insert into db_community(id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        Object[] params = {db_community.getId(),db_community.getCommunityNum(),
                           db_community.getName(),db_community.getAddress(),
                db_community.getCommunityArea(),db_community.getBuildingNum(),
                db_community.getRoomNum(),db_community.getImg(),
                db_community.getGreeningRate(),db_community.getDeveloperName(),
                db_community.getPropertyName(),db_community.getHiredate(),
                db_community.getState(),db_community.getUid()};
        int result = queryRunner.update(sql,params);
        return result;
    }


    //查询
    @Override
    public List<Db_Community> findCommunity() throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community";

        List<Db_Community> list = null;
        list = queryRunner.query(sql,new BeanListHandler<Db_Community>(Db_Community.class));
        return list;
    }

    //模糊查询
    @Override
    public List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community where communityNum like ? and name like ?";
        return queryRunner.query(sql,new BeanListHandler<Db_Community>(Db_Community.class),db_community.getCommunityNum(),db_community.getName());
    }


    //删除
    @Override
    public int deleteCommunity(int id) throws SQLException {
        String sql = "delete from db_community where id=?";
        return queryRunner.update(sql,id);
    }

    //修改
    @Override
    public int editCommunity(Db_Community db_community) throws SQLException {
        String sql = "update db_community set communityNum=?,name=?,address=?,communityArea=?,buildingNum=?,roomNum=?,img=?,greeningRate=?,developerName=?,propertyName=?,hiredate=?,state=?,uid=? where id=?";
        Object[] params = {db_community.getCommunityNum(), db_community.getName(),
                db_community.getAddress(),db_community.getCommunityArea(),
                db_community.getBuildingNum(),db_community.getRoomNum(),
                db_community.getImg(),db_community.getGreeningRate(),
                db_community.getDeveloperName(),db_community.getPropertyName(),
                db_community.getHiredate(),db_community.getState(),
                db_community.getUid(),db_community.getId()};
        return queryRunner.update(sql,params);
    }

    //针对于修改创建的查询
    @Override
    public Db_Community findEditCommunityByNo(int id) throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community where id=?";
//        communityId与参数communityId相同
        //因为只修改了一条所以不用BeanList 用BeanHandler
        return queryRunner.query(sql,new BeanHandler<Db_Community>(Db_Community.class),id);
    }


    //分页
    @Override
    //第一个参数是第几页也就是当前页
    //第二个参数是每页多少条数据
    public List<Db_Community> findCommunityByPage(int currentPage, int pageSize) throws SQLException {
        String sql = "select id,communityNum,name,address,communityArea,buildingNum,roomNum,img,greeningRate,developerName,propertyName,hiredate,state,uid from db_community limit ?,?";
        //第一个参数是从哪开始截取 同时就正好可以理解为从第几页开始查询
        //第二个参数是往后查多少个 同时就正好可以理解为每页多少个
        //数组是针对于?使用的
        Object[] ary = {(currentPage-1)*pageSize,pageSize};
        List<Db_Community> list = null;
        //查询的是多条使用的是BeanListHandler
        list = queryRunner.query(sql,new BeanListHandler<Db_Community>(Db_Community.class),ary);
        return list;
    }

    //批量删除
    @Override
    public int deleteCommunityLotsOf(String ids) throws SQLException {
        String sql="delete from db_community where id in " +ids;
        return queryRunner.update(sql);
    }



}

service层

//接口
package com.qf.villagepro.service;

import com.qf.villagepro.entity.Db_Community;

import java.sql.SQLException;
import java.util.List;

public interface Db_CommunityService {
    //添加
    boolean addDb_Community(Db_Community db_community) throws SQLException;
    //查询
    List<Db_Community> findCommunity() throws SQLException;
    //模糊查询
    List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException;
    //删除
    boolean deleteCommunity(int id) throws SQLException;
    //修改
    boolean editCommunity(Db_Community db_community) throws SQLException;
    //针对于修改创建的查询
    Db_Community findEditCommunityByNo(int id) throws SQLException;
    //分页查询
    List<Db_Community> findCommunityByPage(int currentPage,int pageSize) throws SQLException;
    //批量删除
    boolean deleteCommunityLotsOf(String ids) throws SQLException;
}






//具体实现的方法
package com.qf.villagepro.service.impl;

import com.qf.villagepro.dao.Db_CommunityDao;
import com.qf.villagepro.dao.impl.Db_CommunityDaoImpl;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.service.Db_CommunityService;

import java.sql.SQLException;
import java.util.List;

public class Db_CommunityServiceImpl implements Db_CommunityService {
   private Db_CommunityDao db_communitydao = new Db_CommunityDaoImpl();

    //添加
    @Override
    public boolean addDb_Community(Db_Community db_community) throws SQLException {
        int result = db_communitydao.addDb_Community(db_community);
        if(result == 1){
            return true;
        }else{
            return false;
        }

    }

    //查询
    @Override
    public List<Db_Community> findCommunity() throws SQLException {
        return db_communitydao.findCommunity();
    }

    //模糊查询
    @Override
    public List<Db_Community> findCommunityByCondition(Db_Community db_community) throws SQLException {
        db_community.setCommunityNum("%" + db_community.getCommunityNum() + "%");
        db_community.setName("%" + db_community.getName() + "%");
        return db_communitydao.findCommunityByCondition(db_community);
    }

    //删除
    @Override
    public boolean deleteCommunity(int id) throws SQLException {
    int result = db_communitydao.deleteCommunity(id);
        return result==1;
    }

    //修改
    @Override
    public boolean editCommunity(Db_Community db_community) throws SQLException {
        int result = db_communitydao.editCommunity(db_community);
        return result==1;
    }

    //针对于修改创建的查询
    @Override
    public Db_Community findEditCommunityByNo(int id) throws SQLException {
        return db_communitydao.findEditCommunityByNo(id);
    }

    //分页查询
    @Override
    public List<Db_Community> findCommunityByPage(int currentPage, int pageSize) throws SQLException {
        return db_communitydao.findCommunityByPage(currentPage,pageSize);
    }

    //批量删除
    @Override
    public boolean deleteCommunityLotsOf(String ids) throws SQLException {
        ids="("+ids+")";
        //影响了几行,也就是删除了几行
        int result=db_communitydao.deleteCommunityLotsOf(ids);
        //给ids进行分割按照,进行分割---split是分割
        String[] ary = ids.split(",");
        //影响几行和按,分割之后的行相等证明数对上了,就能删
        return result==ary.length;
    }

}

servlet层

package com.qf.villagepro.servlet;

import com.qf.villagepro.service.Db_CommunityService;
import com.qf.villagepro.service.impl.Db_CommunityServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "BulkDeleteCommunityServlet",value = "/bulkDeleteCommunity")
public class BulkDeleteCommunityServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //获取要删除的数据
        String ids=request.getParameter("communitys");
        Db_CommunityService db_communityService = new Db_CommunityServiceImpl();
        boolean result = false;
        try {
            result=db_communityService.deleteCommunityLotsOf(ids);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        if(result){
            response.getWriter().print("success");
        }else{
            response.getWriter().print("failed");
        }
    }
}

前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>小区主页</title>
    <style>
        #community{
            text-align: center;
            border-collapse: collapse;
            width: 1500px;
        }

        #community td{
            border: 1px solid black;
        }
    </style>
    <script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" type="text/javascript" charset="utf-8">
        //CDN引入,加速
    </script>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
    <script>



        //定义全局变量

        //起始页
        var currentPage=1;
        //每页几条
        var pageSize=3;
        //总页数
        var totalPage;


        //全局显示
        $(function(){
            //分页
            initMain();
            changePage();
        });




        //分页
        function initMain() {
            //发出ajax请求
            $.ajax({
                url:"QueryCommunityByPageAJAX?currentPage="+currentPage+"&pageSize="+pageSize,
                type:"get",
                dataType:"json",
                async:false,
                success:function (jsonData) {
                //给总页数赋值  totalPages是QueryDeptByPageServletAJAX中map集合里的totalPages
                //将后端值的总页数给赋出来
                totalPage=jsonData.totalPages;
                //data指的是key值
                setDataToTable(jsonData.data)
                }
            })
        }

        //分页判断
        function first(a) {
            if(a.innerText=="首页"){
                currentPage=1;
            }else if(a.innerText=="上一页"){
                if(currentPage>1){
                    currentPage--;
                }else{
                    currentPage=1;
                }
            }else if(a.innerText=="下一页"){
                if(currentPage<totalPage){
                    currentPage++;
                }else{
                    currentPage=totalPage;
                }
            }else{
                currentPage=totalPage;
            }
            //继续调映请求响应数据 确保翻页之后也就可以点击
            initMain();
            changePage();
        }



        //改变当前页,总页数
        function changePage() {
            //后去cSpan
            var cSpan=$("#cSpan");
            //给cSpan赋值
            cSpan.text(currentPage);
            var tSpan=$("#tSpan");
            tSpan.text(totalPage);
        }









        // //查询
        //有分页查询了就不需要原先的查询了,就可以不需要这个了
        // function initCommunity() {
        //     $.ajax({
        //         url:"findCommunityByAJAX",
        //         type:"get",
        //         dataType:"json",
        //         async:true,
        //
        //         success:function (jsonData) {
        //             setDataToTable(jsonData);
        //         }
        //     })
        // }










        //动态创建表格
        function setDataToTable(jsonData) {
            var table=$("#community")
            //把表格里的内容删除
            table.empty();

            var th=$("<tr><td><input type='checkbox' name='ckall' onclick='checkall(this)'/>全选</td><td>序号</td><td>小区编号</td><td>小区名称</td><td>小区地址</td><td>小区面积</td><td>总栋数</td><td>总户数</td><td>小区图片</td><td>小区绿化率</td><td>开发商名称</td><td>物业名称</td><td>创建时间</td><td>状态</td><td>管理员ID</td><td>操作</td></tr>")
            table.append(th);



            for(var i=0; i<jsonData.length; i++){
                var community =jsonData[i];
                // 创建行
                var tr=$("<tr></tr>");
                table.append(tr);
                //创建列

                var td1=$("<td></td>");
                var ck=$("<input type='checkbox' name='ck'/>");
                //给上边的语句绑定value值,为了点击删除的时候能够删除点击的
                ck.val(community.id);

                td1.append(ck);
                tr.append(td1);

                var td2=$("<td></td>");
                td2.text(community.id);
                tr.append(td2);

                var td3=$("<td></td>");
                td3.text(community.communityNum);
                tr.append(td3);

                var td4=$("<td></td>");
                td4.text(community.name);
                tr.append(td4);

                var td5=$("<td></td>");
                td5.text(community.address);
                tr.append(td5);

                var td6=$("<td></td>");
                td6.text(community.communityArea);
                tr.append(td6);

                var td7=$("<td></td>");
                td7.text(community.buildingNum);
                tr.append(td7);

                var td8=$("<td></td>");
                td8.text(community.roomNum);
                tr.append(td8);

                var td9=$("<td></td>");
                td9.text(community.img);
                tr.append(td9);

                var td10=$("<td></td>");
                td10.text(community.greeningRate);
                tr.append(td10);

                var td11=$("<td></td>");
                td11.text(community.developerName);
                tr.append(td11);

                var td12=$("<td></td>");
                td12.text(community.propertyName);
                tr.append(td12);

                var td13=$("<td></td>");
                td13.text(community.hiredate);
                tr.append(td13);

                var td14=$("<td></td>");
                td14.text(community.state);
                tr.append(td14);

                var td15=$("<td></td>");
                td15.text(community.uid);
                tr.append(td15);

                var td16=$("<td></td>");
                tr.append(td16);

                var deleteA=$("<a href='#'>删除</a>");
                var editA=$("<a href='#'>修改</a>");












                // //给修改按钮添加事件
                // //修改
                (function (index) {
                    var d=jsonData[index];
                    editA.click(function(){
                    location.href="editCommunity.html?id="+d.id;
                    })
                })(i);



                //解决闭包问题-----删除
                (function(index) {
                    var d=jsonData[index];
                    deleteA.click(function(){
                    //发出ajax请求
                        var result = confirm("确定要删除此条数据吗?")
                       if(result){
                           $.ajax({
                               url: "deleteCommunityByAJAX?id="+d.id,
                               type: "get",
                               //传回的不是数据而是success或者failed
                               dataType: "text",
                               async: true,
                               success:function (result) {
                                   if(result=="success"){
                                       //再次调用查询的方法
                                        initMain();
                                   }else{
                                        alert("删除失败!");
                                   }
                               }
                           })
                       }
                    })
                })(i)


                //创建按钮
                td16.append(deleteA);
                td16.append($(""));
                td16.append(editA);
            }
        }







        //模糊查询
        function queryCommunity() {
            var condition=$('#formCommunity').serialize();
            $.ajax({

                url:"findCommunityConditionByAJAX?"+condition,
                type:"get",
                dataType:"json",
                success:function (jsonData) {
                    setDataToTable(jsonData);
                }
            })

        }







        //添加小区
       function addCommunity(){
        location.href="adddept.html";
       }





       //批--量--删--除

        //全选功能
        //ckall是全选的那个按钮的名字
        //checkall是这个按钮添加的事件
        function checkall(ckall) {
            //获得的名字是每一次循环生成的最前边的那个按钮
            var aryCheckBox=document.getElementsByName("ck");
            //因为获取到的是ck所以肯定是一个数组
            for(var i=0; i<aryCheckBox.length; i++){
                aryCheckBox[i].checked=ckall.checked;
            }
        }



        //批量删除
        function bulkDelete() {
            //判断用户是否选择了要删除的数据
            //获取所有复选框,判断谁被选中,获取谁的value值
            //10,30,40
            //加""是为了不出现undefined
            var communitys="";
            //获取ck
            var ary=document.getElementsByName("ck");
            for(var i=0; i<ary.length; i++){
                if(ary[i].checked==true){
                    communitys=communitys+ary[i].value+",";
                }
            }
            if(communitys.length==0){
                alert("请选择要删除的数据");
            }else{
                var result=confirm("确定要删除选中的数据吗?");
                if(result==true){
                 //lastIndexOf() 方法可返回一个指定的字符串值最后出现的位置,
                 // 在一个字符串中的指定位置从后向前搜索
                 //j代表的是最后一个,之前的那一位的索引,因为有,所以假如点3个 1,3,4,  那么j就是5
                    var j=communitys.lastIndexOf(",");

                    //从0开始截取,截取到j的位置----消除,号
                    communitys=communitys.substr(0,j);
                    //得到的值用来当id  SQL中的删除语句,delete from where in()括号里的id就是communitys
                    // alert(communitys);

                    //AJAX请求删除
                    $.ajax({
                        url:"bulkDeleteCommunity?communitys="+communitys,
                        type:"get",
                        dataType:"text",
                        success:function (result) {
                            if(result=="success"){
                                initMain();
                                alert("删除部门成功!")
                            }else{
                                alert("删除部门失败!");
                            }
                        }
                    })
                }
            }
        }







    </script>
</head>
<body>
    <form id="formCommunity">
        小区编号<input type="text" name="communityNum"/>
        小区名称<input type="text" name="name"/>
        <input type="button" onclick="queryCommunity()" value="查询"/>
        <input type="button" onclick="addCommunity()" value="添加部门">
        <input type="button" value="批量删除" onclick="bulkDelete()"/>
    </form>

<hr/>

    <table id="community">
        <tr>

        </tr>
    </table>

    <hr/>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="#" onclick="first(this)">首页</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="#" onclick="first(this)">上一页</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="#" onclick="first(this)">下一页</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="#" onclick="first(this)">末页</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    当前第<span id="cSpan"></span>页/共<span id="tSpan"></span>页&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

</body>
</html>

文件上传与下载

单文件上传

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="bootstrap-3.4.1-dist/css/bootstrap-theme.css" />
    <link rel="stylesheet" href="bootstrap-3.4.1-dist/css/bootstrap-theme.min.css" />
    <link rel="stylesheet" href="bootstrap-3.4.1-dist/css/bootstrap.css" />
    <link rel="stylesheet" href="bootstrap-3.4.1-dist/css/bootstrap.min.css" />
    <script type="text/javascript" src="bootstrap-3.4.1-dist/js/jquery-3.4.1.min.js" ></script>
    <script type="text/javascript" src="bootstrap-3.4.1-dist/js/bootstrap.js" ></script>
    <script type="text/javascript" src="bootstrap-3.4.1-dist/js/bootstrap.min.js" ></script>
    <!--<script type="text/javascript" src="bootstrap-3.4.1-dist/js/npm.js" ></script>-->
    <script type="text/javascript" src="bootstrap-3.4.1-dist/js/bootstrap-dropdown.js" ></script>
        <style>
            .mybox{
                padding: 50px;
                width: 400px;
                margin: 0 auto;
            }
        </style>
</head>
<body>
<div class="container mybox">
<!--    method必须是post  enctype必须是multipart/form-data-->
    <form class="form-horizontal" method="post" enctype="multipart/form-data" action="addcom2">

        <div class="form-group">
            <label for="admin">管理员</label>
            <input type="text" id="admin" class="form-control" />
        </div>

        <div class="form-group">
            <label for="name">小区名称</label>
            <input type="password" id="name" class="form-control" />
        </div>

        <div class="form-group">
            <label for="location">小区位置</label>
            <input type="password" id="location" class="form-control" />
        </div>

        <div class="form-group">
            <label for="img">小区缩略图</label>
<!--            第三要素 type必须是file-->
            <input type="file" id="img" name="img" class="form-control">

        </div>

        <button class="btn btn-primary">保存小区信息</button>
    </form>
</div>
</body>
</html>

servlet

package com.qf.property.servlets;

import com.qf.property.pojo.Community;
import com.qf.property.utils.UploadUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet(name = "AddComServlet2",value = "/addcom2")
//针对于上传文件的注解 byte*kb*mb  前者是上传的大小是多少  后者是下载的大小是多少
@MultipartConfig(maxFileSize = 1024*1024*100,maxRequestSize = 1024*1024*100)
public class AddComServlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part part = request.getPart("img");
        //源文件名
        String fileName = part.getSubmittedFileName();
        //文件名
        String newName = "";
        //创建对象
        Community community = new Community();
        if(fileName!=null){
            //调用工具得到新文件的名字
            newName = UploadUtils.newFileName(fileName);
            //赋文件名
            community.setImg(newName);
            //准备路径问题
            String path = request.getServletContext().getRealPath("/coming");
            //得到新的路径
            //参数一是一级路径
            //参数二是原文件名
            String newPath = UploadUtils.newFilePath(path,fileName);
            //测试输出
            System.out.println("新文件名" + newName);
            System.out.println("新路径" + newPath);
            //进行文件上传
            part.write(newPath+"\\"+newName);
            response.getWriter().write("文件上传成功");
        }
            //其他标签,就不是file的文件标签了
            String admin = request.getParameter("admin");
            String name = request.getParameter("name");
            String  loc = request.getParameter("loc");
            community.setAdmin(admin);
            community.setName(name);
            community.setLocation(loc);

    }
    //调用业务逻辑

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

多文件上传

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>多文件上传</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="multiservlet">
    <p>文件1:<input type="file" name="file1"/></p>
    <p>文件2:<input type="file" name="file2"/></p>
    <p>文件3:<input type="file" name="file3"/></p>
    <input type="submit" value="多文件上传"/>
</form>
</body>
</html>

servlet

package com.qf.property.servlets;

import com.qf.property.utils.UploadUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;

@WebServlet(name = "MultiServlet",value = "/multiservlet")
@MultipartConfig(maxFileSize = 1024*1024*300,maxRequestSize = 1024*1024*300)
public class MultiServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //路径
        String path= request.getServletContext().getRealPath("/comimg");
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        //多文件上传-----获取到了多个附件
        Collection<Part> parts = request.getParts();
        //不为空证明有附件
        if (parts!=null){
            //挨个上传
            for(Part part:parts){
                //获取文件的名字
                String fileName=part.getSubmittedFileName();
                //通过判断是否获取到文件名能够知道当前标签是普通标签还是文件上传的标签
                if(fileName!=null){
                    //说明是文件标签  type="file"
                    if(fileName.trim().equals("")){
                        continue;
                    }
                    //获取新的文件名
                    String newName= UploadUtils.newFileName(fileName);
                    //获取到新的路径
                    String newPath=UploadUtils.newFilePath(path,fileName);
                    //存储
                    part.write(newPath+"\\"+newName);
                    System.out.println(fileName+"上传成功");
                }else{

                }

            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

文件下载-----文件先上传才能下载

jsp----写前端下载界面

<%--
  Created by IntelliJ IDEA.
  User: poison
  Date: 2022/3/22
  Time: 15:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>文件列表</title>
    <style>
            table{
                width: 600px;
                border-collapse: collapse;
                text-align: center;
            }
            td{
                border: 1px solid black;
            }
    </style>
</head>
<body>
<h1>文件下载列表</h1>
<table>
    <tr>
        <td>文件名</td>
        <td>操作</td>
    </tr>
<%--    一个entry是一个键值对--%>
    <c:forEach items="${map}" var="entry">
        <tr>
            <td>${entry.value}</td>
            <td>
                <a href="downfile?filename=${entry.key}">下载</a>
            </td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

servlet

package com.qf.property.servlets;

import com.qf.property.utils.UploadUtils;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet(name = "DownImgServlet",value = "/downfile")
public class DownImgServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //完成下载功能
        //文件的根目录
        String path=request.getServletContext().getRealPath("/comimg");
        //获取要下载的文件名
        //filename是前端下载那里?后边的
        String fileName=request.getParameter("filename");
        //获取原文件名为了找路径
        //split是分割
        String realName=fileName.split("_")[1];
        //找图片的存储路径
        String realPath = UploadUtils.newFilePath(path,realName);


        //设置响应头信息,告知浏览器如何处理流,下载,另存信息----文件下载特有
        response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));

        //1、先按路径读取到文件
        FileInputStream fileInputStream = new FileInputStream(realPath+"/"+fileName);
        //2、把读取到的文件输出到客户端
        ServletOutputStream servletOutputStream=response.getOutputStream();
        byte[] buf = new byte[1024*4];
        int len=0;
        while((len=fileInputStream.read(buf))!=-1){
            servletOutputStream.write(buf,0,len);
        }
        //关闭资源
        servletOutputStream.close();
        fileInputStream.getChannel();
    }
}

baseServlet版本及多表联合查询

Dao

//接口
package com.qf.villagepro.dao;

import com.qf.villagepro.entity.Db_Building;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

//楼栋
public interface Db_BuildingDao {
    //分页查询
    List<Map<String,Object>> BuildByPage(int currentPage, int pageSize) throws SQLException;
    //删除
    int deleteBuildById(int id) throws SQLException;
    //批量删除
    int deleteBuildLotsOf(String ids) throws SQLException;
    //修改
    int editBuild(Db_Building db_building) throws SQLException;
    //针对于修改的查询
    Map<String, Object> findEditBuild(int id) throws SQLException;
    //添加
    int addBuild(Db_Building db_building) throws SQLException;
    //模糊查询

}



//具体实现的方法
package com.qf.villagepro.dao.impl;

import com.qf.villagepro.dao.Db_BuildingDao;
import com.qf.villagepro.entity.Db_Building;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.utils.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class Db_BuildingDaoImpl implements Db_BuildingDao {
    QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());

    //分页查询
    @Override
    public List<Map<String, Object>> BuildByPage(int currentPage, int pageSize) throws SQLException {
        String sql = "select b.id,c.name as cname,b.buildingNum,b.name,b.roomNum,b.buildingDesc,b.buildHiredata,b.cid from db_building as b INNER JOIN db_community as c on b.cid = c.id limit ?,?";
        Object[] ary = {(currentPage-1)*pageSize,pageSize};
        return queryRunner.query(sql,new MapListHandler(),ary);
    }

    //删除
    @Override
    public int deleteBuildById(int id) throws SQLException {
        String sql = "delete from db_building where id=?";
        return queryRunner.update(sql,id);
    }

    //批量删除
    @Override
    public int deleteBuildLotsOf(String ids) throws SQLException {
        String sql="delete from db_building where id in " +ids;
        return queryRunner.update(sql);
    }

    //修改
    @Override
    public int editBuild(Db_Building db_building) throws SQLException {
        String sql="updata db_building set buildingNum=?,name=?,roomNum=?,buildingDesc = ?,buildHiredate = ?,cid = ? where id = ? ";
        Object[] params = {db_building.getBuildingNum(),db_building.getName(),
                            db_building.getRoomNum(),db_building.getBuildingDesc(),
                            db_building.getBuildHiredata(),db_building.getCid(),
                            db_building.getId()};
        return queryRunner.update(sql,params);
    }

    //针对于修改的查询
    @Override
    public Map<String, Object> findEditBuild(int id) throws SQLException {
        String sql = "select b.id,c.name as cname,b.buildingNum,b.name,b.roomNum,b.buildingDesc,b.buildHiredata,b.cid from db_building as b INNER JOIN db_community as c on b.cid = c.id where b.id = ?";
        return queryRunner.query(sql, new MapHandler(), id);
    }

    //添加
    @Override
    public int addBuild(Db_Building db_building) throws SQLException {
        String sql = "insert into db_building(id,buildingNum,name,roomNum,buildingDesc,buildHiredate,cid) values (?,?,?,?,?,?,?)";
        Object[] params = {db_building.getId(),db_building.getBuildingNum(),
                db_building.getName(), db_building.getRoomNum(),
                db_building.getBuildingDesc(), db_building.getBuildHiredata(),db_building.getCid()};
        return queryRunner.update(sql,params);
    }


}

service层

//接口
package com.qf.villagepro.service;


import com.qf.villagepro.entity.Db_Building;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public interface Db_BuildingService {

    //分页查询
    List<Map<String,Object>> BuildByPage(int currentPage, int pageSize) throws SQLException;
    //删除
    boolean deleteBuildById(int id) throws SQLException;
    //批量删除
    boolean deleteBuildLotsOf(String ids) throws SQLException;
    //修改
    boolean editBuild(Db_Building db_building) throws SQLException;
    //针对于修改的查询
    Map<String, Object> findEditBuild(int id) throws SQLException;
    //添加
    boolean addBuild(Db_Building db_building) throws SQLException;
}


//具体实现的方法
package com.qf.villagepro.service.impl;



import com.qf.villagepro.dao.Db_BuildingDao;
import com.qf.villagepro.dao.impl.Db_BuildingDaoImpl;
import com.qf.villagepro.entity.Db_Building;
import com.qf.villagepro.service.Db_BuildingService;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class Db_BuildingServiceImpl implements Db_BuildingService {
    Db_BuildingDao db_buildingDao = new Db_BuildingDaoImpl();
    //分页查询
    @Override
    public List<Map<String, Object>> BuildByPage(int currentPage, int pageSize) throws SQLException {
        //透传
        return db_buildingDao.BuildByPage(currentPage, pageSize);
    }

    //删除
    @Override
    public boolean deleteBuildById(int id) throws SQLException {
        int result = db_buildingDao.deleteBuildById(id);
        return result==1;
    }

    //批量删除
    @Override
    public boolean deleteBuildLotsOf(String ids) throws SQLException {
        ids="("+ids+")";
        //影响了几行,也就是删除了几行
        int result=db_buildingDao.deleteBuildLotsOf(ids);
        //给ids进行分割按照,进行分割---split是分割
        String[] ary = ids.split(",");
        //影响几行和按,分割之后的行相等证明数对上了,就能删
        return result==ary.length;

    }

    //修改
    @Override
    public boolean editBuild(Db_Building db_building) throws SQLException {
        int result = db_buildingDao.editBuild(db_building);
        return result==1;
    }

    //针对于修改的查询
    @Override
    public Map<String, Object> findEditBuild(int id) throws SQLException {
        return db_buildingDao.findEditBuild(id);
    }

    //添加
    @Override
    public boolean addBuild(Db_Building db_building) throws SQLException {
        int result = db_buildingDao.addBuild(db_building);
        if(result == 1){
            return true;
        }else {
            return false;
        }
    }
}

baseServlet层

baseServlet

package com.qf.villagepro.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//不能用来做具体请求,不用下边这个
//@WebServlet(name = "BaseServlet")
public class BaseServlet extends HttpServlet {
    //重写service方法
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //1、获取用户请求的方法是什么,要调用什么方法,通过action传过来、
        //不是指get/post方法 而是指具体调用的方法

        //标记
        String method=req.getParameter("action");


        //2、判断是否获取到方法
        if(method==null && method.equals("")){
            //这里是没获取到时的解决办法
            //执行默认操作
            resp.sendRedirect("index.jsp");
        }


        //3、通过反射获取对应的方法
        //如果有子类获取到的是子类对象
        Class clazz = this.getClass();

        //getMethod是获取某个方法
        //调用的方法一定有request类型和response类型
        try {
            //通过反射获取到子类中用户调用的方法
            Method method1 = clazz.getMethod(method,HttpServletRequest.class,HttpServletResponse.class);
            //通过反射调用此方法
            //forward:index.jsp   ---  转发
            //redirect:index.jsp  ---  重定向
            //json   --- ajax
            Object result=method1.invoke(this,req,resp);
            //对调用结果进行响应
            if(result!=null){
                String str=result.toString();
                //判断结果是哪一种
                //startsWith---以....开头
                if(str.startsWith("forward:")){
                    //转发
                    //substring---截取--- +1代表从冒号后边开始截取
                    String path=str.substring(str.indexOf(":")+1);
                    req.getRequestDispatcher(path).forward(req,resp);
                }else if(str.startsWith("redirect:")){
                    //重定向
                    String path=str.substring(str.indexOf(":")+1);
                    resp.sendRedirect(path);
                }else{
                    //不是转发和重定向只能是json
                    //响应数据
                    //也可以判断是普通字符串还是json字符串-----这里没写
                    resp.getWriter().print(str);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

servlet

package com.qf.villagepro.servlet;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.qf.villagepro.entity.Db_Building;
import com.qf.villagepro.entity.Db_Community;
import com.qf.villagepro.service.Db_BuildingService;
import com.qf.villagepro.service.Db_CommunityService;
import com.qf.villagepro.service.impl.Db_BuildingServiceImpl;
import com.qf.villagepro.service.impl.Db_CommunityServiceImpl;
import com.qf.villagepro.utils.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "BuildServlet",value = "/build")
public class BuildServlet extends BaseServlet {
    Db_BuildingService db_buildingService = new Db_BuildingServiceImpl();

    //分页查询
    public String findBuildPage(HttpServletRequest request, HttpServletResponse response) {
        //获取表单数据
        int currentPage = Integer.parseInt(request.getParameter("currentPage"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));

        //调用业务逻辑

        List<Map<String, Object>> list = null;
        int totalPages = 0;
        try {
            list = db_buildingService.BuildByPage(currentPage, pageSize);
            totalPages = PageUtil.getTotalPages("db_building", pageSize, "id");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("building", list);
        map.put("totalPage", totalPages);
        //响应结果
        String json = JSON.toJSONString(map);

        return json;
    }


    //删除
    public String deleteBuildById(HttpServletRequest request, HttpServletResponse response) {
        //获取表单数据
        int deleteId = Integer.parseInt(request.getParameter("id"));

        //调用业务逻辑
        String meg = "";
        try {
            boolean result = db_buildingService.deleteBuildById(deleteId);
            if (result) {
                meg = "success";
            } else {
                meg = "failed";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            meg = "failed";
        }
        //转成json
        return JSON.toJSONString(meg);
    }


    //批量删除
    public String deleteBuildLotsOf(HttpServletRequest request, HttpServletResponse response) {

        //获取表单数据
        String deleteIds = request.getParameter("ids");
        //调用业务逻辑
        String meg="";
        boolean result=false;
        try {
            result = db_buildingService.deleteBuildLotsOf(deleteIds);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        //响应结果
        if(result){
            meg="success";
            return JSON.toJSONString(meg);
        }else{
            meg="failed";
            return JSON.toJSONString(meg);
        }

    }

    //修改
    public String editBuild(HttpServletRequest request, HttpServletResponse response) {

        //获取表单数据
        Db_Building db_building = new Db_Building();

        db_building.setId(Integer.parseInt(request.getParameter("id")));
        db_building.setBuildingNum(request.getParameter("buildingNum"));
        db_building.setName(request.getParameter("name"));
        db_building.setRoomNum(Integer.parseInt(request.getParameter("roomNum")));
        db_building.setBuildingDesc(request.getParameter("buildingDesc"));
        db_building.setBuildHiredata(request.getParameter("buildingHiredata"));
        db_building.setCid(Integer.parseInt(request.getParameter("cid")));
        //调用业务逻辑
        String meg = "";
        boolean result = false;
        try {
            result = db_buildingService.editBuild(db_building);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        //响应结果
        if(result){
            meg = "success";
            return  JSON.toJSONString(meg);
        }else{
            meg = "failed";
            return JSON.toJSONString(meg);
        }
    }

    //针对于修改的查询
    public String findEditBuild(HttpServletRequest request, HttpServletResponse response) {
        //获取表单数据
        int id = Integer.parseInt(request.getParameter("id"));

        //调用业务逻辑
        Map<String, Object> map = null;
        try {
            map = db_buildingService.findEditBuild(id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        //响应结果
        return JSON.toJSONString(map);
    }

    //添加
    public String addBuild(HttpServletRequest request, HttpServletResponse response) {

        //获取表单数据
        Db_Building db_building = new Db_Building();

        db_building.setId(Integer.parseInt(request.getParameter("id")));
        db_building.setBuildingNum(request.getParameter("buildingNum"));
        db_building.setName(request.getParameter("name"));
        db_building.setRoomNum(Integer.parseInt(request.getParameter("roomNum")));
        db_building.setBuildingDesc(request.getParameter("buildingDesc"));
        db_building.setBuildHiredata(request.getParameter("buildingHiredata"));
        db_building.setCid(Integer.parseInt(request.getParameter("cid")));

        //调用业务逻辑
        boolean result = false;
        String meg="";
        try {
            result=db_buildingService.addBuild(db_building);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        //相应结果
        if(result){
            meg="success";
            return JSON.toJSONString(meg);
        }else{
            meg="failed";
            return JSON.toJSONString(meg);
        }
    }



    }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值