js| Tutorial
//----------------------------------------------------------------------------------------------
Internal objects
Out (various data types are exported to the client)
Important Method:
Out.print (type) or Out.println (type): NewLine output
Out.newline (): Output a newline symbol
Out.flush (): Data for output buffers
Out.close (): Turn off output stream
Out.clearbuffer (): Clears the data in the buffer and writes the data to the client
Out.clear (): Clears the data in the buffer, but does not write the data to the client
Out.getbuffersize (): The size of the buffer is obtained, and the size of the buffer can be set <%@ page buffer= "Size"%>
Out.getremaining (): Gets the size of the space not used by the buffer
Out.isautoflush (): Returns a Boolean value that returns True if the Auto flush returns FALSE. Whether auto Fush we can set <%@ page is autoflush= "True/false"%>
Note: Chinese display problem
If the direct assignment of the Chinese string, with <%@ page contenttype= "text/html;" charset=gb2312 "%> can be displayed normally. However, you cannot use the GETSTR (String name) function or a similar function to convert the inner code, otherwise the Chinese will not display correctly.
If the request passes the Chinese string, you must use the Getstr (string name) function or similar function to convert the inner code, otherwise the Chinese can not be displayed normally.
Such as:
String Aa=str;
Byte[] Aa=aa.getbytes ("iso8859-1");
String Bb=new string (AA);
In different platforms, different server JSP Chinese problem solving methods are not the same, can be tested by themselves.
Request (Accept the information entered by the client)
Role: Primarily used to accept data transmitted by the client to the server side through an HTTP protocol connection.
Method:
GetCookies (): Returns a Cookie object for the client, and the result is an array of cookies
GetHeader (String name): Obtains the HTTP protocol definition's transfer header information, such as: Request.getheader ("User-agent") returns the client browser version number, type
GetAttribute (String name): Returns the property value specified by name, or null if no specified property exists.
Getattributenames (): Returns the name of all properties of the request object, which is an instance of a enumeration (enumerated) class.
Getheadernames (): Returns the name of all request headers, and the result set is an instance of a enumeration (enumerated) class.
Getheaders (String name): Returns all values for the request header of the specified name, and the result set is an instance of a enumeration (enumeration) class.
GetMethod (): Get the client to the server side of the data transfer method has get, POST, put and other types.
GetParameter (String name): Gets the parameter value that the client sends to the server side, which is specified by name.
Get Parameternames (): Gets all the parameter names that the client sends to the server side, and the result set is an instance of a enumeration (enumerated) class.
Getparametervalues (String name): Gets all values for the specified parameter.
GetQueryString () Gets the query string that is sent by the client to the server side in a Get method.
Getrequesturi (): Gets the client address that issued the request string.
Getservletpath (): Gets the file path of the script file requested by the client.
SetAttribute (String name,java.lang.object o): Name is set. The value of the request parameter, which is specified by O of type object.
getServerName (): Gets the name of the server.
Getserverport (): Gets the port number of the server.
GETREMOTEADDR (): Gets the IP address of the client.
Getremotehost (): Obtain the name of the client computer, if it fails, return the IP address of the client computer.
Getprotocol (): Gets the protocol name on which the client transmits data to the server side, such as http/1.1
Application (save user information)
Role: Once created, unless the server is shut down, it will keep going
Application.setattribute ("name", Val)
Request.setattribute ("name", Val)
Method: GetAttribute (String name): Returns the value of the Application object property with the name specified by name, which is an object
Getattributenames (): Returns the name of all Application object properties, the result set is an instance of a enumeration (enumeration) class
Getinitparameter (String name): Returns the initial value of a application attribute, which is specified by name
Getserverinfo (): Get current version of servlet compiler information
//----------------------------------------------------------------------------
Response (Control HTTP connection)
Role: Send data to the client, such as cookies, HTTP file-close information, and so on.
Method:
Addcookie (Cookie cookie): Adds 1 cookie objects to hold the client's user information. Use the GetCookies () method of request to obtain this cookie
Such as:% Cookie Mycookie=new cookie ("uname", "WSR");
Response.addcookie (MyCookie);
Cookie Delmycookie=new Cookie ("MyCookie", null);
Delmycookie. Setmaxage (0);
Delmycookie. SetPath (/");
Response.addcookie (Delmycookie);
%>
AddHeader (String name,string value): Adds the HTTP file header, which will be uploaded to the client, and if the header of the same name exists, the original header will be overwritten
Containsheader (String name): Determines whether the HTTP file header for the specified name exists and returns a Boolean value
Senderror (int sc): Send error message to client, such as: 505: Server internal error, 404: web Page Cannot find error
such as: response.senderror (response. Sc_no_content);
SetHeader (String name,string value): Sets the value of the HTTP file header for the specified name, which will be overwritten by the new value if it exists
such as 1:
Make the page refresh every 5 seconds
<% Response.setheader ("Refresh", "5");%>
The current dateis:<%=new Date ()%>
such as 2: Using the Response object to set HTTP headers
<% Response.setcontenttype ("application/pdf");
Response.setheader ("Content-disposition", "attachment;filename=\" syntax.pdf\ ")";
%>
Sendredirect ("error.html")/redirect function
Exception (Handling Exceptions and errors)
Action: Handles all errors and exceptions that occur when the JSP file is executed. There are 3 built-in methods.
Note: Exception objects must be used only if the <%@ page iserrorpage= "true"%>
GetMessage (): Return error message
Printstacktrace (): Output a stack of errors and errors in the form of a standard error
ToString (): Returns a description of 1 pairs of exceptions as a string
Session (save user information)
Function: Save each user's information separately
Session.putvalue ("name", Val)
Session.getvalue ("name")
Note: The information saved and retrieved in the session cannot be the base data type, but must be the corresponding object object in Java.
Method:
GetAttribute (String name): Gets the property of the specified name, and returns null if the property does not exist
Getattributenames (): Returns the first Property object stored in the session object, and the result set is an instance of a enumeration class
GetCreationTime (): Returns the time that the session object was created, in milliseconds, starting from January 1, 1970
GetId (): Each generation of a Session object, the server will give it a no duplicate number, this method returns the current session number
Getlastaccessedtime (): Returns the last 1 times the current session object has been manipulated, and returns the number of milliseconds since January 1, 1970
Getmaxinactiveinterval (): Get time to live session object
RemoveAttribute (String name): Deletes the specified property (including property name, property value)
SetAttribute (String name,java.lang.object value): Sets the property value of the specified name and stores it in the Session object
SetAttribute (String Name,object object): Initializes a property with Object, which is specified by name
-------------------------------------------------------------------------------------
Using the Java Bean component
Feature: It can be reused anywhere, including multiple scenarios that can be used in applications, other components, documents, Web sites, and application Builder tools.
The concept of JavaBean
JavaBean is an application interface independent of platform and structure, it can ignore internal structure and detail problem, just define its external features and external functions.
It has three interface surfaces that can be developed independently of the following: properties, methods, and events
Properties of JavaBean
There are two types of properties for a JSP component: Single-valued properties, indexed properties
Single-Valued Properties:
Equivalent to a member variable defined in normal programming, it can have only one data value, and the type of the data value may be any data type in Java, including classes and interfaces.
Such as:
int counter;
Float tax;
String name;
Date datetime;
Note: A special Single value attribute (Boolean property) that has only two allowable values: true, False
Indexed properties:
The equivalent of the usual array, when storing a group of data of the same type, you need to use indexed properties.
such as: int id[];
String name[];
Float score[];
The method of JavaBean
Methods include constructing methods and accessing methods.
Construction Method:
Similar to a constructor in a class (that is, initialization of it and its member variables), its method name 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:
is access to the attributes defined in the component, including read and write (generally similar to the methods defined and used in Java), and note its naming rules:
Read a property: GetXXX ()
Overwrite an attribute: Setxxx ()
Accessing a single Value property: For example, the Counter property of the above, its two access methods can be:
Read Property value:
public int getcounter{
return counter;
}
Overwrite attribute value:
public void Setcounter (int counter) {
This.counter=counter;
}
Accessing a Boolean Single Value property: Using the Isxxx () method for reading property values
For example, the access to the attribute Whizkid of the above Boolean type can be:
public Boolean iswhizkid () {
return whizkid;
}
Accessing indexed properties: Sometimes you have to define several access methods, but their naming rules are the same, such as for the above name attribute, and its reading and rewriting methods need to be defined as follows:
To read an attribute value in an indexed property:
Public String getName (int index) {
return Name[index];
}
To read all property values in an indexed property:
Public string[] GetName () {
return name;
}
To overwrite an attribute value in an indexed property:
public void setname (int index,string str) {
NAME[INDEX]=STR;
}
To overwrite all property values in an indexed property:
public void SetName (string[] str) {
NAME=STR;
}
Creating a bean written in JavaBean in a JSP is actually an object that creates this class.
The work done by the client
The client's work can be divided into two parts:
First, send a request to the server side to send the submission to the server side
Second, in the client to verify, as well as page decoration and other functions
Method of Client Submission
There are two ways to commit a client: Get and Post submit
Get can pass the information only about 2KB, and is the plaintext transmission of information, all the information can be seen in the address bar.
Post can convey a lot of information, encrypted transmission, all the information can be in the address bar is not visible.
Post Submit
All post submissions can only be generated in form and submitted in two different ways: direct submission (submit submission), indirect submission (script submission)
1) Direct submission: Click the submit button to submit immediately
Note: The Submit button has a default event, which is to submit
Note: Before submitting, first on the screen returned a warning box "Hello", if return is true, the page will be submitted, if return is false, the page is not committed.
2) Indirect submission: Refers to the click of the button itself can not complete the submission, and only through the script to complete the submission, called indirect submission.
Note:
In the onclick place can also be onmousedown, onmouseup and other event names
button is only a normal buttons, itself can not be committed, can only be specified by the OnClick script program to complete the submission
Click "Register", the first execution of the OnClick event trigger function, if the return value is true, then commit, or commit abort.
Get Commit
Get commit occurs in form form and URL
1) generated in the form
2. Generated in all URLs
Enter the URL address in the address bar, followed by the parameters to be passed http://*.asp?name=www&age=20
On the hyperlink click me
Response.Redirect "*.asp?name=www" in ASP redirection statements
In client object document: document.location= "http://*.asp?name=www"
In Client object window: window.open ("http://*.asp?name=www")
Server-side work
The method of obtaining client information is done through the request object.
The information that the client submits to the server side is divided into three categories:
Class One: Client information (including the client's IP address, port number, host name, submit method, and so on)
Type II: Submitting information to the server side by form or URL
Category III: Cookie information
Get the first category of information by:
Request.getheader ("User-agent") returns the version number, type of the client browser
GetHeader (String name): Gets the header information for the HTTP protocol definition of the delivery file
Request. GetMethod (): Get the client to the server side of the data transfer method has get, POST, put and other types
Request. Getrequesturi (): Gets the client address that issued the request string
Request. Getservletpath (): Gets the file path of the script file requested by the client
Request. getServerName (): Get the name of the server
Request.getserverport (): Get the port number of the server
REQUEST.GETREMOTEADDR (): Obtain the client's IP address
Request.getremotehost (): Get the name of the client computer, if it fails, return the IP address of the client computer
Request.getprotocol ():
Request.getheadernames (): Returns the name of all request headers, and the result set is an instance of a enumeration (enumerated) class
Request.getheaders (String name): Returns all values for the request header of the specified name, and the result set is an instance of a enumeration (enumeration) class
Get information for the second class:
Request. GetQueryString ("Variable name or control name") gets the query string, which is sent by the client to the server side with a Get method
Get the second kind of post information by:
Request.getparameter (String name): Gets the parameter value that the client sends to the server side, which is specified by name
Request.getparameternames (): Obtains all the parameter names that the client transmits to the server side, and the result set is an instance of a enumeration (enumerated) class
Request.getparametervalues (String name): Get all values for specified parameters
Get the third class cookie information by:
Request.getcookies ("Cookie variable name"): Returns the client's cookie object, resulting in an array of cookies
--------------------------------------------------------------------------------------------
Database Primary section for everyone's convenience, take access as an example
Configuration steps:
At start--settings--Control Panel--Administrative Tools--data source (ODBC)--System DSN--"Add"--"Select data source Driver"--"complete"--"ODBC installation fill out the data source name, click ' OK '"-"complete" can be.
Five elements of a database connection:
IP Address
The port number (the port number is basically fixed for a database service unless specifically set) means that the corresponding database driver
Select Database
Account number, password (is assigned to the database)
Emit SQL statements (sent by statement object)
JDBC principle
JDBC is the connection between Java and data. Because ODBC is written entirely in C language, and Java in the implementation of the C language Program communication is more difficult, so the Java language is produced by the Java Program and database connection technology.
JDBC Connection to database
JDBC is connected to a specific database by automatically loading the driver directly through classes in the JDBC API class library. This class library is typically in the java.sql package, which contains classes for implementing other functions connected to the database, including establishing connections with the database, routing queries, and accepting query results. Detailed descriptions of the following four classes:
Role:
Establishing a 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 Results
------------------------------------------------------------------------------------------
DriverManager class
This class is used to load the driver, all of its members are static members, so there is no need to instantiate it in the program and access it directly through the class name.
The DriverManager class is a JDBC management layer that acts to load drivers between users and drivers
Class.forName ("Company name. Database name. Driver name")
such as: Class.forName ("Sun.jdbc.odbc.jdbcOdbcDriver")
Establish a connection
After loading the driver class and registering with the DriverManager class, you can use it to establish a connection to the database. When the call to Driver.Manager.getConnection () makes 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 users and passwords that log on to the database
The first parameter is the URL that points to the database, which is formatted as follows:
JDBC: (subprotocol):(subname)
Subprotocol: A child protocol that specifies which database to connect to or how to connect to the database
SubName: Establish a connection that can be a data source name or point to an online database
For example: The following are examples of commonly used drivers (JDBC-ODBC bridge drivers) and a student data source with anonymous logins:
Class.forName ("Sun.jdbc.odbc.jdbcOdbcDriver");//Load 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 null NULL
Connection class
The connection class is a connection that points to the same database.
Role: Manage connections to the database, such as: queries that send queries to the database and query results from the receiving database are based on it, and the connection is closed after all tasks that have connected to the database have been completed.
Method:
Statement createstatment (): Creates a new Statement object that can send query information to the database
void Close (): Closes the connection to the database and frees the occupied JDBC resource
Boolean Isclose (): Determines whether the database is still connected
Statement class
Function: The statement object is used to send SQL statements to the database.
Creating statement objects
Once you have established a connection to a specific database, you can use the connection to send the SQL statement. The statement object is created using the connection method createstatement.
Connection cn=drivermanager.getconnection (Rul, "Sunny", "");
Statement stmt=cn.createstatement ();
In order to execute the statement object, the SQL statement sent to the database will be supplied as a parameter to the statement method
ResultSet rs=stmt.executequery ("Select A,b,c from table2");
Executing statements using the statement object
The statement interface provides three ways to execute SQL statements
ExecuteQuery (): statement used to produce a single result set, such as: SELECT statement
Executeupdate (): For INSERT, update, or delete, statement, and so on, the return value is an integer indicating the number of rows affected (that is, the update count)
Execute (): Used to execute statements that return multiple result sets, multiple update counts, or combination of both
Statement completion
Statement is considered complete when it is executed and all results are returned.
For the ExecuteQuery () method that returns a result set, the statement completes after retrieving all rows of the ResultSet object.
For method Executeupdate (), the statement completes when it executes
In the case of a few calls to execute (), the statement completes only after retrieving all the result sets or the update count that it generates
Close Statement Object
The statement object will be automatically closed by the Java garbage collector. But we'd better show them off because the data management system resources will be released immediately, helping to avoid potential memory problems.
Main methods
ResultSet executequery (String sql): Returns a static SQL query result
int executeupdate (String sql): Query the number of inserts, update, deletes, or return 0 in a row of SQL declarations
void Close (): Closes the connection to the database and the JDBC resources it occupies
ResultSet class (record set)
Role: Load query results, and can extract the results of the query through its different methods. ResultSet contains all the rows that conform to the conditions in the SQL statement, and it provides access to the data in those rows through a set of get methods that can access different columns in the current row.
Resultset.next (): Moves the record pointer to the next line in the ResultSet record set to make it the current row.
Note: A record set is a two-dimensional table with the column headings and corresponding values returned by the query.
For method Executeupdate (), the statement completes when it executes
In the case of a few calls to execute (), the statement is only completed after retrieving all the result sets or the update count that it generates
-------'s Over!
PS: This tutorial for my collection of content, do some collation, is the basis of JSP.