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

  • 效果图:
    这里写图片描述

  • 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();
        }
    }
}
  • 15
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值