飘灵儿 发表于 2015-1-18 11:55:15

JAVA教程之Beginner: Using Servlets to display,...

学习JAVA的目的更多的是培养自身的工作能力,我觉得工作能力的一个核心就是:独立思考能力,因为只有独立思考后,才会有自己的见解servletUpdatingrecordsintheDatabasewithJavaServlets.

Overview:

Thisarticleisnextintheseriesofarticlesaboutselecting,inserting,updatinganddeletingrecordsfromthedatabaseusingJDBC.Inthisarticlewewilllearnhowtoupdaterecordsinthedatabase.IfyouhavefollowedmyearlierarticleaboutInsertingrecordsintheDatabasethenthisarticleisnotgoingtobedifficultatall.90%ofthecodewillbesame.SoifyouhaventreadthatarticlethenIwillsuggestthatyougothroughthatarticlebeforestartingthisoneasquiteafewimportantthingshavebeenexplainedindetailthere.

HowtoUpdateRecords?

ToupdaterecordsinthedatabasewewillbeusingthesamePreparedStatementclassweusedbeforeforinsertingrecords.AlthoughwecanupdaterecordsusingtheStatementclass,theupdateoperationislessefficientandnotoptimizedatall.PreparedStatementfillsthatgapandletsusbuildSQLquerieswhicharecompiledandthusmoreefficient.

PreparedStatement:

ThisclasslikeotherJDBCclasseswehavebeendiscussingispresentinthejava.sqlpackage.ThisishowyougethandleonaPreparedStatementobject:

Stringsql="UPDATENamesSETfirst_name=?,last_name=?WHEREID=?";

//conisConnectionobject

PreparedStatementps=con.prepareStatement(sql);

Connection.prepareStatement()returnsareferencetothePreparedStatementobject.TheonlyargumenttotheConnection.prepareStatement()methodisanSQLstatementcontainingoptional?(questionmark).

Youshouldput?marksinthestatementwhereyouaregoingtoputorchangethevalues,forexampleinmyexampleaboveIplaced?marksatthreeplaceswhereIwillputdifferentvaluesdependingonthevaluesenteredbytheuser.

Sohowtosetthevaluesof?parameters.YousetthevaluesbyusingasetXxx()methodsofPreparedStatementclass.setXxx()areover25methodswhosesyntaxissetObject(intparamIndex,Objecto)whereparamIndexisthenumberof?markfromlefttorightintheSQLstatement.ForexamplewewillusesetString(1,value1)andsetString(2,value2)methodstosetthevalueofbothparameterstotwodifferentvalues.AndsetInt(3,value3)tosetthevalueofthird?marktovalue3.

ps.setString(1,"FirstName");
ps.setString(2,"LastName");
ps.setId(3,1);
ps.executeUpdate();

OncetheparametersaresetinthePreparedStatementobject,weexecutethequeryusingPreparedStatement.executeUpdate()method.YoushouldusePreparedStatement.executeUpdate()forupdate,UPDATEandDELETESQLqueriesandPreparedStatement.executeQuery()foranySQLstatementthatreturnsrecords.

OnthenextpagewemakeuseofPreparedStatementobjecttodevelopauserFormpageinwhichausercanupdatehisfirstandlastnamesandthenwhenhepressesthesubmitbuttontheexistingrecordisupdateedinthedatabaseusingthemethodswejustdiscussed.

UpdateServlet:

CreateanewUpdateServlet.javafileinthe/APP_NAME/WEB-INF/classes/com/stardeveloper/servlets/db/folder.Note/APP_NAME/isthepathofyourapplicationwithinyourapplicationserver,inTomcat4.0/APP_NAME/willbe/CATALINA_HOME/webapps/star/wherestaristhenameoftheapplication.

CopyandpastethefollowingcodeintotheUpdateServlet.javafile:

packagecom.stardeveloper.servlets.db;

importjava.sql.*;
importjava.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;

publicclassUpdateServletextendsHttpServlet{

publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres)
throwsServletException,IOException{

res.setContentType("text/html");
PrintWriterout=res.getWriter();

out.print("<html><body>");

//connectingtodatabase

Connectioncon=null;
Statementstmt=null;
ResultSetrs=null;

try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:odbc_exmp");
stmt=con.createStatement();

//displayingrecords

rs=stmt.executeQuery("SELECT*FROMNames");

out.print("<formaction="");
out.print(req.getRequestURI());
out.print(""method="post">");
out.print("<inputtype="hidden"name="id"");
out.print("value="0">");
out.print("<inputtype="submit"value="">");
out.print("DisplayRecords<br><br>");
out.print("First&LastNames:<br><br>");

while(rs.next()){

out.print("<formaction="");
out.print(req.getRequestURI());
out.print(""method="post">");
out.print("<inputtype="hidden"");
out.print("name="id"value="");
out.print(rs.getObject(1).toString());
out.print("">");
out.print("<inputtype="text"");
out.print("name="first"value="");
out.print(rs.getObject(2).toString());
out.print("">");
out.print("<inputtype="text"");
out.print("name="last"value="");
out.print(rs.getObject(3).toString());
out.print("">");
out.print("<inputtype="submit"");
out.print("value="">");
out.print("UpdateRecord<br>");
out.print("</form>");
}

}catch(Exceptione){
thrownewServletException(e);
}finally{
try{
if(rs!=null){
rs.close();
rs=null;
}
if(stmt!=null){
stmt.close();
stmt=null;
}
if(con!=null){
con.close();
con=null;
}
}catch(SQLExceptione){}
}

out.print("</pre></code>");
out.print("<p"><ahref="");
out.print(req.getRequestURI());
out.print("">Back</a></p>");

out.print("</body></html>");
out.close();
}

publicvoiddoPost(HttpServletRequestreq,HttpServletResponseres)
throwsServletException,IOException{

res.setContentType("text/html");
PrintWriterout=res.getWriter();

out.print("<html><body>");

out.print("<code><pre>");
out.print("<fontcolor=green>ID        ");
out.println("FirstName        LastName
</font>");

//receivingparameters

Stringfirst=req.getParameter("first").trim();
Stringlast=req.getParameter("last").trim();
intid;
try{
id=Integer.parseInt(req.getParameter("id").trim());
}catch(NumberFormatExceptione){
thrownewServletException(e);
}

booleanproceed=false;

if(first!=null&&last!=null)
if(first.length()>0&&last.length()>0)
proceed=true;

//connectingtodatabase

Connectioncon=null;
Statementstmt=null;
ResultSetrs=null;
PreparedStatementps=null;

try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:odbc_exmp");

Stringsql="UPDATENamesSETfirst_name=?";
sql+=",last_name=?WHEREID=?";
ps=con.prepareStatement(sql);
stmt=con.createStatement();

//updatingrecords

if(proceed){
ps.setString(1,first);
ps.setString(2,last);
ps.setInt(3,id);
ps.executeUpdate();
}

//displayingrecords

rs=stmt.executeQuery("SELECT*FROMNames");
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print("        ");
out.print(rs.getObject(2).toString());
out.print("                ");
out.print(rs.getObject(3).toString());
out.print("
");
}


}catch(Exceptione){
thrownewServletException(e);
}finally{
try{
if(rs!=null){
rs.close();
rs=null;
}
if(stmt!=null){
stmt.close();
stmt=null;
}
if(ps!=null){
ps.close();
ps=null;
}
if(con!=null){
con.close();
con=null;
}
}catch(SQLExceptione){}
}

out.print("</pre></code>");

out.print("<p"><ahref="");
out.print(req.getRequestURI());
out.print("">Back</a></p>");

out.print("</body></html>");
out.close();
}
}
Startyourapplicationserverandpointyourbrowsertohttp://localhost:8080/star/servlet/com.stardeveloper.servlets.db.UpdateServlettoseetheServletonyourcomputer.Toseethedemopleasemoveontothelastpageofthisarticle.

ForexplanationofUpdateServletcodeabove,pleaseproceedtothenextpage.

Explanation:

NoticethatweareusingthesameAccessdatabasewebuiltintheDisplayingRecordsfromtheDatabasearticlewiththeDSNofodbc_exmp.PleaseconsultthatarticleformoredetailsonthedatabaseandNamestable.

OurUpdateServletclassextendsfromHttpServletclassandoverridestwomethods;doGet()anddoPost().IndoGet()weconnecttothedatabaseandretrieveallthevaluesfromtheNamestableanddisplayaFormtotheuserwithtwoinputfieldscontainingfirstandlastnamesalongwithasubmitbuttonforupdatingrecords.

Stringfirst=req.getParameter("first").trim();
Stringlast=req.getParameter("last").trim();
intid;
try{
id=Integer.parseInt(req.getParameter("id").trim());
}catch(NumberFormatExceptione){
thrownewServletException(e);
}
booleanproceed=false;

if(first!=null&&last!=null)
if(first.length()>0&&last.length()>0)
proceed=true;
IndoPost()weretrievethefirstandlastnamevaluesenteredbytheuserusingHttpServletRequest.getParameter()method.

Usingadoubleifstatementwemakesurethatwearenotenteringnullvaluesintothedatabase.Ifuserhasenteredbothfirstandlastnamethenweproceed.

Connectioncon;
Statementstmt;
ResultSetrs;
PreparedStatementps;
Wedeclaretheobjectswearegoingtousetointeractwiththedatabase.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:odbc_exmp");
WeloadtheSunsJDBC/ODBCdriverandestablishconnectiontoourdatabaseusingtheDSNodbc_exmp.NoticethatthisisthesamedatabaseweusedinDisplayingRecordsfromtheDatabase.PleaseconsultthatarticletoseethestepsofcreatingsuchadatabaseandassigningDSN.

Stringsql="UPDATENamesSETfirst_name=?";
sql+=",last_name=?WHEREID=?";
ps=con.prepareStatement(sql);
stmt=con.createStatement();
WebuildtheSQLstatementwhichwewillusetoinsertrecordsintothedatabase.NextwecreatethePreparedStatementandStatementobjectsusingConnectionobjectsmethods.

if(proceed){
ps.setString(1,first);
ps.setString(2,last);
ps.setInt(3,id);
ps.executeUpdate();
}
Nextwesetthethree?markparametersinourPreparedStatementobjectandupdatetherecordusingPreparedStatement.executeUpdate()method.

rs=stmt.executeQuery("SELECT*FROMNames");
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print("        ");
out.print(rs.getObject(2).toString());
out.print("                ");
out.print(rs.getObject(3).toString());
out.print("
");
}
WecreateourResultSetobjectbyexecutingtheSELECTquery.Wetheniteratethroughtherecordsanddisplayittotheuser.Noticethatthenewrecordwejustinsertedwillalsobevisibletotheuserduringthisiteration.

if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(ps!=null)
ps.close();
if(con!=null)
con.close();
Closealltheobjectsthatwecreated.

Ihaventmentionedtry..catchstatementsthatweusedtocatchdifferentexceptionsthatmaybethrownduringopeningandclosingofdatabaseconnection.

OnthenextpageIsumupwhatwelearnedinthisarticle.

Summary:

InthisstepbysteptutorialwelearnedwhatisPreparedStatementclassandhowtouseittobuildfastSQLstatements.WethenmovedforwardtobuildasimpleFormapplicationinwhichwedisplayfirstandlastnamesofalltheusersinourdatabaseallowingausertoupdatehisfirstandlastnameandthesevaluesarethenupdatedinthedatabase.Afterthatallthenamesaredisplayedtouser.Notethatthisapplicationassumesthatyouhavealreadybuilttheodbc_exmp.mdbAccessdatabasewithaDSNofodbc_exmpandcontainsasingletableNameswiththreefieldsID,first_nameandlast_namewhereIDistheprimarykey.TolearnmoreaboutthisdatabasereadDisplayingRecordsfromtheDatabasearticle.

ThedriverweusedwasJDBC/ODBCdriver,thisdrivercomeswithJavaDevelopmentKitsoyoudontneedtodownloadandinstallitseparately.Formoreinformationonhowwebuilttheodbc_exmp.mdbdatabaseandwhataredifferenttypesJDBCdriverspleaseconsulttheabovementionedarticle.

IfyouhavefollowedmyInsertingRecordsintotheDatabasearticlethenyoumusthavenoticedthattheonlyrealchangethatisrequiredtoupdaterecordsinsteadofinsertingistochangetheSQLqueryfromINSERTtoUPDATE,soyouhavegotonlyonelinetochange.

Thatsitforthisarticle.KindlypostyourquestionsintheForum.Thanks.

Thereisnoassociatedmaterialfordownload
Clickheretoseethedemo
 

先说优点,首先和C,C++这些语言比起来,java很简单,去掉指针的java,非常好理解,自动垃圾回收机制也很好,自从JDK1.5推出以后,性能上又有了很大提高。

柔情似水 发表于 2015-1-21 17:02:19

所以现在应用最广泛又最好学的就是J2EE了。 J2EE又包括许多组件,如Jsp,Servlet,JavaBean,EJB,JDBC,JavaMail等。要学习起来可不是一两天的事。那么又该如何学习J2EE呢?当然Java语法得先看一看的,I/O包,Util包,Lang包你都熟悉了吗?然后再从JSP学起。

分手快乐 发表于 2015-1-24 16:37:43

是一种简化的C++语言 是一种安全的语言,具有阻绝计算机病毒传输的功能

第二个灵魂 发表于 2015-2-2 10:57:28

Java 编程语言的风格十分接近C、C++语言。

简单生活 发表于 2015-2-4 01:42:30

在全球云计算和移动互联网的产业环境下,Java更具备了显著优势和广阔前景。

再见西城 发表于 2015-2-8 16:42:36

其实说这种话的人就如当年小日本号称“三个月拿下中国”一样大言不惭。不是Tomjava泼你冷水,你现在只是学到了Java的骨架,却还没有学到Java的精髓。接下来你得研究设计模式了。

愤怒的大鸟 发表于 2015-2-25 20:52:47

Java自面世后就非常流行,发展迅速,对C++语言形成了有力冲击。Java 技术具有卓越的通用性、高效性、平台移植性和安全性,广泛应用于个人PC、数据中心、游戏控制台

飘灵儿 发表于 2015-3-1 18:38:07

关于设计模式的资料,还是向大家推荐banq的网站 http://www.jdon.com/,他把GOF的23种模式以通俗易懂的方式诠释出来,纯Java描述,真是经典中的经典。

小女巫 发表于 2015-3-1 19:41:28

J2SE开发桌面应用软件比起 VC,VB,DEPHI这些传统开发语言来说,优势好象并不明显。J2ME对于初学者来说,好象又有点深奥,而且一般开发者很难有开发环境。

若天明 发表于 2015-3-4 03:06:15

一般学编程语言都是从C语开始学的,我也不例外,但还是可能不学过程语言而直接学面向对象语言的,你是刚接触语言,还是从C开始学比较好,基础会很深点,如果你直接学习JAVA也能上手,一般大家在学语言的时候都记一些语言的关键词,常有的包和接口等。再去做逻辑代码的编写,以后的学习过程都是从逻辑代码编写中提升的,所以这方面都是经验积累的。你要开始学习就从

谁可相欹 发表于 2015-3-11 15:22:34

任职于太阳微系统的詹姆斯·高斯林等人于1990年代初开发Java语言的雏形,最初被命名为Oak,目标设置在家用电器等小型系统的程序语言

山那边是海 发表于 2015-3-16 04:55:40

Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。

冷月葬花魂 发表于 2015-3-21 01:12:58

关于设计模式的资料,还是向大家推荐banq的网站 http://www.jdon.com/,他把GOF的23种模式以通俗易懂的方式诠释出来,纯Java描述,真是经典中的经典。

金色的骷髅 发表于 2015-3-21 02:22:14

Java是一个纯的面向对象的程序设计语言,它继承了 C++语言面向对象技术的核心。Java舍弃了C ++语言中容易引起错误的指针(以引用取代)、运算符重载(operator overloading)

只想知道 发表于 2015-3-26 16:45:46

Java 不同于一般的编译执行计算机语言和解释执行计算机语言。它首先将源代码编译成二进制字节码(bytecode),然后依赖各种不同平台上的虚拟机来解释执行字节码。从而实现了“一次编译、到处执行”的跨平台特性。

海妖 发表于 2015-3-29 21:11:16

所以现在应用最广泛又最好学的就是J2EE了。 J2EE又包括许多组件,如Jsp,Servlet,JavaBean,EJB,JDBC,JavaMail等。要学习起来可不是一两天的事。那么又该如何学习J2EE呢?当然Java语法得先看一看的,I/O包,Util包,Lang包你都熟悉了吗?然后再从JSP学起。

活着的死人 发表于 2015-3-29 23:04:47

是一种使网页(Web Page)产生生动活泼画面的语言

再现理想 发表于 2015-4-10 16:34:04

如果你学过HTML,那么事情要好办的多,如果没有,那你快去补一补HTML基础吧。其实JSP中的Java语法也不多,它更象一个脚本语言,有点象ASP。

深爱那片海 发表于 2015-4-14 11:50:03

Java 编程语言的风格十分接近C、C++语言。

变相怪杰 发表于 2015-4-18 04:50:13

其实说这种话的人就如当年小日本号称“三个月拿下中国”一样大言不惭。不是Tomjava泼你冷水,你现在只是学到了Java的骨架,却还没有学到Java的精髓。接下来你得研究设计模式了。
页: [1] 2
查看完整版本: JAVA教程之Beginner: Using Servlets to display,...