java web学生表的增加、修改、删除

来源:互联网 发布:scratch2.0趣味编程 编辑:程序博客网 时间:2024/06/16 05:35

三层架构:

1.建立包cn.sdut.dao

建立类:

BaseDao.java/StudentDao.java

BaseDao.java:

创建数据库的连接。public Connection getConn()

关闭数据库。public void closeAll()

StudentDao.java:

数据库的增删改查函数。

2.建立包cn.sdut.po

建立类:

Student.java

Student.java:

定义各个属性。再利用自动补全实现。

3.建立包cn.sdut.view

建立类:

Main.java

测试数据库的增删改查是否可以实现。

JSP界面:

首先将js那个文件夹考到WebRoot下面实现日历的小程序。

index.jsp:对数据库的展示:

效果如下



addStudent.jsp:


 

updateStudent.jsp:

 

 

doDelete.jsp:



 删除学生


源码如下:

BaseDao.java:

package cn.sdut.dao;import java.sql.*;public class BaseDao {Connection con;PreparedStatement pst;ResultSet rs;public Connection getConn(){try {Class.forName("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}String url="jdbc:mysql://localhost:3307/school?useUnicode=true&characterEncoding=utf-8";try {con=DriverManager.getConnection(url,"root","usbw");} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return con;}public void closeAll(){try {if(rs!=null)rs.close();if(pst!=null)pst.close();if(con!=null)con.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void main(String[] args){BaseDao baseDao = new BaseDao();Connection conn=baseDao.getConn();if(conn!=null)System.out.println("yes");else System.out.println("no");}}
StudentDao.java:

package cn.sdut.dao;import java.sql.SQLException;import java.util.*;import cn.sdut.po.Student;public class StudentDao extends BaseDao {public int add(Student stu){int result=0;con=getConn();String sql="insert into student(name,birthday,score) values(?,?,?)";try {pst=con.prepareStatement(sql);pst.setString(1, stu.getName());pst.setString(2,stu.getBirthday());pst.setFloat(3, stu.getScore());result=pst.executeUpdate();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{closeAll();}return result;}public int del(int id){int result=0;con=getConn();String sql="delete from student where id=?";try {pst=con.prepareStatement(sql);pst.setInt(1, id);result=pst.executeUpdate();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{closeAll();}return result;}public int update(Student stu){int result=0;con=getConn();String sql="update student set name='"+stu.getName()+"',birthday='"+stu.getBirthday()+"',score='"+stu.getScore()+"' where id="+stu.getId();System.out.println(stu.getId());try {pst=con.prepareStatement(sql);result=pst.executeUpdate(sql);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{closeAll();}return result;}public List<Student> queryAll(){List<Student> list=new ArrayList<Student>();con=getConn();String sql="select * from student";try {pst=con.prepareStatement(sql);rs=pst.executeQuery();while(rs.next()){Student stu= new Student();stu.setId(rs.getInt(1));stu.setName(rs.getString(2));stu.setBirthday(rs.getString(3));stu.setScore(rs.getFloat(4));list.add(stu);}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{closeAll();}return list;}public Student queryStudentById(int id){Student stu=new Student();con=getConn();String sql="select * from student where id="+id;try {pst=con.prepareStatement(sql);rs=pst.executeQuery(sql);if(rs.next()){stu.setId(rs.getInt(1));stu.setName(rs.getString(2));stu.setBirthday(rs.getString(3));stu.setScore(rs.getFloat(4));}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return stu;}}
Student.java:

package cn.sdut.po;public class Student {private String name;private int id;private String birthday;private float score;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getBirthday() {return birthday;}public void setBirthday(String birthday) {this.birthday = birthday;}public float getScore() {return score;}public void setScore(float score) {this.score = score;}@Overridepublic String toString() {return "Student [name=" + name + ", id=" + id + ", birthday=" + birthday+ ", score=" + score + "]";}}
Main.java:

package cn.sdut.view;import java.util.List;import cn.sdut.dao.StudentDao;import cn.sdut.po.Student;public class Main{public static void main(String[] args){StudentDao studentDao=new StudentDao();Student stu=new Student();stu.setId(48);stu.setName("李四");stu.setBirthday("45613");stu.setScore(78);//studentDao.add(stu);//studentDao.del(30);//studentDao.update(stu);Student stu1=studentDao.queryStudentById(61);System.out.println(stu1);//List <Student> list=studentDao.queryAll();//for(Student stu1:list)//{//System.out.println(stu1);//}}}

calendar.js:

/** * Calendar * @param   beginYear           1990 * @param   endYear             2010 * @param   language            0(zh_cn)|1(en_us)|2(en_en)|3(zh_tw) * @param   patternDelimiter    "-" * @param   date2StringPattern  "yyyy-MM-dd" * @param   string2DatePattern  "ymd" * @version 1.0 build 2006-04-01 * @version 1.1 build 2006-12-17 * @author  KimSoft (jinqinghua [at] gmail.com) * NOTE!    you can use it free, but keep the copyright please * IMPORTANT:you must include this script file inner html body elment  */function Calendar(beginYear, endYear, language, patternDelimiter, date2StringPattern, string2DatePattern) {this.beginYear = beginYear || 1958;this.endYear   = endYear   || 2090;this.language  = language  || 0;this.patternDelimiter = patternDelimiter     || "-";this.date2StringPattern = date2StringPattern || Calendar.language["date2StringPattern"][this.language].replace(/\-/g, this.patternDelimiter);this.string2DatePattern = string2DatePattern || Calendar.language["string2DatePattern"][this.language];this.dateControl = null;this.panel  = this.getElementById("__calendarPanel");this.iframe = window.frames["__calendarIframe"];this.form   = null;this.date = new Date();this.year = this.date.getFullYear();this.month = this.date.getMonth();this.colors = {"bg_cur_day":"#00CC33","bg_over":"#EFEFEF","bg_out":"#FFCC00"}};Calendar.language = {"year"   : ["\u5e74", "", "", "\u5e74"],"months" : [["\u4e00\u6708","\u4e8c\u6708","\u4e09\u6708","\u56db\u6708","\u4e94\u6708","\u516d\u6708","\u4e03\u6708","\u516b\u6708","\u4e5d\u6708","\u5341\u6708","\u5341\u4e00\u6708","\u5341\u4e8c\u6708"],["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"],["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"],["\u4e00\u6708","\u4e8c\u6708","\u4e09\u6708","\u56db\u6708","\u4e94\u6708","\u516d\u6708","\u4e03\u6708","\u516b\u6708","\u4e5d\u6708","\u5341\u6708","\u5341\u4e00\u6708","\u5341\u4e8c\u6708"]],"weeks"  : [["\u65e5","\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d"],["Sun","Mon","Tur","Wed","Thu","Fri","Sat"],["Sun","Mon","Tur","Wed","Thu","Fri","Sat"],["\u65e5","\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d"]],"clear"  : ["\u6e05\u7a7a", "Clear", "Clear", "\u6e05\u7a7a"],"today"  : ["\u4eca\u5929", "Today", "Today", "\u4eca\u5929"],"close"  : ["\u5173\u95ed", "Close", "Close", "\u95dc\u9589"],"date2StringPattern" : ["yyyy-MM-dd", "yyyy-MM-dd", "yyyy-MM-dd", "yyyy-MM-dd"],"string2DatePattern" : ["ymd","ymd", "ymd", "ymd"]};Calendar.prototype.draw = function() {calendar = this;var _cs = [];_cs[_cs.length] = '<form id="__calendarForm" name="__calendarForm" method="post">';_cs[_cs.length] = '<table id="__calendarTable" width="100%" border="0" cellpadding="3" cellspacing="1" align="center">';_cs[_cs.length] = ' <tr>';_cs[_cs.length] = '  <th><input class="l" name="goPrevMonthButton" type="button" id="goPrevMonthButton" value="<" \/><\/th>';_cs[_cs.length] = '  <th colspan="5"><select class="year" name="yearSelect" id="yearSelect"><\/select><select class="month" name="monthSelect" id="monthSelect"><\/select><\/th>';_cs[_cs.length] = '  <th><input class="r" name="goNextMonthButton" type="button" id="goNextMonthButton" value=">" \/><\/th>';_cs[_cs.length] = ' <\/tr>';_cs[_cs.length] = ' <tr>';for(var i = 0; i < 7; i++) {_cs[_cs.length] = '<th class="theader">';_cs[_cs.length] = Calendar.language["weeks"][this.language][i];_cs[_cs.length] = '<\/th>';}_cs[_cs.length] = '<\/tr>';for(var i = 0; i < 6; i++){_cs[_cs.length] = '<tr align="center">';for(var j = 0; j < 7; j++) {switch (j) {case 0: _cs[_cs.length] = '<td class="sun"> <\/td>'; break;case 6: _cs[_cs.length] = '<td class="sat"> <\/td>'; break;default:_cs[_cs.length] = '<td class="normal"> <\/td>'; break;}}_cs[_cs.length] = '<\/tr>';}_cs[_cs.length] = ' <tr>';_cs[_cs.length] = '  <th colspan="2"><input type="button" class="b" name="clearButton" id="clearButton" \/><\/th>';_cs[_cs.length] = '  <th colspan="3"><input type="button" class="b" name="selectTodayButton" id="selectTodayButton" \/><\/th>';_cs[_cs.length] = '  <th colspan="2"><input type="button" class="b" name="closeButton" id="closeButton" \/><\/th>';_cs[_cs.length] = ' <\/tr>';_cs[_cs.length] = '<\/table>';_cs[_cs.length] = '<\/form>';this.iframe.document.body.innerHTML = _cs.join("");this.form = this.iframe.document.forms["__calendarForm"];this.form.clearButton.value = Calendar.language["clear"][this.language];this.form.selectTodayButton.value = Calendar.language["today"][this.language];this.form.closeButton.value = Calendar.language["close"][this.language];this.form.goPrevMonthButton.onclick = function () {calendar.goPrevMonth(this);}this.form.goNextMonthButton.onclick = function () {calendar.goNextMonth(this);}this.form.yearSelect.onchange = function () {calendar.update(this);}this.form.monthSelect.onchange = function () {calendar.update(this);}this.form.clearButton.onclick = function () {calendar.dateControl.value = "";calendar.hide();}this.form.closeButton.onclick = function () {calendar.hide();}this.form.selectTodayButton.onclick = function () {var today = new Date();calendar.date = today;calendar.year = today.getFullYear();calendar.month = today.getMonth();calendar.dateControl.value = today.format(calendar.date2StringPattern);calendar.hide();}};Calendar.prototype.bindYear = function() {var ys = this.form.yearSelect;ys.length = 0;for (var i = this.beginYear; i <= this.endYear; i++){ys.options[ys.length] = new Option(i + Calendar.language["year"][this.language], i);}};Calendar.prototype.bindMonth = function() {var ms = this.form.monthSelect;ms.length = 0;for (var i = 0; i < 12; i++){ms.options[ms.length] = new Option(Calendar.language["months"][this.language][i], i);}};Calendar.prototype.goPrevMonth = function(e){if (this.year == this.beginYear && this.month == 0){return;}this.month--;if (this.month == -1) {this.year--;this.month = 11;}this.date = new Date(this.year, this.month, 1);this.changeSelect();this.bindData();};Calendar.prototype.goNextMonth = function(e){if (this.year == this.endYear && this.month == 11){return;}this.month++;if (this.month == 12) {this.year++;this.month = 0;}this.date = new Date(this.year, this.month, 1);this.changeSelect();this.bindData();};Calendar.prototype.changeSelect = function() {var ys = this.form.yearSelect;var ms = this.form.monthSelect;for (var i= 0; i < ys.length; i++){if (ys.options[i].value == this.date.getFullYear()){ys[i].selected = true;break;}}for (var i= 0; i < ms.length; i++){if (ms.options[i].value == this.date.getMonth()){ms[i].selected = true;break;}}};Calendar.prototype.update = function (e){this.year  = e.form.yearSelect.options[e.form.yearSelect.selectedIndex].value;this.month = e.form.monthSelect.options[e.form.monthSelect.selectedIndex].value;this.date = new Date(this.year, this.month, 1);this.changeSelect();this.bindData();};Calendar.prototype.bindData = function () {var calendar = this;var dateArray = this.getMonthViewDateArray(this.date.getFullYear(), this.date.getMonth());var tds = this.getElementsByTagName("td", this.getElementById("__calendarTable", this.iframe.document));for(var i = 0; i < tds.length; i++) {  tds[i].style.backgroundColor = calendar.colors["bg_over"];tds[i].onclick = null;tds[i].onmouseover = null;tds[i].onmouseout = null;tds[i].innerHTML = dateArray[i] || " ";if (i > dateArray.length - 1) continue;if (dateArray[i]){tds[i].onclick = function () {if (calendar.dateControl){calendar.dateControl.value = new Date(calendar.date.getFullYear(),calendar.date.getMonth(),this.innerHTML).format(calendar.date2StringPattern);}calendar.hide();}tds[i].onmouseover = function () {this.style.backgroundColor = calendar.colors["bg_out"];}tds[i].onmouseout  = function () {this.style.backgroundColor = calendar.colors["bg_over"];}var today = new Date();if (today.getFullYear() == calendar.date.getFullYear()) {if (today.getMonth() == calendar.date.getMonth()) {if (today.getDate() == dateArray[i]) {tds[i].style.backgroundColor = calendar.colors["bg_cur_day"];tds[i].onmouseover = function () {this.style.backgroundColor = calendar.colors["bg_out"];}tds[i].onmouseout  = function () {this.style.backgroundColor = calendar.colors["bg_cur_day"];}}}}}//end if}//end for};Calendar.prototype.getMonthViewDateArray = function (y, m) {var dateArray = new Array(42);var dayOfFirstDate = new Date(y, m, 1).getDay();var dateCountOfMonth = new Date(y, m + 1, 0).getDate();for (var i = 0; i < dateCountOfMonth; i++) {dateArray[i + dayOfFirstDate] = i + 1;}return dateArray;};Calendar.prototype.show = function (dateControl, popuControl) {if (this.panel.style.visibility == "visible") {this.panel.style.visibility = "hidden";}if (!dateControl){throw new Error("arguments[0] is necessary!")}this.dateControl = dateControl;popuControl = popuControl || dateControl;this.draw();this.bindYear();this.bindMonth();if (dateControl.value.length > 0){this.date  = new Date(dateControl.value.toDate(this.patternDelimiter, this.string2DatePattern));this.year  = this.date.getFullYear();this.month = this.date.getMonth();}this.changeSelect();this.bindData();var xy = this.getAbsPoint(popuControl);this.panel.style.left = xy.x + "px";this.panel.style.top = (xy.y + dateControl.offsetHeight) + "px";this.panel.style.visibility = "visible";};Calendar.prototype.hide = function() {this.panel.style.visibility = "hidden";};Calendar.prototype.getElementById = function(id, object){object = object || document;return document.getElementById ? object.getElementById(id) : document.all(id);};Calendar.prototype.getElementsByTagName = function(tagName, object){object = object || document;return document.getElementsByTagName ? object.getElementsByTagName(tagName) : document.all.tags(tagName);};Calendar.prototype.getAbsPoint = function (e){var x = e.offsetLeft;var y = e.offsetTop;while(e = e.offsetParent){x += e.offsetLeft;y += e.offsetTop;}return {"x": x, "y": y};};/** * @param   d the delimiter * @param   p the pattern of your date * @author  meizz * @author  kimsoft add w+ pattern */Date.prototype.format = function(style) {var o = {"M+" : this.getMonth() + 1, //month"d+" : this.getDate(),      //day"h+" : this.getHours(),     //hour"m+" : this.getMinutes(),   //minute"s+" : this.getSeconds(),   //second"w+" : "\u65e5\u4e00\u4e8c\u4e09\u56db\u4e94\u516d".charAt(this.getDay()),   //week"q+" : Math.floor((this.getMonth() + 3) / 3),  //quarter"S"  : this.getMilliseconds() //millisecond}if (/(y+)/.test(style)) {style = style.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));}for(var k in o){if (new RegExp("("+ k +")").test(style)){style = style.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));}}return style;};/** * @param d the delimiter * @param p the pattern of your date * @rebuilder kimsoft * @version build 2006.12.15 */String.prototype.toDate = function(delimiter, pattern) {delimiter = delimiter || "-";pattern = pattern || "ymd";var a = this.split(delimiter);var y = parseInt(a[pattern.indexOf("y")], 10);//remember to change this next century ;)if(y.toString().length <= 2) y += 2000;if(isNaN(y)) y = new Date().getFullYear();var m = parseInt(a[pattern.indexOf("m")], 10) - 1;var d = parseInt(a[pattern.indexOf("d")], 10);if(isNaN(d)) d = 1;return new Date(y, m, d);};document.writeln('<div id="__calendarPanel" style="position:absolute;visibility:hidden;z-index:9999;background-color:#FFFFFF;border:1px solid #666666;width:200px;height:216px;">');document.writeln('<iframe name="__calendarIframe" id="__calendarIframe" width="100%" height="100%" scrolling="no" frameborder="0" style="margin:0px;"><\/iframe>');var __ci = window.frames['__calendarIframe'];__ci.document.writeln('<!DOCTYPE html PUBLIC "-\/\/W3C\/\/DTD XHTML 1.0 Transitional\/\/EN" "http:\/\/www.w3.org\/TR\/xhtml1\/DTD\/xhtml1-transitional.dtd">');__ci.document.writeln('<html xmlns="http:\/\/www.w3.org\/1999\/xhtml">');__ci.document.writeln('<head>');__ci.document.writeln('<meta http-equiv="Content-Type" content="text\/html; charset=utf-8" \/>');__ci.document.writeln('<title>Web Calendar(UTF-8) Written By KimSoft<\/title>');__ci.document.writeln('<style type="text\/css">');__ci.document.writeln('<!--');__ci.document.writeln('body {font-size:12px;margin:0px;text-align:center;}');__ci.document.writeln('form {margin:0px;}');__ci.document.writeln('select {font-size:12px;background-color:#EFEFEF;}');__ci.document.writeln('table {border:0px solid #CCCCCC;background-color:#FFFFFF}');__ci.document.writeln('th {font-size:12px;font-weight:normal;background-color:#FFFFFF;}');__ci.document.writeln('th.theader {font-weight:normal;background-color:#666666;color:#FFFFFF;width:24px;}');__ci.document.writeln('select.year {width:64px;}');__ci.document.writeln('select.month {width:60px;}');__ci.document.writeln('td {font-size:12px;text-align:center;}');__ci.document.writeln('td.sat {color:#0000FF;background-color:#EFEFEF;}');__ci.document.writeln('td.sun {color:#FF0000;background-color:#EFEFEF;}');__ci.document.writeln('td.normal {background-color:#EFEFEF;}');__ci.document.writeln('input.l {border: 1px solid #CCCCCC;background-color:#EFEFEF;width:20px;height:20px;}');__ci.document.writeln('input.r {border: 1px solid #CCCCCC;background-color:#EFEFEF;width:20px;height:20px;}');__ci.document.writeln('input.b {border: 1px solid #CCCCCC;background-color:#EFEFEF;width:100%;height:20px;}');__ci.document.writeln('-->');__ci.document.writeln('<\/style>');__ci.document.writeln('<\/head>');__ci.document.writeln('<body>');__ci.document.writeln('<\/body>');__ci.document.writeln('<\/html>');__ci.document.close();document.writeln('<\/div>');var calendar = new Calendar();//-->
addStudent.java:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'addStudent.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="styles.css">--><script src="js/calendar.js"></script>  </head>    <body>    <form action="doAdd.jsp" method="post">    <table border="1">    <caption>增加学生</caption>    <tr>    <td align="center">姓        名  </td>    <td width="50"><input type="text" name="name" style="height: 27px; width: 319px; "/></td></tr>    <tr>    <td width="50" align="center" >出 生 年 月 </td>    <td><input type="text" name="birthday" style="height: 27px; width: 319px;" onclick="new Calendar().show(this) "/></td></tr>    <tr>    <td width="50" align="center">成            绩</td>    <td><input type="text" name="score" style="height: 27px; width: 319px;"/></td></tr>    <tr><td colspan="2" align="center"><input type="submit" value="确定" /><input type="reset" value="取消"/></td>        </table>    </form>  </body></html>

doAdd.jsp:

<%@page import="cn.sdut.po.Student" %><%@page import="cn.sdut.dao.StudentDao"%><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'doAdd.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="styles.css">-->  </head>  <%  request.setCharacterEncoding("UTF-8");  String name=request.getParameter("name");  String birthday=request.getParameter("birthday");  String score1=request.getParameter("score");  float score=Float.parseFloat(score1);    Student stu=new Student();  stu.setName(name);  stu.setBirthday(birthday);  stu.setScore(score);  <pre name="code" class="html"><%@page import="cn.sdut.dao.StudentDao"%><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'doDelete.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="styles.css">-->  </head>    <body>   <%     //1 获得客户端数据     int id=Integer.parseInt(request.getParameter("id"));          //2 利用StudentDao类的delStudent(id)方法删除     StudentDao dao=new StudentDao();     int result=dao.del(id);          //3 回到main.jsp    %>    <jsp:forward page="index.jsp"></jsp:forward>  </body></html>

doDelete.jsp:

<%@page import="cn.sdut.dao.StudentDao"%><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'doDelete.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="styles.css">-->  </head>    <body>   <%     //1 获得客户端数据     int id=Integer.parseInt(request.getParameter("id"));          //2 利用StudentDao类的delStudent(id)方法删除     StudentDao dao=new StudentDao();     int result=dao.del(id);          //3 回到main.jsp    %>    <jsp:forward page="index.jsp"></jsp:forward>  </body></html>

doUpdate.jsp:

<%@page import="cn.sdut.dao.StudentDao" %><%@page import="cn.sdut.po.Student" %><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'doUpdate.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="styles.css">-->  </head>  <%  request.setCharacterEncoding("utf-8");  int id=Integer.parseInt(request.getParameter("id"));  String name=request.getParameter("name");  String birthday=request.getParameter("birthday");  String score1=request.getParameter("score");  float score=Float.parseFloat(score1);Student stu=new Student();stu.setId(id);stu.setName(name);stu.setBirthday(birthday);stu.setScore(score);StudentDao studentDao=new StudentDao();studentDao.update(stu);   %><jsp:forward page="index.jsp"></jsp:forward>    <body>  </body></html>
index.jsp:

<pre name="code" class="html"><pre name="code" class="html"><%@page import="cn.sdut.dao.StudentDao"%><%@page import="cn.sdut.po.Student"%><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'index.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="styles.css">-->  </head>  <%  StudentDao studentDao=new StudentDao();  List<Student> list=studentDao.queryAll();  int i=1;   %>    <body>   <table border="1">   <caption>学生表</caption>   <tr>   <td>序号</td>   <td>姓名</td>   <td>出生年月</td>   <td>成绩</td>   <td>操作</td>   </tr>   <%   for(Student stu:list){    %>    <tr>    <td><%=i++ %>    </td>    <td><%=stu.getName()%></td>    <td><%=stu.getBirthday()%></td>    <td><%=stu.getScore()%></td>    <td><a href="updateStudent.jsp?id=<%=stu.getId()%>">修改</a>    <a href="doDelete.jsp?id=<%=stu.getId()%>">删除</a>    </td>    </tr>    <%} %>   </table>   <a href="addStudent.jsp">增加学生</a>  </body></html>



updateStudent.java:

<%@page import="cn.sdut.po.Student" %><%@page import="cn.sdut.dao.StudentDao" %><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'update.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="styles.css">--><script src="js/calendar.js"></script>  </head> <%       //1 从客户端接收id       int id=Integer.parseInt(request.getParameter("id"));              //2 利用StudentDao类queryStudentById方法得到Student对象  StudentDao studentDao=new StudentDao();  Student stu=studentDao.queryStudentById(id);   %>  <body><form action="doUpdate.jsp" method="post"><table><caption>修改学生信息</caption><tr><td>姓名</td><td><input type="text" name="name" value="<%=stu.getName()%>"/></td></tr><tr><td>出生年月</td><td><input type="text" name="birthday"  value="<%=stu.getBirthday()%>" onclick="new Calendar().show(this)"/></td></tr><tr><td>成绩</td><td><input type="text" name="score" value="<%=stu.getScore()%>"></td></tr><tr><td colspan="2"><input type="submit" value="确定" /><input type="reset" value="取消"/></td></table><input type="hidden" name="id" value="<%=stu.getId()%>"/></form> </body></html>

/注意SQL不适用字符串拼接时,String sql="update goods set id=?,goodsname=?,price=?,size=?,color=?,number=? where id=?";

注意中间是逗号,注意有两个id












 

0 0