效果图:
![通过jsp和servlet实现后台界面完成对数据库的增删改查_第1张图片](http://img.e-com-net.com/image/info8/927bca72e5ab48c9bfec85a16db93e0e.jpg)
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 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();
}
}
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'Student.jsp' starting pagetitle>
<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;ivar ch=document.getElementById("ch_"+i);
ch.checked=true;
}
}
else{
for(var i=0;ivar 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;iif(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;ivar 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;iget(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();
}
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"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 getStudents(String whereOption){
List list=new ArrayList()
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)
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()
}
}
}