Java--小项目(登录、增删改查、分页、搜索)

Java--小项目(登录、增删改查、分页、搜索)

博客说明

文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!

概念

技术选型

Servlet、JSP、MySQL、JDBCTempleat、Duird、BeanUtilS、tomcat

功能介绍

登录功能,列表展示,数据添加,数据编辑,数据删除,批量删除,分页展示,关键字搜索

创建JavaWeb项目

Java--小项目(登录、增删改查、分页、搜索)_第1张图片

导入依赖

Java--小项目(登录、增删改查、分页、搜索)_第2张图片

添加页面文件

Java--小项目(登录、增删改查、分页、搜索)_第3张图片

数据库

create database little; -- 创建数据库
use little; 			   -- 使用数据库
create table user(   -- 创建表
	id int primary key auto_increment,
	name varchar(20) not null,
	gender varchar(5),
	age int,
	address varchar(32),
	qq	varchar(20),
	email varchar(50,
	username varchar(32),
  password varchar(32),
);

列表展示

思路

首先我们需要一组列表的数据,那么我们就需要一个相对应servlet,通过我们的三层架构,使用service同一做接口,然后调用dao层使用JBDC操作数据库,这样我们可以获得一个map集合的数据,然后就是渲染数据到jsp页面了,通过JSTL和EL把数据循环渲染到表里面,达到列表的展示

list.jsp
<%--
  Created by IntelliJ IDEA.
  User: tanglei
  Date: 2020/6/28
  Time: 下午2:15
  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" %>





    
    
    
    
    
    
    
    用户信息管理系统

    
    
    
    
    
    
    


用户信息列表

编号 姓名 性别 年龄 籍贯 QQ 邮箱 操作
${s.count} ${user.name} ${user.gender} ${user.age} ${user.address} ${user.qq} ${user.email} 修改 删除
添加联系人
servlet

代码文件很多,就不一一展示了

Java--小项目(登录、增删改查、分页、搜索)_第4张图片

UserListServlet
package cn.guizimo.little.web.servlet;

import cn.guizimo.little.domain.User;
import cn.guizimo.little.service.UserService;
import cn.guizimo.little.service.impl.UserServiceImpl;

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.util.List;

@WebServlet("/userListServlet")
public class UserListServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //调用UserService完成查询
        UserService userService = new UserServiceImpl();
        List users = userService.findAll();
        //存入request域
        req.setAttribute("users",users);
        //转发到list.jsp
        req.getRequestDispatcher("/list.jsp").forward(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

测试

Java--小项目(登录、增删改查、分页、搜索)_第5张图片

登录

思路

登录功能首先就是对表单提交的数据进行比对,验证码可以在生成的时候就把它存入到session中,然后在servlet中进行比对,其他的字段在通过调用dao层的JDBC操作数据库进行比对,最后把登录成功的用户信息存入session中

login.jsp
<%--
  Created by IntelliJ IDEA.
  User: tanglei
  Date: 2020/6/28
  Time: 下午7:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>



    
    
    
    管理员登录

    
    
    
    
    
    
    


管理员登录


LoginServlet
package cn.guizimo.little.web.servlet;

import cn.guizimo.little.domain.User;
import cn.guizimo.little.service.UserService;
import cn.guizimo.little.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;


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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码
        req.setCharacterEncoding("utf-8");
        //传递过来的验证码
        String verifycode = req.getParameter("verifycode");
        HttpSession session = req.getSession();
        //session里面的验证码
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");
        //比对验证码
        if (!checkcode_server.equalsIgnoreCase(verifycode)) {
            req.setAttribute("login_msg", "验证码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }

        Map parameterMap = req.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user, parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        UserService userService = new UserServiceImpl();
        User loginUser = userService.login(user);
        if(loginUser != null){
            session.setAttribute("user",loginUser);
            resp.sendRedirect(req.getContextPath()+"/index.jsp");
        }else {
            req.setAttribute("login_msg", "登录失败");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

CheckCodeServlet
package cn.guizimo.little.web.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证码
 */
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		
		//服务器通知浏览器不要缓存
		response.setHeader("pragma","no-cache");
		response.setHeader("cache-control","no-cache");
		response.setHeader("expires","0");
		
		//在内存中创建一个长80,宽30的图片,默认黑色背景
		//参数一:长
		//参数二:宽
		//参数三:颜色
		int width = 80;
		int height = 30;
		BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		
		//获取画笔
		Graphics g = image.getGraphics();
		//设置画笔颜色为灰色
		g.setColor(Color.GRAY);
		//填充图片
		g.fillRect(0,0, width,height);
		
		//产生4个随机验证码,12Ey
		String checkCode = getCheckCode();
		//将验证码放入HttpSession中
		request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);
		
		//设置画笔颜色为黄色
		g.setColor(Color.YELLOW);
		//设置字体的小大
		g.setFont(new Font("黑体",Font.BOLD,24));
		//向图片上写入验证码
		g.drawString(checkCode,15,25);
		
		//将内存中的图片输出到浏览器
		//参数一:图片对象
		//参数二:图片的格式,如PNG,JPG,GIF
		//参数三:图片输出到哪里去
		ImageIO.write(image,"PNG",response.getOutputStream());
	}
	/**
	 * 产生4位随机字符串 
	 */
	private String getCheckCode() {
		String base = "0123456789ABCDEFGabcdefg";
		int size = base.length();
		Random r = new Random();
		StringBuffer sb = new StringBuffer();
		for(int i=1;i<=4;i++){
			//产生0到size-1的随机值
			int index = r.nextInt(size);
			//在base字符串中获取下标为index的字符
			char c = base.charAt(index);
			//将c放入到StringBuffer中去
			sb.append(c);
		}
		return sb.toString();
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request,response);
	}
}

测试

Java--小项目(登录、增删改查、分页、搜索)_第6张图片

添加人员

思路

添加操作就是把jsp提交的表单的数据向数据库里面存储,过程为jsp->servlet->service->dao

add.jsp
<%--
  Created by IntelliJ IDEA.
  User: tanglei
  Date: 2020/6/28
  Time: 下午8:55
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>





    
    
    
    
    
    
    
    添加用户

    
    
    
    
    
    


添加联系人页面

AddUserServlet
package cn.guizimo.little.web.servlet;

import cn.guizimo.little.domain.User;
import cn.guizimo.little.service.UserService;
import cn.guizimo.little.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

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.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Map parameterMap = req.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        UserService userService = new UserServiceImpl();
        userService.addUser(user);
        resp.sendRedirect(req.getContextPath()+"/userListServlet");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

测试

Java--小项目(登录、增删改查、分页、搜索)_第7张图片

修改

思路

首先我们需要在打开jsp页面的时候就查询到这样的一条记录,通过这一条记录的id作为表单的隐藏域,在servlet里面将数据进行保存即可

update.jsp
<%--
  Created by IntelliJ IDEA.
  User: tanglei
  Date: 2020/6/29
  Time: 上午10:44
  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" %>




    
    
    
    
    修改用户

    
    
    



修改联系人

FindUserServlet
package cn.guizimo.little.web.servlet;

import cn.guizimo.little.domain.User;
import cn.guizimo.little.service.UserService;
import cn.guizimo.little.service.impl.UserServiceImpl;

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;

@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取id
        String id = req.getParameter("id");
        //2.调用Service查询
        UserService service = new UserServiceImpl();
        User user = service.findUserById(id);

        //3.将user存入request
        req.setAttribute("user",user);
        //4.转发到update.jsp
        req.getRequestDispatcher("/update.jsp").forward(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

UpdateUserServlet
package cn.guizimo.little.web.servlet;

import cn.guizimo.little.domain.User;
import cn.guizimo.little.service.UserService;
import cn.guizimo.little.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

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.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/updateUserServlet")
public class UpdateUserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置编码
        req.setCharacterEncoding("utf-8");
        //2.获取map
        Map map = req.getParameterMap();
        //3.封装对象
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //4.调用Service修改
        UserService service = new UserServiceImpl();
        service.updateUser(user);

        //5.跳转到查询所有Servlet
        resp.sendRedirect(req.getContextPath()+"/userListServlet");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

测试

Java--小项目(登录、增删改查、分页、搜索)_第8张图片

删除

思路

通过获取到对应的id即可到servlet中处理,操作数据库删除,在进行删除的时候可出现提示框

DelUserServlet
package cn.guizimo.little.web.servlet;

import cn.guizimo.little.service.UserService;
import cn.guizimo.little.service.impl.UserServiceImpl;

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;

@WebServlet("/delUserServlet")
public class DelUserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取id
        String id = req.getParameter("id");
        //2.调用service删除
        UserService service = new UserServiceImpl();
        service.deleteUser(id);

        //3.跳转到查询所有Servlet
        resp.sendRedirect(req.getContextPath()+"/userListServlet");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

测试

Java--小项目(登录、增删改查、分页、搜索)_第9张图片

删除选择的多个

思路

和删除差不多,最主要是获取id的集合

DelSelectedServlet
package cn.guizimo.little.web.servlet;

import cn.guizimo.little.service.UserService;
import cn.guizimo.little.service.impl.UserServiceImpl;

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;

@WebServlet("/delSelectedServlet")
public class DelSelectedServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取所有id
        String[] ids = req.getParameterValues("uid");
        //2.调用service删除
        UserService service = new UserServiceImpl();
        service.delSelectedUser(ids);

        //3.跳转查询所有Servlet
        resp.sendRedirect(req.getContextPath()+"/userListServlet");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

测试

Java--小项目(登录、增删改查、分页、搜索)_第10张图片

分页

思路

在jsp中获取查询的总条数,每页显示的条数,当前的页码,将之传递给服务器,操作数据库进行查询

list.jsp
<%--
  Created by IntelliJ IDEA.
  User: tanglei
  Date: 2020/6/28
  Time: 下午2:15
  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" %>





    
    
    
    
    
    
    
    用户信息管理系统

    
    
    
    
    
    
    
    


用户信息列表

编号 姓名 性别 年龄 籍贯 QQ 邮箱 操作
${s.count} ${user.name} ${user.gender} ${user.age} ${user.address} ${user.qq} ${user.email} 修改  删除
FindUserByPageServlet
package cn.guizimo.little.web.servlet;


import cn.guizimo.little.domain.PageBean;
import cn.guizimo.little.domain.User;
import cn.guizimo.little.service.UserService;
import cn.guizimo.little.service.impl.UserServiceImpl;

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.util.Map;

@WebServlet("/findUserByPageServlet")
public class FindUserByPageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        //1.获取参数
        String currentPage = request.getParameter("currentPage");//当前页码
        String rows = request.getParameter("rows");//每页显示条数

        if(currentPage == null || "".equals(currentPage)){
            currentPage = "1";
        }

        if(rows == null || "".equals(rows)){
            rows = "5";
        }
        
        //获取条件查询参数
        Map condition = request.getParameterMap();

        //2.调用service查询
        UserService service = new UserServiceImpl();
        PageBean pb = service.findUserByPage(currentPage,rows,condition);

        System.out.println(pb);

        //3.将PageBean存入request
        request.setAttribute("pb",pb);
        request.setAttribute("condition",condition);//将查询条件存入request
        //4.转发到list.jsp
        request.getRequestDispatcher("/list.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

测试

Java--小项目(登录、增删改查、分页、搜索)_第11张图片

条件查询

思路

主要是在sql语句的编写

jsp
dao层方法
@Override
    public int findTotalCount(Map condition) {
        //1.定义模板初始化sql
        String sql = "select count(*) from user where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        //2.遍历map
        Set keySet = condition.keySet();
        //定义参数的集合
        List params = new ArrayList();
        for (String key : keySet) {
            //排除分页条件参数
            if("currentPage".equals(key) || "rows".equals(key)){
                continue;
            }
            //获取value
            String value = condition.get(key)[0];
            //判断value是否有值
            if(value != null && !"".equals(value)){
                //有值
                sb.append(" and "+key+" like ? ");
                params.add("%"+value+"%");//?条件的值
            }
        }
        System.out.println(sb.toString());
        System.out.println(params);
        return template.queryForObject(sb.toString(),Integer.class,params.toArray());
    }

    @Override
    public List findByPage(int start, int rows, Map condition) {
        String sql = "select * from user  where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        //2.遍历map
        Set keySet = condition.keySet();
        //定义参数的集合
        List params = new ArrayList();
        for (String key : keySet) {
            //排除分页条件参数
            if("currentPage".equals(key) || "rows".equals(key)){
                continue;
            }
            //获取value
            String value = condition.get(key)[0];
            //判断value是否有值
            if(value != null && !"".equals(value)){
                //有值
                sb.append(" and "+key+" like ? ");
                params.add("%"+value+"%");//?条件的值
            }
        }
        //添加分页查询
        sb.append(" limit ?,? ");
        //添加分页查询参数值
        params.add(start);
        params.add(rows);
        sql = sb.toString();
        System.out.println(sql);
        System.out.println(params);
        return template.query(sql,new BeanPropertyRowMapper(User.class),params.toArray());
    }
 
 
测试

Java--小项目(登录、增删改查、分页、搜索)_第12张图片

感谢

黑马程序员

万能的网络

以及勤劳的自己

关注公众号: 归子莫,获取更多的资料,还有更长的学习计划

你可能感兴趣的:(Java--小项目(登录、增删改查、分页、搜索))