JSP ----- step by step

xiaoxiao2021-03-06  59

Client (Client) Conceptual Server of Server: Generally, Server Different (Hardware Server, Software Server) Hardware Server: Refers to a relative PC, performance and stability are better, using special Hardware computer. Software Server: It is a popular saying that a service software is installed and a machine that provides the corresponding service, we call it a server. Service software has many kinds, common: WWW services software: PWS, IIS, Apachej2ee middleware application server: WebSphere, SilverstreamJSP engine (weak WWW service): Tomcat, Resin, WebLogic, JRunsmtp, POP3: IIS SMTP , Exchange, Lotus DominoftP: IIS comes with the client: Relative to the server, it is a party to enjoy some kind of service, called the client. However, if you want some kind of service, you must install the appropriate software, such as (IE / Netscape, Outlook / Foxmail, CuteftP) data type has the following four: INT length data types are: Byte (8bits), Short (16bits) INT (32BITS), long (64bits), Float length data types are: single precision (32bits float), double precision (64bits double) Boolean type variable with: Ture, falsechar data types are: Unicode characters, 16-bit Corresponding class type: Integer, Float, Boolean, Character, Double, Short, Byte, Long conversion Principle: From low precision to high precision Byte, Short, Int, Long, Float, Double, CHAR Note: Two CHAR type operations Automatically converted to int type; when char and other types, it will be automatically converted to int type, then do other types of automatic conversion basic type to class type conversion forward conversion: through class wrapper to New Out of a new type of variable in Integer a = new integer (2); reverse conversion: convert INT b = a.intValue () through class wrapper (); class type to string conversion forward conversion: for each class Both are the subclasses of the Object class, and all Object classes have a toString () function, so through the toString () function to translate reverse conversions: By the class wrapper New Out a new class type variable EG1: INT i = INTEGER.VALUEOF ("123"). INTVALUE () Description: The above example is converted a string into an Integer object, and then call the IntValue () method of this object returns its corresponding int value. EG2: float f = float.valueof ("123"). FLOATVALUE () Description: The above example is converting a string into a float object, and then call the FLOATVALUE () method of this object returns its corresponding float value. EG3: Boolean B = Boolean.Valueof ("123"). BooleanValue () Description: The above example is converting a string into a Boolean object, and then call the BooleanValue () method of this object returns its corresponding Boolean value.

EG4: DOUBLE D = Double.Valueof ("123"). DoubleValue () Description: The above example is converting a string into a Double object, and then call the DoubleValue () method of this object returns its corresponding Double value. Eg5: long l = long.valueof ("123"). LongValue () Description: The above example is converted a string into a long object, then call the longValue () method of this object returns its corresponding long value. EG6: Char = Character.Valueof ("123"). CHARVALUE () Description: The above example is converting a string into a CHARACTER object, and then call the CHARVALUE () method of this object returns its corresponding char value. Basic types of conversion forward conversion to strings: int a = 12; string b; b = a ""; reverse conversion: through class wrapper EG1: INT i = integer.parseint ("123") Description: This method can only be applied to strings to convert to integer variables EG2: float f = float.valueof ("123"). FLOATVALUE () Description: The above example is converting a string into a float object, and then call this object The floatvalue () method returns its corresponding FLOAT value. EG3: Boolean B = Boolean.Valueof ("123"). BooleanValue () Description: The above example is converting a string into a Boolean object, and then call the BooleanValue () method of this object returns its corresponding Boolean value. EG4: DOUBLE D = Double.Valueof ("123"). DoubleValue () Description: The above example is converting a string into a Double object, and then call the DoubleValue () method of this object returns its corresponding Double value. Eg5: long l = long.valueof ("123"). LongValue () Description: The above example is converted a string into a long object, then call the longValue () method of this object returns its corresponding long value. EG6: Char = Character.Valueof ("123"). CHARVALUE () Description: The above example is converting a string into a CHARACTER object, and then call the CHARVALUE () method of this object returns its corresponding char value. My future is not a dream, Blueidea Web Teammoderator Of Blueidea Developer Forum, confidence, football kid points: 8546 Posting: 2593 From: AC Milan Registration: 2002-07-16 Posted on 2003-06-10 23:19:19

JSP basic directive ------ 1 - Script tag declares that the language will be used: <% @. Page language = "java"%> Indicate the JSP instruction, indicating that the following script code will be in the Java language syntax reference package Class: <% @ .Page Import = "java.util. *"%> Indicates the class declaration variable to use to java.util package: <%! Int count = 0;%> declare a plastic variable, and assign Initial 0 declaration method: <%! Int show (int value}%> Output expression: <% = 2 * x%> Direct output expression value, x must be previously declared Variables (no semicolons), equivalent to the <% =%> JSP comment in ASP: <% - here is comments -%> indicates a JSP comment, and it will be ignored at the server side, nor is it html Note, can't see when viewing the source code at the client. Contains another JSP file: <% jsp: include Page = "Another: JSP"%> Indicates the content of the contents of another file Another.jsp in the current page: <% for (int i = 0, i <10 , I ) // JSP's body section OUT.PRINTLN (i "
");%> 2. Instruction --- JSP instruction has Page, include two Page instructions (attribute: 6) Language Properties: < @ page language = "java"%> // Indicates the language IMPORT attribute used: <@ page import = "java.util. *"%> // Load package Note: In Java, you want to load multiple packages , Use Import to refer to, and separated by a semicolon; in JSP, if multiple packages are specified with an Import, separated by commas. Such as: <% @ page import = "java.util. *, Java.lang. *"%> Can also <% @ Page Import = "java.util. *"%> <% @ Page import = "java.lang . * "%> (But does not advocate this use, irregular.) Session attribute: <@ page session =" true or false "%> Default SESSION value TRUE such as: <% @ Page session =" TRUE "%> <% IF (session.getvalue (" name ") == null) session.putValue (" name "," 123456 "); else session.putValue (" name ", session.getvalue (" name ") "1");%> <% out.println (Session.getValue ("name")));%> If session = "false", the compile error will occur.

ErrorPage Properties: When the current page program is wrong, the program specified by ErrorPage is handled: <@ @ er = "ErrorPage.jsp"%>, Test.jsp: <% @ Page ErrorPage = "ErrorPage.jsp" @ > <%! int i = 0;%> <% = 7 / i%> errorpage.jsp: <% @ page isrrorpage = "true" @> <% = exception%> Run Test.jsp, will be seen 0 except error message. IserrorPage Properties: Indicates whether the current program is an exception handler for another program. Whether it is set, the exception is directed to the current program, and the problem is whether the current program can get this exception. If set to True, an exception of the exception will occur, and you can use it in your code; if false is set, using the Exception program will be erroneous at compile time. Such an error will appear to false, the following error will occur: Error: 500UNABLE TO Compile Class for JSP Write: <% @ Page ISERRPAGE = "True" @> ContentType Property: Specify the type of MIME and JSP files Character encoding method, they all transmit it to the client. Mime types are: Text / Plain, Text / HTML (Default Type), Text / HTML, Image / GIF, Image / JPEG, Image / JPEG Default Character Coding Method: ISO8859-1InClude instructions: Yes to current Insert a static file in the page, this file may be an HTML file, a JSP file, or another text file, the format is as follows: <% @ include file = "incrude.inc"%> such as: native.jsp: Native File
<% @ include file = "incrude.inc"%> native file end.
incrude.incianclude file start here.
<%! String str = " Here Is Include's Context! ";%> <% Out.pringln (STR "
");%> include file end end.
Run native.jsp, the results are as follows: Native File Start Here.include File Start Here .Here is incline's context! Incrude file end end end end. Note: Because the include.inc file is inserted when compiling, then only change the contents of the incrude.inc file, not to modify the original JSP page, obtained The result will still be the previous result. (Because the JSP engine judged that the JSP page is not changed, the existing bytecode is directly executed, and the source code is recompiled, so that the modification of the incrude is not reflected.)

My future is not a dream Blueidea Web Teammoderator Of Blueidea Developer Forum confidence Soccer Kid Points: 8546 Posting: 2593 From: AC Milan Registration: 2002-07-16 Posted on 2003-06-10 23:32:58

The script JSP script is the code block written in the scripting language specified by the Page Instruction Language property, and the functions that need to be completed with JSP are mainly implemented. The basics currently used is Java language. The code block must be fully compliant with Java syntax, but can be used with HTML text. In fact, no matter what, it will be converted to servlet, they are the same in servlet. The: output of the first blank line 5, and then outputs "hello" right: <% for (int i = 0; i <5; i )%>
<%;%> hello
error :( One line of BR; one line hello) =============== <% for (int i = 0; i <5; i )%>
Hello error equivalent: <% For (int i = 0; i <5; i ) {%>
Hello <%}%> Action (<% jsp%>) JSP provides action instructions with: include, forward, usebean, getproperty, setPropertyInClude action JSP adds another file to the current page. Forward action puts the current page on another page, the address seen by the client is the address of the A page, and the actual content is indeed the contents of the B page. . , here is aa. here is bb. pay attention : Before using Forward, there is no content that has been output to the client, otherwise the exception will occur. UseBean action This action is used to generate a bean component and set its ID number and use range action for bean id =" beanname ": Define Generating bean components Name, cannot be renamed and the value of scope is also the same, otherwise the JSP engine will determine the one you created first. Scope = "Page | Request | Session | Application": Defines the BEAN's activity range, beans can only be used in the range it define, will not access it outside it. JSP is set for it: Page: BE: BEAN's default Using Range REQUEST: A JSP file for any same request until the page is running back to a response or before this, before this. If the redirection, links, etc. are turned to another file.

You can also affect any changes to this bean property in the session cycle by using the Request Object to Access Bean, such as Request.getTribute (BeanName): During the survival period of the entire Session Another page, another Request call to this bean. However, you must specify session = true in the file that created this bean. Application: During the living cycle of the entire Application, any changes to this bean property in the Application cycle will affect this application in this application, another Request, and another session call to this bean. Class = "package.class": A bean according to the class presentation with the class attribute, where the package name must be specified in the class with keyword package. TYPE = "package.class" class = "package.class" type = "package.class" beanname = "{package.class | <% = express%>}" type = "package.class" such as: tt.jsp < JSP: usebean id = "student" scope = "page" class = "mime.student" /> <% = student.getname ()%>
<% student.setname ("WLL");%> student. javapackage mine; public class student {long classno; String name; int age; Boolean sex; public student () {classno = 12345; name = "aaaa"; age = 21; sex = true;} public long getClassno () {return classno;} public void setClassno (long no) {this.classno = no;} public String getName () {return name;} public void setName (String name) {this.name = name;} public int getAge () {return PUBLIC VOID Setage (Int Age) {this.age = age;} public boolean getsex () {return sex;} public void setsex (boolean sex) {this.sex = sex;}} My future is not a dream Blueidea Web Teammoderator Of Blueidea Developer Forum Confident Soccer Kid Points: 8546 Posting: 2593 From: AC Milan Registration: 2002-07-16 Posted on 2003-06-10 23:36:24

Note: When Scope = "Page", run the test.jsp file, the initial value of Name is "AAAA". Although reset to "WLL" in the JSP file, the Test.jsp file is run when the "AAAA" Scope = "Session" is still refreshed, and the initial value of Name is "AAAA". Although it is reset to "WLL" in the JSP file, it is still "WLL" after refresh, as long as this window is not closed, any refresh or open a new window, output "WLL". Until all windows are closed, run the Test.jsp file, the output will be "AAAA" for the initial value. When Scope = "Application", run the test.jsp file, the initial value of Name is "AAAA". Although it is reset to "WLL" in the JSP file, it is still "WLL" after refresh, as long as this window is not closed, any refresh or open a new window, output "WLL". Even if all windows are closed, run the test.jsp file, the output is still "WLL". Unless the service is turned off again, then run the test.jsp file, the output of the Name is the initial value "AAAA". When Scope = "Request", the new one file TEST1.JSP content is the same as Test.jsp. First run the Test.jsp file in your browser, the value of the output Name is the initial value "AAAA". The Test1.jsp file is run in the browser, and the output is "WLL" because they are the same REQUEST.

GetProperty action: Use to return an attribute value of the bean component that has been created: name: Value of the value when creating a bean component with usebean: specify Which attribute is obtained, for example, the properties value of the Student component in the precedent: equivalent: <% = student.classno%> output is: 12345 AAAA 21SetProperty action: Used to set an attribute value of a BEAN component that has been created: name: Value of the value when creating a bean component with UseBean: Indicates the property name value to set the attribute value: for setting Attribute values, such as: The attribute set in the pre-example, attribute set in SetProperty equivalence: <% student.age = 33;%> output results: 56789 BBBB 33 My future is not a dream Blueidea Web Teammoderator Of Blueidea Developer Forum confidence Soccer Kid Points: 8546 Posting: 2593 From: AC Milan Registration: 2002-07-16 Posted on 2003-06-10 23:49:17

Internal object OUT (outputs various data types to the client) Important method: Out.print (Type) or Out.println: Link Output Out.Newline (): Output a wrap symbol Out.Flush (): Output buffer Data out.close (): Turn off output flow out.clearbuffer (): Clear data in the buffer and write data to the client out.clear (): Clear data in the buffer, but do not write data To the client out.getBuffersize (): Get the size of the buffer, the size of the buffer can be used <% @ page buffer = "size"%> Set Out.getRemaining (): Get the size of the space where the buffer does not use Out.isautoflush (): Return to the Boolean value, if Auto Flush returns true, otherwise returns false. Whether Auto Fush We can use% @ page is autoflush = "true / false"% to set Note: If the Chinese display problem is directly assigned Chinese string, <% @ page contentType = "text / html; charSet = GB2312"%> It can be displayed normally. But you can't convert the internal code with a getStr (string name) function or a similar function, otherwise Chinese cannot be displayed normally. If the Chinese string passed through the request, you must convert the internal code with a getStr (String Name) function or a similar function, otherwise Chinese cannot be displayed normally. Such as: string aa = Str; Byte [] aa = aa.getbytes ("ISO8859-1"); string bb = new string (aa); different platforms, different server JSP Chinese issues are different, Self-test. Request (Acceptable client input) effect: Mainly used to accept data transmitted to the server side via HTTP protocol connection. Method: getCookies (): Returns the Cookie object of the client, the result is a cookie array getHeader (String name): Get the transfer file header information defined by the HTTP protocol, such as: Request.getHeader ("User-Agent") Return to Client Browser The version number, type getAttribute (String Name): Returns Name specified attribute value, if there is no specified property, return null values ​​(NULL).

GetAttributeNames (): Returns the name of all attributes of the Request object, the result set is an instance of an Enumeration class GetHeadernAmes (): Returns the name of all Request Header, the result set is an Enumeration class instance GetHeaders (String) Name): Returns all values ​​of the Request Header of the specified name, the result set is an Enumeration class instance getMethod (): Getting the client to send data to the server, there is Get, Post, Put, etc. GetParameter (String) Name): Get the client to send the parameter value to the server side, which is specified by Name Get parameternames (): Get all the parameter names to the server side, the result set is an enumeration class instance getParameterValues ​​(String Name): Get the value of the specified parameter get QueryString () get the query string, which transmits getRequesturi (): obtains the client address getServletPath (): Get the client address of the request string by the client. The file path of the script file setttribute (String Name, java.lang.Object O): Set the name of the name to name, which is specified by the Object Type of o GetServerName (): Get the name GetServerPort (): get The port number of the server getRemoteAddr (): Get the client's IP address getRemotehost (): Get the name of the client computer, if it fails, return to the client computer's IP address getProtocol (): Get the client to transfer data to the server. Agreement name, such as HTTP / 1.1Application effect: Once created, unless the server is turned off, otherwise keeps Application.setttribute ("Name", val) method: GetAttribute (String name): Returns the value of the Application object attribute specified by name, this is an Object object GetAttributeNames (): Returns the name of all Application object properties, the result set is an ENUMER ATIONNitParameter (String Name): Returns the initial value of Application Plant Properties, this property is specified by Name GetServerInfo (): Gets the current version of the servlet compiler SetAttribute (String Name, Object Object): Use Object to initialize an attribute, this property is specified by Name. My future is not a dream Blueidea Web Teammoderator Of Blueidea Web Teammoderator Of Blueidea Web TEAMMODERATOR OF BLUEIDEA Web Points: 8546 Posting: 2593 From: AC Milan Registration: 2002-07-16 Posted in 2003- 06-10 23:55:51

Response (Control HTTP Connection) Role: Send data to the client, such as cookie, HTTP file information, etc. Method: AddCookie (cookie cookie): Add 1 cookie object to save the client's user information. This cookie is available in a getCookies () method to get this cookie, such as: <% cookie mycookie = new cookie ("uname", "wsr"); response.addcookie; cookie delmyCookie = New cookie ("MyCookie", NULL; DelmyCookie .SetMaxage (0); DelmyCookie .SetPath (/ "); response.addcookie (DELMYCOOKIE);%> addheader (String name, string value): Add HTTP file header, the header will pass to the client, if the same name Header exists, the original header will be overwritten: String Name: Determine whether the HTTP file header of the specified name exists and returns the Boolean Senderror (INT SC): Error message to the client, such as: 505: server internal error; 404 : The web page cannot be found, such as: response.Senderror (response.sc_no_content); setHeader (String Name, String Value): Set the value of the HTTP file header of the specified name, if this value exists, it will be covered by the new value such as 1: Let the web page all 5 seconds, "Refresh", "5");%> the current dateis: <% = new date ()%>, such as 2: Setting the HTTP header using the Response object <% respternse.setContentType ("Application / PDF"); Response.setHeader ("Content-Disposition", "Attachment; FileName = /" Syntax.pdf / ");%> Sendredirect (" Error.html ") //// Redirection Function Exception (Processing Exceptions and Errors) Role: Processing all incorrections and exceptions occurring during JSP files. Take 3 built-in methods. Note: Must be in the case of <% @ page isrrorpage = "true"%> You can use the Exception object getMessage (): Return Error Message PRINTSTACKTRACE (): Output an error and error in the form of a standard error Tostring (): in the form of strings Returns 1 to anomalous description session (save user information): Save each user's information session.putValue ("name", val) session.getValue ("name") Note: The information saved and retrieved in the session cannot It is the basic data type, but must be the corresponding Object object of Java.

Method: GetAttribute (String Name): Get the properties of the specified name, if the property does not exist, return nulltattributenames (): Returns the first attribute object stored in the Session object, the result set is an instance of an Enumeration class getCreationTime (): Returns the time created by the session object, from January 1, 1970, getId from January 1, 1970: The server will give it a number that will not be repeated, this method returns the number of the current session GetLastAccessedTime. : Returns the time of the current session object last once, returning from the milliseconds of the Since January 1, 1970, getMaxinActiveInterval (): Get the survival time of the session object Removeattribute (String Name): Delete the specified property (including attributes Name, attribute value) SetAttribute (String name, java.lang.Object value): Set the attribute value of the specified name, and store it in the session object, my future is not a dream Blueidea Web Teammoderator Of Blueidea Developer Forum confident Soccer kid Points: 8546 Posting: 2593 From: AC Milan Registration: 2002-07-16 Posted on 2003-06-11 12:21:59

Using the Java Bean component feature: Yes, you can reuse anywhere in the application, other components, documents, Web sites, and application constructor can be reused. JavaBean concept JavaBean is an application interface independent of platform and structure, which itself can ignore internal structures and detail issues, just define their external features and external functions. It has three interfaces that can be developed independently, which is: the properties, methods, and event JavaBeans have two properties of the JSP component: single-value properties, index properties single-value properties: a member variable defined in usual programming, It can only have a data value, the type of this data value can be any data type in Java, including classes, and interfaces. Such as: int counter; Float Tax; String name; DateTime; Note: A special single-value property (Boolean properties), only two allowed values: true, false index properties: equivalent to array, when When you store a batch of data, you need to use index properties. For example: int id []; string name []; method score []; JavaBean method method includes constructor and access methods. Construction method: similar to the constructor in the class (ie, initialize it and its member variable), its method is the same as the class of this JavaBean.

Such as: Package Student; Public class student {int counter; ind id []; string name []; float score []; boolean whiszkid; public student () {id = new int [50]; name = new String [50] Score = new float [50]; counter = 0;}} Access method: Access to the properties defined in the component, including reading and writing (general situation with almost the way to define and use in Java), pay attention to it Name Rules: Read an attribute: getxxx () Rewinds a property: setXXX () Access single-value properties: If the counter single value attribute on the above, its two access methods can be: read attribute value: public int GetCounter {RETURN Counter;} Remote Property: Public void setCounter (int counter) {this.counter = counter;} Access Boolean single-value attribute: The read attribute value uses isxxx () method, such as the above Boolean properties WHIZKID access can be: public boolean iswhizkid () {return whizzid;} Access index properties: Sometimes they want to define several access methods, but their name rules are still the same, such as the above name properties, its reads and Rewriting method You must define this: read an attribute value in the index property: public string getname (int index) {return name [index];} All attribute values ​​in the index properties: public string [] getName () {Return Name;} Rewinding an attribute value in the index property: public void setname (int index, string str) {name [index] = Str;} All attribute values ​​in index properties: public void setname (String [] str) { Name = str ;;} Create a bean written in JSP, actually creates an object of this class. My future is not a dream Blueidea Web Teammoderator Of Blueidea Developer Forum confidence Soccer Kid Points: 8546 Posting: 2593 From: AC Milan Registration: 2002-07-16 Published on 2003-06-11 12:32:49

The work client for the client and the server-side work client can be divided into two parts: First, send a request to the server to send submission to the server side. In the client, check, and the page modification and other function client submit Method client submission method divided by two: GET and POST submitted GET can be delivered only 2KB, and it is clearly transmitted information, all information can be seen in the address bar. POST can deliver a lot of information, encrypted transmission, all information can be invisible in the address bar. POST Submit all POST submission can only be generated in the form: Direct submission (Submit submission), indirect submission (Submit) 1) Direct Submit: Click the Submit button, immediately submit

Note: Submit button has a default event, is to submit Note: Before submission, first return a warning box" Hello "on the screen, if return is true, then the page is submitted; if return is false, the page does not submit. 2) Indirect Submit: means that the click button itself cannot be submitted, and only the submission can be completed by scripts, called indirect submission. Note: At the onclick, you can also be onMousedown, onmouseup, etc. Button is just a normal button, it does not have submission, only After the script specified by ONClick can complete the commit button, execute the function triggered by the onclick event, if the return value is true, otherwise it will be submitted. GET Submit Get Submit Procedure in Form Form and URL 1) 2 generated in Form Added in Form> Enter the URL address in the address bar in all URLs, followed by Parameters http://*.asp? Name = www & agn = 20 On the hyperlink "frame src =" * .asp? Name = www "Name = Frame Name" in the frame name> in the ASP redirect statement "* .asp? Name = WWW "in the client object document: Document.Location =" http: // * .asp? name = www "in the client object Window: WINDOW.Open (" http: // * .asp? name = www ") The method of obtaining the client information is done by the Request object.

The information submitted to the server side is divided into three categories: the first category: client information (including client IP address, port number, host name, submission, etc.) Second category: submitted to the server side by form or URL Information Third Category: Cookie Information Getting Class 1 Information: Request.getHeader ("User-Agent") Returns the version number of the client browser, the type getHeader: Get the transfer file header information defined by the HTTP protocol, Request. getMethod (): Get the method of sending data to the server to the server has GET, POST, PUT and other type request. getRequesturi (): Get the client address request. getServletPath (): get the client request File path of the script file request. GetServerName (): Get the server's name request.getServerport (): Get the server's port number request.getRemoteAddr (): Get the client's IP address request.getRemotehost (): Get the name of the client computer If it fails, return to the client computer's IP address request.getProtocol (): Request.getHeadernAmes (): Returns the name of all Request Header, the result set is an enumeration class instance request.getHeaders (String name) : Returns all values ​​of the Request Header of the specified name, the result set is an Enumeration class instance to obtain the second type of GET information: request. GetQueryString ("Variable name or control name") Get the query string, the The string is transmitted by the client to send the second class POST information to the server side by the client: request.getParameter (String name): Get the client to send the parameter value to the server side, which specifies request.getParameterNames (): Get customers The end is sent to all the parameter names of the server side, and the result set is an instance of an Enumeration class. Request.getParameterValues ​​(String Name): Get all values ​​for specified parameters to get the third class cookie information: Request.getCookies ("cookie variable Name "): Return to the client's cookie object, the result is a CO Okie array My future is not a dream Blueidea Web Teammoderator of Blueidea Web Teammoderator Of Blueidea Developer Forum CHEN SOTS Football Kid Points: 8546 Posting: 2593 From: AC Milan Registration: 2002-07-16 Posted on 2003-06-11 12:42:50

The primary part of the database is for everyone convenient, with Access as an example configuration step: Start - "Settings" - "Control Panel" - "Data Source (ODBC)" - "System DSN" - "Add" - "Select Data Source Driver" - "Complete" - "ODBC Installation Fill in the Data Source Name, click 'OK' -" Complete ". The five elements of the database connection: IP address port number (port number is fundamentally fixed, unless specifically set) means that the corresponding database driver selection database account, password (is assigned to the database) SQL The statement (Send via the Statement object) JDBC principle JDBC is a connection between Java and data. Because the ODBC is written in the C language, communication with C language programs in Java is more difficult, so interface technologies for Java programs and database connections are generated by Java language. JDBC and database connection JDBC is connected to a specific database, which is automatically loaded directly through classes in the JDBC API class library. This library is typically in the Java.sql package, which contain classes for implementing other functions connected to the database, including connecting to the database, transmitting queries, and accepting query results. Detailed introduction of the following four classes: Role: Connection to the database Send SQL statement processing results Connection CN = DriverManager.getConnection ("JDBC: ODBC: Wombat", "Login", "Password"); statement stmt = cn.createstatement ); // Send SQL statement ResultSet RS = Stmt.executeQuery ("SELECT A, B, C from table1"); while (rs.next ()) {INT x = rs.getint ("a"); string s = rs.getstring ("b"); float f = rs.getfloat ("c");} // Processing the result My future is not a dream Blueidea Web Teammoderator Of Blueidea Developer Forum confident Soccer Kid Points: 8546 Posting: 2593 From : AC Milan Registration: 2002-07-16 Posted on 2003-06-11 12:57:52

DriverManager class This class is used to load the driver, and all of its members are static members, so they do not need to instantiate it in the program, and they can access it directly through class names. The DriverManager class is the management of JDBC, which acts on the user and driver loading driver Class.Forname ("Company Name. Database Name. Driver Name), such as: Class.Forname (" Sun.jdbc.odbc.jdbCodbDriver) Establish a connection to load the Driver class and register after the DriverManager class can be used to connect to the database. When the calling driver.manager.getConnection () issues a connection request, DriverManager checks each driver to see if it can establish a connection. Method: Connection getConnection (String URL, String User, String Password) where user and password are the user and password of the login database, the first parameter is pointing to the URL of the database, its format is as follows: JDBC: (Subprotocol) :( Subname) Subprotocol : Sub protocol, specify how database or what to connect to the database Subname: Establish a connection, can be a data source name, or point to an online database such as: The following is a usual driver (JDBC-ODBC bridge driver) ), And even a student data source, an anonymous login example: class.forname ("Sun.jdbc.jdbcodbcDriver"); // Loading the driver string url = "jdbc: odbc: student"; connection CN = DriverManager.getConnection (URL, "Anonymous", "); getConnection (): Returns a connection class object. If successful, this object points to a connection to this database; otherwise, this object will be an empty NullConnection class Connection class to point to the same database. Role: Manage the connection to the database, such as sending queries to the database and receiving query results of the database are based on it; turn off this connection after all tasks with the connection of the database. Method: Statement CreateStatment (): New Statement object, this object can send query information to the database (): Close the connection with the database and release the occupied JDBC resource boolean isclose (): Judgment is still working with the database connection Statement : Statement object is used to send SQL statements to the database. After creating a Statement object After the connection to a specific database, you can send a SQL statement with this connection. The Statement object creates CreateStatement with the Connection method.


New Post(0)