[JSP&JDBC]连接数据库DAO增删查改+JavaBean+分页显示实例

8 篇文章 0 订阅

src结构


Student

package com.yiki.dbutil;

public class Student {
	int id;
	String name;
	int age;
	
	 public static final int PAGE_SIZE=2;
	
	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 int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
}


DButil打开数据库和关闭数据库

package com.yiki.dbutil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DButil {

	private static String driver;
	private static String url;
	private static String username;
	private static String password;

	static {
		driver = "com.mysql.jdbc.Driver";
		url = "jdbc:mysql://localhost:3306/yiki?useUnicode=true&characterEncoding=gb2312";
		username = "root";
		password = "*******";
	}

	public static Connection open() {

		try {
			Class.forName(driver);
			return DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("连接错误");
		}
		return null;
	}
	
	public static void close(Connection con) {
		if (con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}

DAO接口

package com.yiki.dbutil;

import java.util.List;

public interface StudentDAO {

	public void add(Student s);
	public void delete(int id);
	public  Student getSbyID(int id);
	public List<Student> query();
	public void Update(Student s);
	public int findCount();
	public List<Student> find(int page);
}

实现接口的类

package com.yiki.dbutil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class StudentImpl implements StudentDAO {
	@Override
	public void add(Student s) {
		String sql = "insert into student(name,age)value(?,?)";
		Connection con = DButil.open();
		try {
			PreparedStatement pstm = con.prepareStatement(sql);
			pstm.setString(1, s.getName());
			pstm.setInt(2, s.getAge());
			pstm.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DButil.close(con);
		}

	}

	@Override
	public void delete(int id) {
		String sql = "delete from student where id = ?";
		Connection con = DButil.open();
		try {
			PreparedStatement pstm = con.prepareStatement(sql);
			pstm.setInt(1, id);
			pstm.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DButil.close(con);
		}
	}

	@Override
	public Student getSbyID(int id) {
		String sql = "select * from student where id=?";
		Connection con = DButil.open();
		Student s = new Student();
		try {
			PreparedStatement pstm = con.prepareStatement(sql);
			pstm.setInt(1, id);
			ResultSet rs = pstm.executeQuery();
			if (rs.next()) {
				String name = rs.getString(2);
				int age = rs.getInt(3);
				s.setId(id);
				s.setName(name);
				s.setAge(age);

			}
			return s;

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DButil.close(con);
		}

		return null;
	}

	@Override
	public List<Student> query() {
		String sql = "select * from student";
		Connection con = DButil.open();
		try {
			Statement stm = con.createStatement();
			ResultSet rs = stm.executeQuery(sql);
			List<Student> list = new ArrayList<Student>();
			while (rs.next()) {
				int id = rs.getInt(1);
				String name = rs.getString(2);
				int age = rs.getInt(3);
				Student s = new Student();
				s.setId(id);
				s.setName(name);
				s.setAge(age);
				list.add(s);
			}
			return list;

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DButil.close(con);
		}

		return null;
	}

	@Override
	public void Update(Student s) {
		String sql = "Update student set name=?,age=? where id=?";
		Connection con = DButil.open();
		try {
			PreparedStatement pstm = con.prepareStatement(sql);
			pstm.setString(1, s.getName());
			pstm.setInt(2, s.getAge());
			pstm.setInt(3, s.getId());
			pstm.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DButil.close(con);
		}

	}

	public int findCount() {
		int count = 0;
		Connection conn = DButil.open();
		String sql = "select count(*) from student";
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			if (rs.next()) {
				count = rs.getInt(1);
			}
			rs.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count; // 返回总记录数
	}

	public List<Student> find(int page) {//分页
		List<Student> list = new ArrayList<Student>();
		Connection con = DButil.open();
		String sql = "select* from student order by id desc limit ?,?";
		try {
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setInt(1, (page - 1) * Student.PAGE_SIZE);
			ps.setInt(2, Student.PAGE_SIZE);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				Student p = new Student();
				p.setId(rs.getInt("id"));
				p.setName(rs.getString("name"));
				p.setAge(rs.getInt("age"));
				list.add(p);
			}
			ps.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DButil.close(con);
		}
		return list;
	}
}

分页的Servlet

package com.yiki.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yiki.dbutil.Student;
import com.yiki.dbutil.StudentDAO;
import com.yiki.dbutil.StudentImpl;

public class Find extends HttpServlet {

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

		 int currPage=1;
	        if(request.getParameter("page")!=null){
	            currPage=Integer.parseInt(request.getParameter("page"));
	        }
	        StudentDAO dao = new StudentImpl();
	        List<Student> list = dao.find(currPage);
	        request.setAttribute("list", list);
	        int pages;  //总页数
	        int count=dao.findCount(); //查询总记录数
	        if(count%Student.PAGE_SIZE==0){
	            pages=count/Student.PAGE_SIZE;
	        }else{
	            pages=count/Student.PAGE_SIZE+1;
	        }
	        StringBuffer sb = new StringBuffer();
	        //通过循环构建分页条
	        for(int i=1;i<=pages;i++){
	            if(i==currPage){   //判断是否为当前页
	                sb.append("『"+i+"』");  //构建分页条
	            }else{
	                sb.append("<a href='Find?page="+i+"'>"+i+"</a>"); //构建分页条 !!!!注意路径!
	            }
	            sb.append(" ");
	        }
	        request.setAttribute("bar", sb.toString());
	        request.getRequestDispatcher("../product.jsp").forward(request, response);//注意这里的路径!
	    }
	
	

}

web文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<servlet>
		<description>This is the description of my J2EE component</description>
		<display-name>This is the display name of my J2EE component</display-name>
		<servlet-name>Find</servlet-name>
		<servlet-class>com.yiki.servlet.Find</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>Find</servlet-name>
		<url-pattern>/servlet/Find</url-pattern>
	</servlet-mapping>

</web-app>

JSP结构


忽略跳转页面,只显示取值
显示全部

<%@page import="com.yiki.dbutil.*"%>
<%@ page language="java" import="java.util.*,java.sql.*"
	pageEncoding="gb2312"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

<body>

	<table align="center" border="1">
		<tr>
			<td>id</td>
			<td>name</td>
			<td>age</td>
		</tr>
		<%
			StudentDAO dao = new StudentImpl();
			int count = dao.findCount();
			List<Student> list = dao.query();
			String name = null;
			int id = 0;
			int age = 0;
			for (int i = 0; i < list.size(); i++) {
				Student s = (Student) list.get(i);
				name = s.getName();
				id = s.getId();
				age = s.getAge();
		%>
		<tr>
			<td><%=id%></td>
			<td><%=name%></td>
			<td><%=age%></td>
		</tr>
		<%
			}
		%>

	</table>
	一共<%=count %>条记录
	
	
	<a href="index.jsp">返回</a>
	
	
</body>
</html>


删除

<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="gb2312"%>
<%@page import="com.yiki.dbutil.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  
  <body>
 删除成功 <br>
 <a href="look.jsp">查看</a>
 <a href="index.jsp">返回</a>
   <%
		int id =  Integer.parseInt(request.getParameter("ids"));
		StudentDAO dao = new StudentImpl();
		Student student = new Student();
		student.setId(id);
		dao.delete(id);
    %>
   
  </body>
</html>

插入

<%@ page language="java" import="java.util.*,java.sql.*"
	pageEncoding="gb2312"%>
<%@ page import="com.yiki.dbutil.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

<body>

	插入成功
	<a href="look.jsp">查看</a>
	<a href="index.jsp">返回</a>


	<%
		String name = request.getParameter("name");
		byte[] n = name.getBytes("ISO-8859-1");
		name = new String(n);
		StudentDAO dao = new StudentImpl();
		int age = Integer.parseInt(request.getParameter("age"));
		Student student = new Student();
		student.setName(name);
		student.setAge(age);
		dao.add(student);
	%>

</body>
</html>

根据ID查询

<%@page import="com.yiki.dbutil.*"%>
<%@ page language="java" import="java.util.*,java.sql.*"
	pageEncoding="gb2312"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

<body>
<h1>查询成功</h1>
	<table align="center" border="1">
		<tr>
			<td>id</td>
			<td>name</td>
			<td>age</td>
		</tr>
		<%
			int id = Integer.parseInt(request.getParameter("ids"));
			String name = null;
			int ids = 0;
			int age = 0;
			StudentDAO dao = new StudentImpl();
			Student student = new Student();
			Student s = dao.getSbyID(id);
			name = s.getName();
			ids = s.getId();
			age = s.getAge();
		%>
		<tr>
			<td><%=ids%></td>
			<td><%=name%></td>
			<td><%=age%></td>
		</tr>
		<%
			
		%>

	</table>



	<a href="index.jsp">返回</a>


</body>
</html>

更新

<%@page import="com.yiki.dbutil.*"%>
<%@ page language="java" import="java.util.*,java.sql.*"
	pageEncoding="gb2312"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

<body>

	<h1>更新成功</h1>
	<a href="look.jsp">查看</a>
	<a href="index.jsp">返回</a>


	<%
		String name = request.getParameter("name");
		byte[] n = name.getBytes("ISO-8859-1");
		name = new String(n);
		int id =  Integer.parseInt(request.getParameter("ids"));
		int age = Integer.parseInt(request.getParameter("age"));
		StudentDAO dao = new StudentImpl();
		Student student = new Student();
		student.setName(name);
		student.setAge(age);
		student.setId(id);
		dao.Update(student);
	%>

</body>
</html>

分页显示

<%@page import="com.yiki.dbutil.Student"%>
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  
  <body>
   <table align="center" border="1">
        <tr>
            <td align="center" colspan="5">
                <h2>所有信息</h2>
            </td>
        </tr>
        <tr align="center">
            <td><b>ID</b></td>
            <td><b>姓名</b></td>
            <td><b>年龄</b></td>
        </tr>
        <%
            List<Student> list=(List<Student>)request.getAttribute("list");
            for(Student p:list){
         %>
         <tr align="center">
             <td><%=p.getId() %></td>
             <td><%=p.getName()%></td>
             <td><%=p.getAge()%></td>
           
         </tr>
         <%
             }
          %>
          <tr>
              <td align="center" colspan="5">
                  <%=request.getAttribute("bar") %>
              </td>
          </tr>
    </table>
    
    <a href="../index.jsp">返回</a>
  </body>
</html>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值