本文主要是一些简单的学习心得:

1.首先创建本地的Mysql数据库

2.然后要了解到MVC模式,然后在idea中创建动态的java-web模块,并分在不同的文件夹里实现不同的操作

3.在webapp下创建static文件夹,导入js文件

4.然后再WEB-INF文件夹导入相应的jar包

4.在webapp文件下创建前端的页面user.jsp

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/8/8
  Time: 10:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户列表</title>
    <link rel="stylesheet" href="static/css/bootstrap.min.css">
    <script src="static/js/jquery-1.11.3.min.js"></script>
    <script src="static/js/bootstrap.min.js"></script>
    <script src="static/js/jqPaginator.js"></script>
</head>
<body>
<-- 搜索框 -->
<div class="container-fluid">
    <div class="row">
        <div class="col-md-4">
            <form class="form-inline">
                <div class="form-group">
                    <label class="sr-only" for="user_name">用户名</label>
                    <input type="text" class="form-control" id="user_name" placeholder="用户名">
                </div>
                <div class="form-group">
                    <label class="sr-only" for="user_tel">电话</label>
                    <input type="tel" class="form-control" id="user_tel" placeholder="电话">
                </div>
                <button type="button" class="btn btn-primary" onclick="queryUser()">搜索</button>
            </form>
        </div>
        <div class="col-md-2">
            <button type="button" class="btn btn-primary" data-toggle='modal' data-target='#myModal1'>添加用户</button>
        </div>
    </div>
</div>
    <!-- Table-->
    <table class="table table-hover">
        <thead>
        <tr>
            <th>用户名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>电话</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="tab">

        </tbody>
        <tfoot>
            <tr>
                <td colspan="8" style="">
                    <ul class="pagination" id="pagination1"></ul>
                </td>
            </tr>
        </tfoot>
    </table>
    <!-- Modal修改 -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">用户修改</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <%--隐藏域(存放id值)--%>
                        <input type="hidden" id="userId">
                        <div class="form-group">
                            <label for="username" class="col-sm-2 control-label">用户名</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="username" placeholder="用户名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="userage" class="col-sm-2 control-label">年龄</label>
                            <div class="col-sm-10">
                                <input type="number" class="form-control" id="userage" placeholder="年龄">
                            </div>
                        </div>
                        <div class="form-group">
                            <label  class="col-sm-2 control-label">性别</label>
                            <div class="col-sm-10">
                                <div class="radio-inline">
                                    <input type="radio"  name="sex" id="sex1" value="男">男
                                </div>
                                <div class="radio-inline">
                                    <input type="radio"  name="sex" id="sex2" value="女">女
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="usertel" class="col-sm-2 control-label">电话</label>
                            <div class="col-sm-10">
                                <input type="tel" class="form-control" id="usertel" placeholder="电话">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="updateUser()">保存</button>
                </div>
            </div>
        </div>
    </div>
    <!-- Modal(添加) -->
    <div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">用户添加</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label for="username" class="col-sm-2 control-label">用户名</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="username1" placeholder="用户名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="userage" class="col-sm-2 control-label">年龄</label>
                            <div class="col-sm-10">
                                <input type="number" class="form-control" id="userage1" placeholder="年龄">
                            </div>
                        </div>
                        <div class="form-group">
                            <label  class="col-sm-2 control-label">性别</label>
                            <div class="col-sm-10">
                                <div class="radio-inline">
                                    <input type="radio"  name="gender" id="gender1" value="男">男
                                </div>
                                <div class="radio-inline">
                                    <input type="radio"  name="gender" id="gender2" value="女">女
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="usertel" class="col-sm-2 control-label">电话</label>
                            <div class="col-sm-10">
                                <input type="tel" class="form-control" id="usertel1" placeholder="电话">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="addUser()">提交</button>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

样式设置如下图所示

5.在后端的entity文件夹放的是实体类User

package com.xhu.fy.entity;

public class User {
    private Integer id;
    private String userName;
    private String userAge;
    private String userSex;
    private String userTel;
    private String userPwd;

    public User(Integer id, String userName, String userAge, String userSex, String userTel, String userPwd) {
        this.id = id;
        this.userName = userName;
        this.userAge = userAge;
        this.userSex = userSex;
        this.userTel = userTel;
        this.userPwd = userPwd;
    }

    public User() {
    }

    public Integer getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

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

    public String getUserAge() {
        return userAge;
    }

    public void setUserAge(String userAge) {
        this.userAge = userAge;
    }

    public String getUserSex() {
        return userSex;
    }

    public void setUserSex(String userSex) {
        this.userSex = userSex;
    }

    public String getUserTel() {
        return userTel;
    }

    public void setUserTel(String userTel) {
        this.userTel = userTel;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", userAge='" + userAge + '\'' +
                ", userSex='" + userSex + '\'' +
                ", userTel='" + userTel + '\'' +
                ", userPwd='" + userPwd + '\'' +
                '}';
    }
}

6.再Utils写连接数据库的工具类

package com.xhu.fy.utils;

import java.sql.*;

public class DBUtil {
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static Connection getCon(){
        try {
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=UTF-8", "root", "123456");
            return con;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return null;
        }
    }
    public static void closeAll(ResultSet rs, PreparedStatement ps,Connection con){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (ps!=null){
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (con!=null){
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

注意:此方法是用的Class.forName的方法

在getCon方法里加上?useUnicode=true&characterEncoding=UTF-8防止前端进行修改后出现“?

 编写分页的工具类PageUtil

package com.xhu.fy.utils;

import java.util.List;

public class PageUtil<T> {
    //总页数
    private int totalPages;
    //每页展示条数
    private int pageSize;
    //当前页码
    private int currentPage;
    //总条数
    private int totalCounts;
    //存放查询出的数据
    private List<T> pageInfo;

    public int getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(int totalPages) {
        this.totalPages = totalPages;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getTotalCounts() {
        return totalCounts;
    }

    public void setTotalCounts(int totalCounts) {
        this.totalCounts = totalCounts;
    }

    public List<T> getPageInfo() {
        return pageInfo;
    }

    public void setPageInfo(List<T> pageInfo) {
        this.pageInfo = pageInfo;
    }
}

7.在前端页面使用Ajax方法实现局部刷新的功能,查询数据库中所有的数据并实现分页功能

var total = 0;//总条数
        var visiblePages = 5;//显示的分页按钮数
        var current_Page = 0;//当前页码
        var pageSize = 5;//每页展示的条数
        /*
        页面加载完毕就执行
         */
        $(function () {
            showUser(-1);
            pageInit();
        });

 分页插件的初始化

/**
         * 分页插件初始化
         * 注意:要么设置totalPages,要么设置totalCounts + pageSize,否则报错;设置了totalCounts和pageSize后,会自动计算出totalPages。
         */
        function pageInit() {
            $('#pagination1').jqPaginator({
                pageSize:pageSize,
                visiblePages:visiblePages,
                currentPage:current_Page,
                totalCounts:total,
                first: '<li class="first"><a href="javascript:void(0);">第一页</a></li>',
                prev: '<li class="prev"><a href="javascript:void(0);">前一页</a></li>',
                next: '<li class="next"><a href="javascript:void(0);">下一页</a></li>',
                last: '<li class="last"><a href="javascript:void(0);">最后一页</a></li>',
                page: '<li class="page"><a href="javascript:void(0);">{{page}}</a></li>',
                onPageChange: function (num) {
                    /* num代表改变过后的页码 */
                    showUser(num);
                }
            });
        }
/*
        查询全部信息
         */
        function showUser(pageNum) {
            $.ajax({
                url:"user",
                type:"POST",
                async:false,//同步请求
                dataType:"json",
                data:{"_method":"queryUser","pageNum":pageNum,"pageSize":pageSize},
                success:function (data) {
                    if (pageNum==-1){//如果pageNum==-1,代表第一次访问
                        total=data.totalCounts;
                        current_Page=data.pageNum;
                    }
                    var str = "";
                    for(var i=0;i<data.pageInfo.length;i++){
                        str+="<tr><td>"+data.pageInfo[i].userName+"</td><td>"+data.pageInfo[i].userAge+"</td><td>"+data.pageInfo[i].userSex+"</td><td>"+
                            +data.pageInfo[i].userTel+"</td>"+
                            "<td><button type='button' class='btn btn-danger' onclick='deleteUser("+data.pageInfo[i].id+")'>删除</button>"+
                            "<button type='button' class='btn btn-primary' data-toggle='modal' data-target='#myModal' onclick='findUserById("+data.pageInfo[i].id+")'>修改</button></td></tr>";
                    }
                    $("#tab").html(str);
                }
            });
        }

向后端传递一个查询方法queryUser

在控制层controller里创建一个实现请求转发的servlet,重写方法doGET和doPost

String method = req.getParameter("_method");
        if (method.equals("queryUser")){
            queryUser(req,resp);
        }//获取方法名,并实现该方法
    public void queryUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pageNum = req.getParameter("pageNum");
        String pageSize = req.getParameter("pageSize");
        resp.setContentType("text/html;charset=utf-8");
        PageUtil<User> pageUtil = userService.queryUserPage(pageNum,pageSize);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(pageUtil);
        resp.getWriter().write(json);
    }

调用service层内封装的dao层的方法queryUserPage

编写service的接口

PageUtil<User> queryUserPage(String pageNum,String pageSize);

在serviceImpl实现类实现该方法

private UserDao userDao=new UserDaoImpl();
    @Override
    public PageUtil<User> queryUserPage(String pageNum,String pageSize) {
        int pageNum1 = Integer.parseInt(pageNum);
        if (pageNum1==-1){
            pageNum1=1;
        }
        PageUtil<User> userPageUtil = new PageUtil<>();
        int totalCounts = userDao.selectCountAll();
        userPageUtil.setTotalCounts(totalCounts);
        userPageUtil.setPageSize(Integer.parseInt(pageSize));
        userPageUtil.setCurrentPage(pageNum1);
        List<User> users = userDao.selectUser(pageNum1, Integer.parseInt(pageSize));
        userPageUtil.setPageInfo(users);
        return userPageUtil;
    }

调用dao层的方法来访问数据库中的数据

编写dao层的接口

 List<User> selectUser(int pageNum,int pageSize);

在dao层实现类daoImpl实现该方法

private Connection con = null;
    private PreparedStatement ps = null;
    private ResultSet rs = null;
    @Override
    public List<User> selectUser(int pageNum,int pageSize) {
        con = DBUtil.getCon();
        String sql="select * from user limit ?,?";
        try {
            ps = con.prepareStatement(sql);
            ps.setInt(1,(pageNum-1)*pageSize);
            ps.setInt(2,pageSize);
            rs = ps.executeQuery();
            List<User> users=new ArrayList<>();
            while (rs.next()){
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUserName(rs.getString("userName"));
                user.setUserAge(rs.getString("userAge"));
                user.setUserSex(rs.getString("userSex"));
                user.setUserTel(rs.getString("userTel"));
                user.setUserPwd(rs.getString("userPwd"));
                users.add(user);
            }
            return users;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.closeAll(rs,ps,con);
        }
        return null;
    }

8.实现删除数据的功能

在前端删除按钮定义一个点击方法,使用ajax局部刷新

/*
        删除
         */
        function deleteUser(id){
            var isDelete=confirm("确认是否删除?");
                if (isDelete){
                    $.ajax({
                        url: "user",
                        type: "get",
                        data: {"id":id,"_method":"deleteUser"},
                        dataType: "text",
                        success:function (data){
                            if (data="success"){
                                showUser();
                            }
                        }
                    });
                }
            }

注意:为了防止用户不小心数据,所以改在删除增加一个提示框

定义的方法名为deleteUser

后端controller层来接受

else if (method.equals("deleteUser")){
            deleteUser(req,resp);
        }
public void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        int id1 = Integer.parseInt(id);
        String mess = userService.deleteUserById(id1);
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(mess);
    }

通过主键id来进行删除

同理调用的service层封装的方法

String deleteUserById(int id);
   @Override
    public String deleteUserById(int id) {
        int num = userDao.deleteUserById(id);
        if(num>0){
            return "success";
        }else {
            return "fail";
        }
    }

dao层的方法

int deleteUserById(int id);
@Override
    public int deleteUserById(int id) {
        con = DBUtil.getCon();
        String sql = "delete from user where id = ?";
        try {
            ps = con.prepareStatement(sql);
            ps.setInt(1,id);
            int num = ps.executeUpdate();
            return num;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.closeAll(rs,ps,con);
        }
        return 0;
    }

9.实现修改数据的功能

在点击修改功能后,应该弹出一个新的模态框,内容为该数据的内容,可在上面进行修改和保存

首先要查询该指定用户的信息放在模态框上显示

 /*
        根据id查询用户
         */
        function findUserById(id){
            $.ajax({
                url:"user",
                type:"get",
                data:{"_method":"queryUserById","id":id},
                dataType:"json",
                success:function (data){
                    $("#userId").val(data.id);
                    $("#username").val(data.userName);
                    $("#userage").val(data.userAge);
                    if (data.userSex=="男"){
                        $("#sex1").prop("checked",true);
                    }else if(data.userSex=="女"){
                        $("#sex2").prop("checked",true);
                    }
                    $("#usertel").val(data.userTel);
                }
            });
        }

并进入到controller层

else if (method.equals("queryUserById")){
            queryUserById(req, resp);
        }
public void queryUserById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        int id1 = Integer.parseInt(id);
        resp.setContentType("text/html;charset=utf-8");
        User user = userService.queryUserById(id1);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(user);
        resp.getWriter().write(json);
    }

根据id值来查询当前的用户信息

service层的方法实现

User queryUserById(int id);
 @Override
    public User queryUserById(int id) {
        return userDao.selectUserById(id);
    }

dao层方法实现

User selectUserById(int id);
@Override
    public User selectUserById(int id) {
        con = DBUtil.getCon();
        String sql="select * from user where id=?";
        try {
            ps = con.prepareStatement(sql);
            ps.setInt(1,id);
            rs = ps.executeQuery();
             if (rs.next()){
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUserName(rs.getString("userName"));
                user.setUserAge(rs.getString("userAge"));
                user.setUserSex(rs.getString("userSex"));
                user.setUserTel(rs.getString("userTel"));
                user.setUserPwd(rs.getString("userPwd"));
                return user;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.closeAll(rs,ps,con);
        }
        return null;
    }

查询到数据后显示在模态框内,如图所示

修改用户的值

 /*
        修改用户信息
         */
        function updateUser(){
            //获取修改完后得表单值
            var userId = $("#userId").val()
            var userName = $("#username").val();
            var userSex = $("input[name='sex']:checked").val();
            var userAge = $("#userage").val();
            var userTel = $("#usertel").val();
            $.ajax({
                url:"user",
                type:"POST",
                data:{
                    "userId":userId,
                    "userName":userName,
                    "userSex":userSex,
                    "userAge":userAge,
                    "userTel":userTel,
                    "_method":"updateUserById"
                },
                dataType:"text",
                success:function (data){
                    if (data=="success"){
                        $('#myModal').modal('hide');
                        showUser();
                    }
                }
            });
        }

controller层

else if (method.equals("updateUserById")){
            updateUserById(req,resp);
        }
public void updateUserById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");
        String id = req.getParameter("userId");
        String userName = req.getParameter("userName");
        String userSex = req.getParameter("userSex");
        String userAge = req.getParameter("userAge");
        String userTel = req.getParameter("userTel");
        User user = new User();
        user.setId(Integer.parseInt(id));
        user.setUserName(userName);
        user.setUserSex(userSex);
        user.setUserAge(userAge);
        user.setUserTel(userTel);
        String mess = userService.updateUserById(user);
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(mess);
    }

service层

String updateUserById(User user);
 @Override
    public String updateUserById(User user) {
        int num = userDao.updateUserById(user);
        if(num>0){
            return "success";
        }else {
            return "fail";
        }
    }

dao层

 int updateUserById(User user);
@Override
    public int updateUserById(User user) {
        con=DBUtil.getCon();
        String sql="update user set userName=?,userAge=?,userSex=?,userTel=? where id=?";
        try {
            ps=con.prepareStatement(sql);
            ps.setString(1,user.getUserName());
            ps.setString(2,user.getUserAge());
            ps.setString(3,user.getUserSex());
            ps.setString(4,user.getUserTel());
            ps.setInt(5,user.getId());
            int num=ps.executeUpdate();
            return num;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeAll(rs,ps,con);
        }
        return 0;
    }

10.添加新的用户

点击按钮时弹出一个模态框来输入用户信息

/*
        添加用户信息
         */
        function addUser() {
            //获取修改完后得表单重点得值
            var userName=$("#username1").val();
            var userSex=$("input[name='gender']:checked").val();
            var userAge=$("#userage1").val();
            var userTel=$("#usertel1").val();
            $.ajax({
                url:"user",
                type:"POST",
                data:{
                    "userName":userName,
                    "userSex":userSex,
                    "userAge":userAge,
                    "userTel":userTel,
                    "_method":"addUser"
                },
                dataType:"text",
                success:function (data){
                    if (data=="success"){
                        $('#myModal1').modal('hide');
                        showUser();
                    }
                }
            });
        }

controller层

else if (method.equals("addUser")){
            addUser(req,resp);
        }
public void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");
        String userName = req.getParameter("userName");
        String userSex = req.getParameter("userSex");
        String userAge = req.getParameter("userAge");
        String userTel = req.getParameter("userTel");
        User u = new User();
        u.setUserSex(userSex);
        u.setUserName(userName);
        u.setUserAge(userAge);
        u.setUserTel(userTel);
        String mess = userService.addUser(u);
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(mess);
    }

service层

 String addUser(User user);
@Override
    public String addUser(User user) {
        int num = userDao.insertUser(user);
        if(num>0){
            return "success";
        }else {
            return "fail";
        }
    }

dao层

int insertUser(User user);
 @Override
    public int insertUser(User user) {
        con=DBUtil.getCon();
        String sql="insert into user (userName,userSex,userAge,userTel) value (?,?,?,?)";
        try {
            ps=con.prepareStatement(sql);
            ps.setString(1, user.getUserName());
            ps.setString(2, user.getUserSex());
            ps.setString(3, user.getUserAge());
            ps.setString(4, user.getUserTel());
            int num=ps.executeUpdate();
            return num;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeAll(rs,ps,con);
        }
        return 0;
    }

11.搜索有条件的用户

/*
        按照范围查找
         */
        function queryUser() {
            var username=$("#user_name").val();
            var usertel=$("#user_tel").val();
            $.ajax({
                url:"user",
                type:"POST",
                data:{
                    "userName":username,
                    "userTel":usertel,
                    "_method":"queryUserByUserNameAndTel"
                },
                dataType:"json",
                success:function (data){
                    //在显示数据前,先清空表格
                    $("#tab").html("");
                    var str = "";
                    for(var i=0;i<data.length;i++){
                        str+="<tr><td>"+data[i].userName+"</td><td>"+data[i].userAge+"</td><td>"+data[i].userSex+"</td><td>"+
                            +data[i].userTel+"</td>"+
                            "<td><button type='button' class='btn btn-danger' onclick='deleteUser("+data[i].id+")'>删除</button>"+
                            "<button type='button' class='btn btn-primary' data-toggle='modal' data-target='#myModal' onclick='findUserById("+data[i].id+")'>修改</button></td></tr>";
                    }
                    $("#tab").html(str);
                }
            });
        }

注意的时在查找前要显示所以的用户信息,点击查找后,页面显示的为查找过后的页面,两个都为空时,查找的是全部数据

controller层

else if (method.equals("queryUserByUserNameAndTel")){
            queryUserByUserNameAndTel(req,resp);
        }
public void queryUserByUserNameAndTel(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userName = req.getParameter("userName");
        String userTel = req.getParameter("userTel");
        resp.setContentType("text/html;charset=utf-8");
        List<User> users = userService.queryUser(userName,userTel);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(users);
        resp.getWriter().write(json);
    }

service层

List<User> queryUser(String userName,String userTel);
 @Override
    public List<User> queryUser(String userName, String userTel) {
        return Optional.ofNullable(userDao.selectUser(userName,userTel)).orElse(Collections.emptyList());
    }

dao层

    List<User> selectUser(String userName,String userTel);
    int selectCountAll();
 @Override
    public List<User> selectUser(String userName, String userTel) {
        con=DBUtil.getCon();
        String sql="select * from user where 1=1 ";
        List<Object> params = new ArrayList<>();
        if (!userName.equals("")){
            sql+="and userName=? ";
            params.add(userName);
        }
        if (!userTel.equals("")){
            sql+="and userTel=? ";
            params.add(userTel);
        }
        try {
            ps=con.prepareStatement(sql);
            for (int i = 0; i <params.size(); i++) {
                ps.setObject(i+1,params.get(i));
            }
            rs=ps.executeQuery();
            List<User> users = new ArrayList<>();
            while (rs.next()){
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUserName(rs.getString("userName"));
                user.setUserAge(rs.getString("userAge"));
                user.setUserSex(rs.getString("userSex"));
                user.setUserTel(rs.getString("userTel"));
                user.setUserPwd(rs.getString("userPwd"));
                users.add(user);
            }
            return users;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeAll(rs,ps,con);
        }
        return null;
    }

    @Override
    public int selectCountAll() {
        con=DBUtil.getCon();
        String sql="select count(*) num from user";
        try {
            ps=con.prepareStatement(sql);
            rs=ps.executeQuery();
            if (rs.next()){
                int totalCounts = rs.getInt("num");
                return totalCounts;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeAll(rs,ps,con);
        }
        return 0;
    }

 

注意,在查询时sql语句的拼接要用空格符号分割开来

12.总结

经过这次一个简单的sevlet项目来实现增删改查操作,由以下问题需要注意:

1.如何获取前端页面传进来的值

2.下一步实现登录页面的时候,如何与数据库中值进行比较,并实现页面的转发,登录页面如何防止sql注入等问题

3.在用户界面用模板实现界面的美化,和具体功能的实现

4.登陆界面实现动态验证码

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐