孟繁森

使用JSP + Servlet + JDBC + Mysql+C3P0连接池实现简单增删改查
java编辑器eclipse 服务器环境:tomcat HTML编辑器:Hbuilder 数据库管理系统:sqly...
扫描右侧二维码阅读全文
25
2019/07

使用JSP + Servlet + JDBC + Mysql+C3P0连接池实现简单增删改查

开发工具:

java编辑器eclipse
服务器环境:tomcat
HTML编辑器:Hbuilder
数据库管理系统:sqlyog
数据库:mysql
项目架构:

1.servlet 类
2.service类
3.dao类
4.entity类
5.utils类
需要依赖的文件:

mysql驱动包、dbutils驱动包、c3p0驱动包、mchange驱动包
配置文件:c3p0.properties
创建数据库,创建表:

ssj.png
搭建页面:

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>欢迎来到学生管理系统</h1>
    <a href="regist.jsp">注册学生信息</a>
    <a href="/student_crud/student?func=findAllStudent">查询所有学生</a>
</body>
</html>

regist.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h3>学生信息的注册页面</h3>
    <form action="student?func=insertStudent" method="post">
        姓名:<input type="text" name="sname" placeholder="请输入姓名" /><br />
        性别:
            <input type="radio" name="gender" value="男" />男
            <input type="radio" name="gender" value="女" />女<br />
        爱好:
            <input type="checkbox" name="hobby" value="唱歌" />唱歌
            <input type="checkbox" name="hobby" value="跳舞" />跳舞
            <input type="checkbox" name="hobby" value="rap" />rap
            <input type="checkbox" name="hobby" value="篮球" />篮球<br />
        学历:
            <select name="degree">
                <option value="本科">本科</option>
                <option value="专科">专科</option>
                <option value="红太阳幼儿园">红太阳幼儿园</option>
                <option value="外婆交大">外婆交大</option>
            </select><br />
        个人简介:
            <textarea name="mark" rows="10" cols="30"></textarea><br />
        <input type="submit" value="注册" />
    </form>
</body>
</html>

error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1 style="color: red;">来了老弟~~~</h1>
</body>
</html>

show.jsp

<%@page import="com.offcn.entity.Student"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table width="800" align="center" border="1" cellspacing="0" cellpadding="">
                <caption style="font-size: 60px;">学生信息</caption>
            <tr>
                <th>姓名</th>
                <th>性别</th>
                <th>爱好</th>
                <th>学历</th>
                <th>简介</th>
                <th>操作</th>
            </tr>
            <%
                List<Student> stus =(List<Student>) request.getAttribute("stus");
                for(Student s:stus){
            %>
                <tr style = "text-align:center;">
                    <td><%=s.getSname() %></td>
                    <td><%=s.getGender() %></td>
                    <td><%=s.getHobby() %></td>
                    <td><%=s.getDegree() %></td>
                    <td><%=s.getMark() %></td>
                    <td>
                        <a href="student?func=findStudent&sid=<%=s.getSid()%>>">修改</a>
                        <a href="student?func=deleteStudent&sid=<%=s.getSid() %>>">删除</a>
                    </td>
                </tr>
            <%
                }
            %>
        
        </table> 
</body>
</html>

update.jsp

<%@page import="com.offcn.entity.Student"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h3>学生信息的注册页面</h3>
    <form action="student?func=updateStudent&sid=${stu.sid }" method="post">
        姓名:<input type="text" value="${stu.sname }" name="sname" placeholder="请输入姓名" /><br />
        性别:
            <%
                Student stu = (Student)request.getAttribute("stu");
                if (stu.getGender().equals("男")) {
            %>
                    <input type="radio" name="gender" value="男" checked="checked" />男
                    <input type="radio" name="gender" value="女" />女<br />
            <%
                } else {
            %>
                    <input type="radio" name="gender" value="男" />男
                    <input type="radio" name="gender" value="女" checked="checked" />女<br />
            <%
                }
            %>
        爱好:
            <input type="checkbox" name="hobby" value="唱歌" />唱歌
            <input type="checkbox" name="hobby" value="跳舞" />跳舞
            <input type="checkbox" name="hobby" value="rap" />rap
            <input type="checkbox" name="hobby" value="篮球" />篮球<br />
        学历:
            <select name="degree">
                <option value="本科">本科</option>
                <option value="专科">专科</option>
                <option value="红太阳幼儿园">红太阳幼儿园</option>
                <option value="外婆交大">外婆交大</option>
            </select><br />
        个人简介:
            <textarea name="mark" rows="10" cols="30">${stu.mark }</textarea><br />
        <input type="submit" value="修改" />
    </form>
</body>
</html>

Class页面:

com.offcn.entity包下的Student.java类

package com.offcn.entity;
//javaBean书写规范
public class Student {
    private int sid;
    private String sname;
    private String gender;
    private String hobby;
    private String degree;
    private String mark;
    public int getSid() {
        return sid;
    }
    public void setSid(int sid) {
        this.sid = sid;
    }
    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getHobby() {
        return hobby;
    }
    public void setHobby(String hobby) {
        this.hobby = hobby;
    }
    public String getDegree() {
        return degree;
    }
    public void setDegree(String degree) {
        this.degree = degree;
    }
    public String getMark() {
        return mark;
    }
    public void setMark(String mark) {
        this.mark = mark;
    }
    public Student(int sid, String sname, String gender, String hobby, String degree, String mark) {
        super();
        this.sid = sid;
        this.sname = sname;
        this.gender = gender;
        this.hobby = hobby;
        this.degree = degree;
        this.mark = mark;
    }
    public Student(String sname, String gender, String hobby, String degree, String mark) {
        super();
        this.sname = sname;
        this.gender = gender;
        this.hobby = hobby;
        this.degree = degree;
        this.mark = mark;
    }
    public Student() {
        // TODO Auto-generated constructor stub
    }
    @Override
    public String toString() {
        return "Student [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", hobby=" + hobby + ", degree="
                + degree + ", mark=" + mark + "]";
    }
    
}

com.offcn.servlet包下的StudentServlet.java

package com.offcn.servlet;

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

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 com.offcn.entity.Student;
import com.offcn.service.StudentService;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private StudentService studentService = new StudentService();
    
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String func = request.getParameter("func");
        switch (func) {
            case "insertStudent":
                insertStudent(request, response);
                break;
            case "findAllStudent":
                findAllStudent(request, response);
                break;
            case "deleteStudent":
                deleteStudent(request, response);
                break;
            case "findStudent":
                findStudent(request, response);
                break;
            case "updateStudent":
                updateStudent(request, response);
                break;
            default:
                break;
        }
    }
    
    //修改学生信息的方法
    private void updateStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取学生信息
        String sname = request.getParameter("sname");
        String gender = request.getParameter("gender");
        String[] hobby = request.getParameterValues("hobby");
        String degree = request.getParameter("degree");
        String mark = request.getParameter("mark");
        String sid = request.getParameter("sid");
        
        //一旦传递的数据超过了一个,那么创建对象来传递对象
        Student student = new Student(Integer.valueOf(sid), sname, gender, Arrays.toString(hobby), degree, mark);
        boolean isSuccess = studentService.updateStudent(student);
        if (isSuccess) {
            //如果删除成功,跳转展示页面
            response.sendRedirect("student?func=findAllStudent");
        } else {
            //删除失败跳转一个失败页面
            response.sendRedirect("error.jsp");
        }
    }

    //通过主键id查找学生的方法
    private void findStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sid = request.getParameter("sid");
        Student student = studentService.findStudent(sid);
        /*
             先将学生放入域对象request中,转发到修改页面
         */
        request.setAttribute("stu", student);
        request.getRequestDispatcher("update.jsp").forward(request, response);
    }

    //删除学生
    private void deleteStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取传过来的主键id
        String sid = request.getParameter("sid");
        boolean isSuccess = studentService.deleteStudent(sid);
        if (isSuccess) {
            //如果删除成功,跳转展示页面
            response.sendRedirect("student?func=findAllStudent");
        } else {
            //删除失败跳转一个失败页面
            response.sendRedirect("error.jsp");
        }
    }

    //查询所有学生的方法
    private void findAllStudent(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        List<Student> stus = studentService.findAllStudent();
        /*
             1、完成从当前的servlet跳转show.jsp的功能
             2、将得到的学生stus传递到show.jsp中
             将数据存入request域中,再通过请求转发跳转页面
         */
        request.setAttribute("stus", stus);
        request.getRequestDispatcher("show.jsp").forward(request, response);
    }

    //注册学生信息的方法
    private void insertStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取学生信息
        String sname = request.getParameter("sname");
        String gender = request.getParameter("gender");
        String[] hobby = request.getParameterValues("hobby");
        String degree = request.getParameter("degree");
        String mark = request.getParameter("mark");
        
        //一旦传递的数据超过了一个,那么创建对象来传递对象
        Student student = new Student(sname, gender, Arrays.toString(hobby), degree, mark);
        boolean isSuccess = studentService.insertStudent(student);
        if (isSuccess) {
            //注册成功,跳转到展示页面
            response.sendRedirect("student?func=findAllStudent");
        } else {
            //注册失败,回到注册页面,重新注册
            response.sendRedirect("regist.jsp");
        }
    }
}

com.offcn.service包下的StudentService.java类

package com.offcn.service;

import java.util.List;

import com.offcn.dao.StudentDao;
import com.offcn.entity.Student;

public class StudentService {
    
    private StudentDao studentDao = new StudentDao();
    
    public boolean insertStudent(Student student) {
        int row = studentDao.insertStudent(student);
        if (row > 0) {
            return true;
        }
        return false;
    }

    public List<Student> findAllStudent() {
        return studentDao.findAllStudent();
    }

    public boolean deleteStudent(String sid) {
        int row = studentDao.deleteStudent(sid);
        if (row > 0) {
            return true;
        }
        return false;
    }

    public Student findStudent(String sid) {
        return studentDao.findStudent(sid);
    }

    public boolean updateStudent(Student student) {
        int row = studentDao.updateStudent(student);
        if (row > 0) {
            return true;
        }
        return false;
    }

}

com.offcn.dao包下的StudentDao.java类

package com.offcn.dao;

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

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.offcn.entity.Student;

public class StudentDao {
    
    private QueryRunner qRunner = new QueryRunner(new ComboPooledDataSource());
    
    public int insertStudent(Student student) {
        int row = 0;
        try {
            row = qRunner.update("insert into student values (null, ?, ?, ?, ?, ?)",
                        student.getSname(), student.getGender(), student.getHobby(),
                        student.getDegree(), student.getMark());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return row;
    }

    public List<Student> findAllStudent() {
        List<Student> stus = null;
        try {
            stus = qRunner.query("select * from student", new BeanListHandler<Student>(Student.class));
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return stus;
    }

    public int deleteStudent(String sid) {
        int row = 0;
        try {
            row = qRunner.update("delete from student where sid = ?", sid);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return row;
    }

    public Student findStudent(String sid) {
        Student student = null;
        try {
            student = qRunner.query("select * from student where sid = ?", new BeanHandler<Student>(Student.class), sid);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return student;
    }

    public int updateStudent(Student student) {
        int row = 0;
        try {
            row = qRunner.update("update student set sname = ?, gender = ?, hobby = ?, degree = ?, mark = ? where sid = ?",
                        student.getSname(), student.getGender(), student.getHobby(),
                        student.getDegree(), student.getMark(), student.getSid());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return row;
    }

}

c3p0.properties配置文件:

c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/student
c3p0.user=root
c3p0.password=root

这里附上源码+所用jar包:

此处内容需要评论回复后(审核通过)方可阅读。

此处内容需要评论回复后(审核通过)方可阅读。

Last modification:September 19th, 2019 at 08:51 am
如果觉得我的文章对你有用,请随意赞赏

One comment

  1. A

    滴,打卡成功!上车的旅客请系好安全带!现在是:Thu Jul 25 2019 22:09:39 GMT+0800 (中国标准时间)

Leave a Comment