查询用户的信息页面(Servlet)

目录

一.页面效果

二.需求

三. 技术选型:

四.设计架构

五. 准备工作(导入jar包、配置文件、工具类,创建数据库,创建用户类)

六.登录页面

七.查询所有用户

八. 添加联系人

九.删除某条记录

十.修改信息

十一. 删除选中

十二. 分页查询

十三. 条件查询

十四.service层和dao层


一.页面效果

查询用户的信息页面(Servlet)_第1张图片

二.需求

简单功能:列表查询、登录、添加、删除、修改

复杂功能:删除选中、分页查询、条件查询

三. 技术选型

Servlet+JSP+MySQL+JDBCTempleat+Duird(数据库连接池)+BeanUtils(封装数据)+Tomcat

四.设计架构

查询用户的信息页面(Servlet)_第2张图片

 

 

五. 准备工作(导入jar包、配置文件、工具类,创建数据库,创建用户类)

查询用户的信息页面(Servlet)_第3张图片

工具类

package util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

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

/**
 * JDBC工具类 使用Durid连接池
 */
public class JDBCUtils {

    private static DataSource ds ;
    static {

        try {
            //1.加载配置文件
            Properties pro = new Properties();
            //使用ClassLoader加载配置文件,获取字节输入流
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);

            //2.初始化连接池对象
            ds = DruidDataSourceFactory.createDataSource(pro);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接池对象
     */
    public static DataSource getDataSource(){
        return ds;
    }

    /**
     * 获取连接Connection对象
     */
    public static Connection getConnection() throws SQLException {
        return  ds.getConnection();
    }
}

数据库

CREATE DATABASE USER;
USE USER;
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(20)
);

查询用户的信息页面(Servlet)_第4张图片

用户类

public class User {
    private int id;
    private String name;
    private String gender;
    private int age;
    private String address;
    private String QQ;
    private String email;
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getQQ() {
        return QQ;
    }
    public void setQQ(String QQ) {
        this.QQ = QQ;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

dao层:操作数据库

public class UserDaoImpl implements UserDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public List findAll() {
        //使用JDBC操作数据库
        String sql = "select * from user";
        List users = template.query(sql, new BeanPropertyRowMapper<>(User.class));
        return users;
    }
    //根据用户名和密码查询用户
    @Override
    public User findUserByUsernameAndPassword(String username, String password) {
        try {
            String sql ="select * from user where username = ? and password = ?";
            User user = template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), username, password);
            return user;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    //添加用户
    @Override
    public void add(User user) {
        String sql = "insert into user values(null,?,?,?,?,?,?,null,null)";
        //执行sql
        template.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQQ(),user.getEmail());
    }

    @Override
    public void delete(int id) {
        String sql = "delete from user where id = ?";
        //执行sql
        template.update(sql,id);
    }

    @Override
    public User findById(int id) {
        String sql = "select * from user where id = ?";
        return template.queryForObject(sql,new BeanPropertyRowMapper<>(User.class),id);
    }

    @Override
    public void update(User user) {
        String sql = "update user set name = ?, gender = ?, age = ?, address = ?, qq = ?, email = ? where id = ?";
        template.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQQ(),user.getEmail(),user.getId());
    }

    @Override
    public int findTotalCount() {
        String sql = "select count(*) from user";
        return template.queryForObject(sql,Integer.class);
    }

    @Override
    public List findByPage(int start, int rows) {
        String sql = "select * from user limit ? ,?";
        return template.query(sql,new BeanPropertyRowMapper<>(User.class),start,rows);
    }

    @Override
    public int findTotalByCondition(Map condition) {
        //定义初始sql模板
        String sql = "select count(*) from user where 1 = 1 ";//1=1为了方便加and
        StringBuilder sb = new StringBuilder(sql);
        //定义参数的集合
        List list = new ArrayList();
        //遍历map
        Set keySet = condition.keySet();
        for (String key : keySet) {
            //获取value
            String value = condition.get(key)[0];//明确知道只有一个值
            //排除分页条件参数
            if("currentPage".equals(value) || "rows".equals(value)){
                continue;
            }
            if(value!=null && !"".equals(value)){
                sb.append(" and "+key+" like ? ");
                list.add("%"+value+"%");//?条件的值

            }
        }
        sql = sb.toString();
        return template.queryForObject(sql,Integer.class,list.toArray());
    }

    @Override
    public List findByCondition(int start, int rows, Map condition) {
        String sql = "select * from user where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        //定义参数的集合
        List list = new ArrayList();
        //遍历map
        Set keySet = condition.keySet();
        for (String key : keySet) {
            //获取value
            String value = condition.get(key)[0];//明确知道只有一个值
            //排除分页条件参数
            if("currentPage".equals(value) || "rows".equals(value)){
                continue;
            }
            if(value!=null && !"".equals(value)){
                sb.append(" and "+key+" like ? ");
                list.add("%"+value+"%");//?条件的值

            }
        }
        //添加分页查询
        sb.append(" limit ?,?");
        list.add(start);
        list.add(rows);

        sql = sb.toString();
        return template.query(sql,new BeanPropertyRowMapper<>(User.class),list.toArray());
    }
} 
  

src目录:

查询用户的信息页面(Servlet)_第5张图片

六.登录页面

查询用户的信息页面(Servlet)_第6张图片

checkCodeServlet(生成验证码图片   可以网上找一个不用自己写)


@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);
	}
}

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: 15634
  Date: 2020/8/7
  Time: 14:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>



    
    
    
    管理员登录

    
    
    
    
    
    
    


管理员登录


index.jsp

<%--
  Created by IntelliJ IDEA.
  User: 15634
  Date: 2020/8/5
  Time: 14:04
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>



  
  
  
  首页

  
  
  
  
  
  
  


${user.name},欢迎您
查询所有用户信息

七.查询所有用户

查询用户的信息页面(Servlet)_第7张图片

userListServlet

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

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

list.jsp

<%@ 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)_第8张图片

add.jsp

<%--
  Created by IntelliJ IDEA.
  User: 15634
  Date: 2020/8/7
  Time: 16:16
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>





    
    
    
    
    
    
    
    添加用户

    
    
    
    
    
    


添加联系人页面

addUserServlet

@WebServlet("/addUserServlet")
public class addUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //获取参数
        Map map = request.getParameterMap();
        //封装对象
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //调用service保存
        UserService service = new UserServiceImpl();
        service.add(user);
        //跳转到userListServlet
        response.sendRedirect(request.getContextPath()+"/userListServlet");
    }

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

九.删除某条记录

查询用户的信息页面(Servlet)_第9张图片

delServlet

@WebServlet("/delServlet")
public class delServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取要删除的id
        String id = request.getParameter("id");
        //调用service删除
        UserService service = new UserServiceImpl();
        service.deleteUser(id);
        //跳转到userListServlet
        response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
    }

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

十.修改信息

查询用户的信息页面(Servlet)_第10张图片

update.jsp

<%--
  Created by IntelliJ IDEA.
  User: 15634
  Date: 2020/8/8
  Time: 15:16
  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"%>




    
    
    
    
    修改用户

    
    
    



修改联系人

 updateUserServlet

@WebServlet("/updateUserServlet")
public class updateUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //获取map
        Map map = request.getParameterMap();
        //把已经修改了的user信息封装
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //修改
        UserService service = new UserServiceImpl();
        service.updateUser(user);
        //跳转到查询所有Servlet
        response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
    }

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

十一. 删除选中

查询用户的信息页面(Servlet)_第11张图片

 delSelectedServlet

@WebServlet("/delSelectedServlet")
public class delSelectedServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取所有id
        String[] ids = request.getParameterValues("uid");
        UserService service = new UserServiceImpl();
        service.delSelected(ids);
        //跳转
        response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
    }

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

 十二. 分页查询

查询用户的信息页面(Servlet)_第12张图片

PageBean

/**
 * 分页对象
 */
public class PageBean {
    private int totalCount;     //总的记录数
    private int totalPage;      //总的页码
    private List list;       //每页的数据
    private int currentPagePage;//当前页码
    private int rows;           //每页显示的记录数

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public List getList() {
        return list;
    }

    public void setList(List list) {
        this.list = list;
    }

    public int getCurrentPagePage() {
        return currentPagePage;
    }

    public void setCurrentPagePage(int currentPagePage) {
        this.currentPagePage = currentPagePage;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }
}

 findUserByPageServlet

@WebServlet("/findUserByPageServlet")
public class findUserByPageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取参数
        String currentPage = request.getParameter("currentPage");//当前页码
        String rows = request.getParameter("rows");//每页显示的个数
        //如果第一访问,设置初始值
        if(currentPage==null || "".equals(currentPage)){
            currentPage = "1";
        }
        if(rows==null || "".equals(rows)){
            rows = "5";
        }
        //调用service查询
        UserService service = new UserServiceImpl();
        PageBean pb = service.findUserByPage(currentPage,rows);
        //将pb存入request
        request.setAttribute("pb",pb);
        //转发
        request.getRequestDispatcher("/list.jsp").forward(request,response);
    }

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

service方法:

    /**
     *  分页查询
     * @param _currentPage
     * @param _rows
     * @return
     */
    @Override
    public PageBean findUserByPage(String _currentPage, String _rows) {
        int currentPage = Integer.parseInt(_currentPage);
        int rows = Integer.parseInt(_rows);
        //创建空的PageBean对象
        PageBean pb = new PageBean<>();
        //设置参数
        pb.setCurrentPagePage(currentPage);
        pb.setRows(rows);
        //调用dao查询总记录数
        int totalCount = dao.findTotalCount();
        pb.setTotalCount(totalCount);
        //查询当前页面数据的集合
        //计算开始的索引
        int start = (currentPage - 1) * rows;
        List list = dao.findByPage(start,rows);
        pb.setList(list);
        //计算总页码
        int totalPage = (totalCount % rows) == 0 ? totalCount/rows : totalCount/rows + 1;
        pb.setTotalPage(totalPage);

        return pb;
    }

十三. 条件查询

查询用户的信息页面(Servlet)_第13张图片

findUserByConditionServlet

@WebServlet("/findUserByConditionServlet")
public class findUserByConditionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //获取参数
        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();


        //调用service查询
        UserService service = new UserServiceImpl();
        PageBean pb = service.findUserByCondition(currentPage,rows,condition);
        //将pb存入request
        request.setAttribute("pb",pb);
        //转发
        request.getRequestDispatcher("/list.jsp").forward(request,response);
    }

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

 service

    /**
     * 分页条件查询
     * @param _currentPage   当前的页码
     * @param _rows          要显示的行数
     * @param condition      条件
     * @return
     */
    @Override
    public PageBean findUserByCondition(String _currentPage, String _rows, Map condition) {
        int currentPage = Integer.parseInt(_currentPage);
        if(currentPage <= 0 ) currentPage = 1;
        int rows = Integer.parseInt(_rows);
        //创建空的PageBean对象
        PageBean pb = new PageBean<>();
        //设置参数
        pb.setCurrentPagePage(currentPage);
        pb.setRows(rows);
        //调用dao查询总记录数
        int totalCount = dao.findTotalByCondition(condition);
        pb.setTotalCount(totalCount);
        //查询当前页面数据的集合
        //计算开始的索引
        int start = (currentPage - 1) * rows;
        List list = dao.findByCondition(start,rows,condition);
        pb.setList(list);
        //计算总页码
        int totalPage = (totalCount % rows) == 0 ? totalCount/rows : totalCount/rows + 1;
        pb.setTotalPage(totalPage);

        return pb;
    }

dao

    //条件查询的满足条件的总个数
    @Override
    public int findTotalByCondition(Map condition) {
        //定义初始sql模板
        String sql = "select count(*) from user where 1 = 1 ";//1=1为了方便加and
        StringBuilder sb = new StringBuilder(sql);
        //定义参数的集合
        List list = new ArrayList();
        //遍历map
        Set keySet = condition.keySet();
        for (String key : keySet) {
            //获取value
            String value = condition.get(key)[0];//明确知道只有一个值
            //排除分页条件参数
            if("currentPage".equals(value) || "rows".equals(value)){
                continue;
            }
            if(value!=null && !"".equals(value)){
                sb.append(" and "+key+" like ? ");
                list.add("%"+value+"%");//?条件的值

            }
        }
        sql = sb.toString();
        return template.queryForObject(sql,Integer.class,list.toArray());
    }
    // 条件查询返回的对象集合
    @Override
    public List findByCondition(int start, int rows, Map condition) {
        String sql = "select * from user where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        //定义参数的集合
        List list = new ArrayList();
        //遍历map
        Set keySet = condition.keySet();
        for (String key : keySet) {
            //获取value
            String value = condition.get(key)[0];//明确知道只有一个值
            //排除分页条件参数
            if("currentPage".equals(value) || "rows".equals(value)){
                continue;
            }
            if(value!=null && !"".equals(value)){
                sb.append(" and "+key+" like ? ");
                list.add("%"+value+"%");//?条件的值

            }
        }
        //添加分页查询
        sb.append(" limit ?,?");
        list.add(start);
        list.add(rows);

        sql = sb.toString();
        return template.query(sql,new BeanPropertyRowMapper<>(User.class),list.toArray());
    } 
  

十四.service层和dao层

service

public class UserServiceImpl implements UserService {
    private UserDao dao = new UserDaoImpl();
    @Override
    public List findAll() {
        //调用dao来完成查询
        return dao.findAll();
    }

    @Override
    public User loin(User user) {
        return dao.findUserByUsernameAndPassword(user.getUsername() ,user.getPassword());
    }

    @Override
    public void add(User user) {
        dao.add(user);
    }

    @Override
    public void deleteUser(String id) {
        dao.delete(Integer.parseInt(id));
    }

    @Override
    public User findUserById(String id) {
        return dao.findById(Integer.parseInt(id));
    }

    @Override
    public void updateUser(User user) {
        dao.update(user);
    }

    /**
     *  删除选中
     * @param ids
     */
    @Override
    public void delSelected(String[] ids) {
        if(ids!=null && ids.length!=0){//防止空指针异常
            //遍历删除
            for (String id : ids) {
                dao.delete(Integer.parseInt(id));
            }
        }
    }

    /**
     *  分页查询
     * @param _currentPage
     * @param _rows
     * @return
     */
    @Override
    public PageBean findUserByPage(String _currentPage, String _rows) {
        int currentPage = Integer.parseInt(_currentPage);
        int rows = Integer.parseInt(_rows);
        //创建空的PageBean对象
        PageBean pb = new PageBean<>();
        //设置参数
        pb.setCurrentPagePage(currentPage);
        pb.setRows(rows);
        //调用dao查询总记录数
        int totalCount = dao.findTotalCount();
        pb.setTotalCount(totalCount);
        //查询当前页面数据的集合
        //计算开始的索引
        int start = (currentPage - 1) * rows;
        List list = dao.findByPage(start,rows);
        pb.setList(list);
        //计算总页码
        int totalPage = (totalCount % rows) == 0 ? totalCount/rows : totalCount/rows + 1;
        pb.setTotalPage(totalPage);

        return pb;
    }

    /**
     * 分页条件查询
     * @param _currentPage   当前的页码
     * @param _rows          要显示的行数
     * @param condition      条件
     * @return
     */
    @Override
    public PageBean findUserByCondition(String _currentPage, String _rows, Map condition) {
        int currentPage = Integer.parseInt(_currentPage);
        if(currentPage <= 0 ) currentPage = 1;
        int rows = Integer.parseInt(_rows);
        //创建空的PageBean对象
        PageBean pb = new PageBean<>();
        //设置参数
        pb.setCurrentPagePage(currentPage);
        pb.setRows(rows);
        //调用dao查询总记录数
        int totalCount = dao.findTotalByCondition(condition);
        pb.setTotalCount(totalCount);
        //查询当前页面数据的集合
        //计算开始的索引
        int start = (currentPage - 1) * rows;
        List list = dao.findByCondition(start,rows,condition);
        pb.setList(list);
        //计算总页码
        int totalPage = (totalCount % rows) == 0 ? totalCount/rows : totalCount/rows + 1;
        pb.setTotalPage(totalPage);

        return pb;
    }
}

dao

public class UserDaoImpl implements UserDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public List findAll() {
        //使用JDBC操作数据库
        String sql = "select * from user";
        List users = template.query(sql, new BeanPropertyRowMapper<>(User.class));
        return users;
    }
    //根据用户名和密码查询用户
    @Override
    public User findUserByUsernameAndPassword(String username, String password) {
        try {
            String sql ="select * from user where username = ? and password = ?";
            User user = template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), username, password);
            return user;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    //添加用户
    @Override
    public void add(User user) {
        String sql = "insert into user values(null,?,?,?,?,?,?,null,null)";
        //执行sql
        template.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQQ(),user.getEmail());
    }

    @Override
    public void delete(int id) {
        String sql = "delete from user where id = ?";
        //执行sql
        template.update(sql,id);
    }

    @Override
    public User findById(int id) {
        String sql = "select * from user where id = ?";
        return template.queryForObject(sql,new BeanPropertyRowMapper<>(User.class),id);
    }

    @Override
    public void update(User user) {
        String sql = "update user set name = ?, gender = ?, age = ?, address = ?, qq = ?, email = ? where id = ?";
        template.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQQ(),user.getEmail(),user.getId());
    }

    @Override
    public int findTotalCount() {
        String sql = "select count(*) from user";
        return template.queryForObject(sql,Integer.class);
    }

    @Override
    public List findByPage(int start, int rows) {
        String sql = "select * from user limit ? ,?";
        return template.query(sql,new BeanPropertyRowMapper<>(User.class),start,rows);
    }
    //条件查询的满足条件的总个数
    @Override
    public int findTotalByCondition(Map condition) {
        //定义初始sql模板
        String sql = "select count(*) from user where 1 = 1 ";//1=1为了方便加and
        StringBuilder sb = new StringBuilder(sql);
        //定义参数的集合
        List list = new ArrayList();
        //遍历map
        Set keySet = condition.keySet();
        for (String key : keySet) {
            //获取value
            String value = condition.get(key)[0];//明确知道只有一个值
            //排除分页条件参数
            if("currentPage".equals(value) || "rows".equals(value)){
                continue;
            }
            if(value!=null && !"".equals(value)){
                sb.append(" and "+key+" like ? ");
                list.add("%"+value+"%");//?条件的值

            }
        }
        sql = sb.toString();
        return template.queryForObject(sql,Integer.class,list.toArray());
    }
    // 条件查询返回的对象
    @Override
    public List findByCondition(int start, int rows, Map condition) {
        String sql = "select * from user where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        //定义参数的集合
        List list = new ArrayList();
        //遍历map
        Set keySet = condition.keySet();
        for (String key : keySet) {
            //获取value
            String value = condition.get(key)[0];//明确知道只有一个值
            //排除分页条件参数
            if("currentPage".equals(value) || "rows".equals(value)){
                continue;
            }
            if(value!=null && !"".equals(value)){
                sb.append(" and "+key+" like ? ");
                list.add("%"+value+"%");//?条件的值

            }
        }
        //添加分页查询
        sb.append(" limit ?,?");
        list.add(start);
        list.add(rows);

        sql = sb.toString();
        return template.query(sql,new BeanPropertyRowMapper<>(User.class),list.toArray());
    }
}
 
  

 

你可能感兴趣的:(JavaEE学习,后端)