通过jsp和servlet实现后台界面完成对数据库的增删改查

原创 2016年06月15日 11:16:26
  • 效果图:
    这里写图片描述

  • jsp代码:Student.jsp

<%@page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="entity.Students"%>
<%@page import="dao.StudentsDao"%>
<%@page import="com.mysql.jdbc.Connection"%>
<%@page import="dbhelper.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
request.setCharacterEncoding("utf-8");
Connection con=null;
List<Students> myData=null;
String sName=request.getParameter("searchName");
String ok=request.getParameter("ok");
try{
    con=MyConnection.getConnection();
    StudentsDao stuDao=new StudentsDao(con);
    if(sName!=null){
        myData=stuDao.getStudents(sName);
    }else{
        myData=stuDao.getStudents("");      
    }
}catch(Exception e){
    e.printStackTrace();
}finally{
    if(con!=null){
    con.close();
    }
}

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'Student.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <link rel="stylesheet" type="text/css" href="BesWeb.css">
    <script type="text/javascript">
        if('<%=ok %>'=="1"){
            alert("新增成功");
        }else if('<%=ok %>'=="2"){
            alert("修改成功");
        }else if('<%=ok %>'=="3"){
            alert("删除成功");
        }
        function search(){
         var sName=document.getElementById("searchName");
         document.baseForm.target="_self";
         document.baseForm.action="Student.jsp";
         document.baseForm.submit();
        }
        function checkAll(){
         var chAll=document.getElementById("chAll");
         var count=document.getElementById("count").value;
         if(chAll.checked){
            for(var i=0;i<count;i++){
                var ch=document.getElementById("ch_"+i);
                ch.checked=true;
            }
         }
         else{
            for(var i=0;i<count;i++){
                var ch=document.getElementById("ch_"+i);
                ch.checked=false;
            }
         }
        }

        function trSelected(idx){
         var count=document.getElementById("count").value;
         var listTable=document.getElementById("listTable");
         var c1=listTable.rows[idx].cells[1].innerText;
         var c2=listTable.rows[idx].cells[2].innerText;
         var c3=listTable.rows[idx].cells[3].innerText;
         var c4=listTable.rows[idx].cells[4].innerText;
         var stuId=document.getElementById("stuId");
         var stuName=document.getElementById("stuName");
         var stuClass=document.getElementById("stuClass");
         stuId.value=c1;
         stuName.value=c2;
         stuClass.value=c4;
         if(c3=='男'){
          document.getElementById("stu1").checked=true;
         }else{
          document.getElementById("stu2").checked=true;
         }
         for(var i=0;i<count;i++){
          if(i%2==0){
            listTable.rows[i+2].className='A';
          }else{
            listTable.rows[i+2].className='B';
          }
         }
         listTable.rows[idx].className='C';
        }

        function insert(){
         var stuId=document.getElementById("stuId");
         var stuName=document.getElementById("stuName");
         var stuClass=document.getElementById("stuClass");
         if(stuId.value==""){
            alert("请输入学生ID");
            stuId.focus();
            return;
         }
         if(stuName.value==""){
            alert("请输入学生姓名");
            stuName.focus();
            return;
         }
         document.getElementById("tag").value="insert";
         document.baseForm.target="_self";
         document.baseForm.submit();         
        }

        function update(){
         var stuId=document.getElementById("stuId");
         if(stuId.value==""){
            alert("请选择要修改的学生");
            stuId.focus();
            return;
         }
         document.getElementById("tag").value="update";
         document.baseForm.target="_self";
         document.baseForm.submit();
        }

        function del(){
         if(!checkId()){
            alert("请选择要删除的数据!");
            return;
         }
         if(confirm("确定删除吗?")){
            document.getElementById("tag").value="delete";
            document.baseForm.target="_self";
            document.baseForm.submit();
         }
        }

        function checkId(){
         var count=document.getElementById("count").value;
         for(var i=0;i<count;i++){
                var ch=document.getElementById("ch_"+i);
                if(ch.checked){
                    return true;
                }
            }
         return false;
        }

    </script>
  </head>

  <body>
    <form name=baseForm method=post action="<%=basePath%>/servlet/StudentServlet">
    <input type="hidden" id=count name=count value='<%=myData.size()%>'/>
    <input type="hidden" id=tag name=tag value="insert" />
        <table width=980>
            <tr>
                <td class=c width=100 align=center>
                    姓名
                </td>
                <td class=c width=100>
                    <input type=text id=searchName name=searchName value='<%=sName==null?"":sName %>' style="width:100%"/>
                </td>
                <td align=right>
                    <input type="button" value='查询'  onClick='search()'/>
                    <input type="button" value='新增' onClick='insert()'/>
                    <input type="button" value='修改' onClick='update()'/>
                    <input type="button" value='删除' onClick='del()'/>
                </td>
            </tr>
        </table>
        <table id=listTable width=980>
            <tr>
                <th width=50 align=center>选择</th>
                <th width=80 align=center>学号</th>
                <th width=80 align=center>姓名</th>
                <th width=80 align=center>性别</th>
                <th width=80 align=center>班级</th>
                <th width=* align=center>备注</th>
            </tr>

            <tr>
                <td align=center>
                    <input type=checkBox id=chAll name=chAll onClick="checkAll()"/>
                </td>
                <td>
                    <input type=text id=stuId name=stuId style="width:100%" class="INPUT_CT_BK"/>
                </td>
                <td>
                    <input type=text id=stuName name=stuName style="width:100%"/>
                </td>
                <td>
                    <input type=radio id=stu1 name=stuSex value='男' checked /><input type=radio id=stu2 name=stuSex value='女' /></td>
                <td>
                    <select id=stuClass name=stuClass style="width:100%">
                        <option value='1班'>1班</option>
                        <option value='2班' selected>2班</option>
                        <option value='3班'>3班</option>
                        <option value='4班'>4班</option>
                    </select>
                </td>
                <td>
                    <input type=text style="width:100%"/> 
                </td>

            </tr>
            <%
            String cls=""; 
            for(int i=0;i<myData.size();i++){
                Students stu=myData.get(i);
                if(i%2==0){
                cls="A";
                }else{
                cls="B";
                }
            %>
            <tr class='<%=cls%>' onClick="trSelected('<%=i+2%>')">
                <td align=center>
                    <input type=checkBox id=ch_<%=i%> name=ch_<%=i%> value='<%=stu.getStuId() %>' />
                </td>
                <td align=center><%= stu.getStuId() %></td>
                <td align=center><%= stu.getStuName() %></td>
                <td align=center><%= stu.getSexId() %></td>
                <td align=center><%= stu.getStuClass() %></td>
                <td align=center></td>
            </tr>
            <%} %>
        </table>
    </form>
  </body>
</html>
  • servlet代码:StudentServlet.java
package servlet;

import java.io.IOException;

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

import com.mysql.jdbc.Connection;

import dao.StudentsDao;
import dbhelper.MyConnection;
import entity.Students;

public class StudentServlet extends HttpServlet {
    public StudentServlet() {
        super();
    }

    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
    }
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String tag=request.getParameter("tag");
        if(tag.equals("insert")){
            insertStudent(request, response);
        }
        if(tag.equals("update")){
            updateStudent(request, response);
        }
        if(tag.equals("delete")){
            deleteStudent(request, response);
        }
    }

    public void insertStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        String stuId=request.getParameter("stuId");
        String stuName=request.getParameter("stuName");
        String stuSex=request.getParameter("stuSex");
        String stuClass=request.getParameter("stuClass");
        Students stu=new Students(stuId, stuName, stuSex, stuClass);
        try {
            Connection con=MyConnection.getConnection();
            StudentsDao sd=new StudentsDao(con);
            sd.insert(stu);
            String path = request.getContextPath();
            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
            response.sendRedirect(basePath+"/Student.jsp?ok=1");
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            MyConnection.closeConnection();
        }


    }

    public void updateStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        String stuId=request.getParameter("stuId");
        String stuName=request.getParameter("stuName");
        String stuSex=request.getParameter("stuSex");
        String stuClass=request.getParameter("stuClass");
        Students stu=new Students(stuId, stuName, stuSex, stuClass);
        try {
            Connection con=MyConnection.getConnection();
            StudentsDao sd=new StudentsDao(con);
            sd.update(stu);
            String path = request.getContextPath();
            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
            response.sendRedirect(basePath+"/Student.jsp?ok=2");
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            MyConnection.closeConnection();
        }
    }

    public void deleteStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        Connection con=MyConnection.getConnection();
        try {
            StudentsDao sd=new StudentsDao(con);
            int count=Integer.parseInt(request.getParameter("count"));
            for(int i=0;i<count;i++){
                String str="ch_"+i;
                String ch=request.getParameter(str);
                if(ch!=null){
                    sd.delete(ch);
                }
            }
            String path = request.getContextPath();
            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
            response.sendRedirect(basePath+"/Student.jsp?ok=3");
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            MyConnection.closeConnection();
        }
    }

    public void init() throws ServletException {
    }

}
  • 数据库增删改查代码:StudentsDao.java
package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

import entity.Students;


public class StudentsDao {
    private Connection con;
    public StudentsDao(){}
    public StudentsDao(Connection con){
        this.con=con;
    }

    public List<Students> getStudents(String whereOption){
        List<Students> list=new ArrayList<Students>();
        String sql="select * from stu";
        ResultSet rs=null;
        if(!whereOption.equals("")){
            sql+=" where stuName like '%"+whereOption+"%'";
        }
        try {
            Statement statement=(Statement)con.createStatement();
            rs=statement.executeQuery(sql); //执行sql语句
            Students stu=null;
            while(rs.next()){
                stu=new Students();
                stu.setStuId(rs.getString("stuId"));
                stu.setStuName(rs.getString("stuName"));
                stu.setStuClass(rs.getString("stuClass"));
                stu.setSexId(rs.getString("sexId"));
                list.add(stu);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally{
            try {
                if(rs!=null){
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
    public void insert(Students stu){
//      String sql="insert into student values('"+stu.getStuid()+"')";      //不安全,会造成注释攻击
//      String sql="insert into student values(?,?,?,?,?)";
        String sql="insert into stu select ?,?,?,? FROM DUAL WHERE NOT EXISTS(SELECT stuId FROM stu WHERE stuId = ?)";
        PreparedStatement ps=null;
        try {
            ps=(PreparedStatement) con.prepareStatement(sql);
            ps.setString(1,stu.getStuId());
            ps.setString(2,stu.getStuName());
            ps.setString(3,stu.getSexId());
            ps.setString(4,stu.getStuClass());
            ps.setString(5,stu.getStuId());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public void delete(String stuId){
        String sql="DELETE FROM stu WHERE stuid=?";
        PreparedStatement ps=null;
        try {
            ps=(PreparedStatement) con.prepareStatement(sql);
            ps.setString(1,stuId);
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void update(Students stu){
        String sql="UPDATE stu SET stuName=? ,sexId=? ,stuClass=? WHERE stuId=?";
        PreparedStatement ps=null;
        try {
            ps=(PreparedStatement) con.prepareStatement(sql);
            ps.setString(1,stu.getStuName());
            ps.setString(2,stu.getSexId());
            ps.setString(3,stu.getStuClass());
            ps.setString(4,stu.getStuId());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ygd1994/article/details/51679822

一个jsp网站,前台和后台

  • 2009年04月25日 17:04
  • 2.28MB
  • 下载

新闻发布项目——后台JSP界面adminManage/adminIndex.jsp

添加主题--管理后台 欢迎使用新闻管理系统! 管理员: 登录      login out 添加新闻 ...
  • qq_34137397
  • qq_34137397
  • 2016-11-25 00:24:41
  • 1428

后台开发学习——Jsp学习

后台开发学习——Jsp学习 1、jsp语法的三种类型: 答:(1)编译器指令(directive) ①编译器指令包括“包含指令”,“页指令”和“taglib指令” ②它们包含在卷标里 ③常用...
  • Remoa_Dengqinyi
  • Remoa_Dengqinyi
  • 2016-09-25 13:30:54
  • 985

JSP网站后台管理系统

  • 2012年01月11日 03:48
  • 32.65MB
  • 下载

jsp后台管理代码 完整

  • 2010年04月26日 22:52
  • 488KB
  • 下载

jsp 项目的后台模板

  • 2014年01月01日 00:04
  • 195KB
  • 下载

jsp+servlet+jdbc实现对数据库的增删改查

jsp+servlet+jdbc实现对数据库的增删改查
  • j086924
  • j086924
  • 2016-06-22 18:05:14
  • 37052

Servlet实现对SQLServer数据库的增删改查(工程源码)

  • 2015年06月24日 14:09
  • 19KB
  • 下载

Java+MyEclipse+Tomcat (六)详解Servlet和DAO数据库增删改查操作

此篇文章主要讲述DAO、Java Bean和Servlet实现操作数据库,把链接数据库、数据库操作、前端界面显示分模块化实现。其中包括数据的CRUD增删改查操作,并通过一个常用的JSP网站前端模板界面...
  • Eastmount
  • Eastmount
  • 2015-05-24 05:16:55
  • 23077

简易jsp+servlet实现单表增删查改

jsp+servlet进行单表增删查改
  • maple082
  • maple082
  • 2016-10-23 20:15:01
  • 9561
收藏助手
不良信息举报
您举报文章:通过jsp和servlet实现后台界面完成对数据库的增删改查
举报原因:
原因补充:

(最多只允许输入30个字)