JSP Study Notes 1 -- initial access to JSP and JSP built-in objects

Source: Internet
Author: User
Tags html comment html header

JSP Study Notes 1 -- initial access to JSP and JSP built-in objects

This is a small project with JSP: User Login project file: http://pan.baidu.com/s/1i37mS2h

Write the first Web program manually
Create a project directory in WebApps
Compile index. jsp
Create a WEB-INF directory
Test Run
The WEB-INF security directory. The client is not accessible and the server is accessible.
Including: web. xml
Classes
Lib
Set the default welcome homepage:
Tag in the web. xml file

/Haha. jsp

Configure JRE in MyEclipse:
Window-> Preference-> Java-> Installed JREs
Configure the Tomcat server in MyEclipse:
Window-> Prefernce-> Myeclipse-> server-> Tomcat


[Basic Jsp syntax]
Page command: Usually located at the top of the jsp page. The same page can have multiple page commands.
Include command: embed an external file into the current JSP file and parse the JSP statement on this page.
Taglib command: Use the tag library to define new custom tags and enable custom behaviors on the JSP page.


Page command syntax:
<% @ Page attribute 1 = "attribute value", attribute 2 = "attribute value", attribute 3 = "attribute value"... attribute n = "attribute value" %>

| Locale | attribute | description | default value | ----------- | locale | -------------------- | language | specifies the scripting language used on the JSP page | java | ------------- | locale | ------------------ | import | this attribute is used to reference the class files used in the script language | none | ------------- | ------------------------------------ | ------------------ | contentType | used to specify the encoding method used by JSP pages | text/html, ISO-8856-1 | ------------------------------------------------------------------------- |

[JSP page comment]
HTML comment:
// Visible to the client
JSP comments:
<% -- HTML comment -- %> // invisible to the client
JSP script annotation:
// Single line comment
/**/Multi-line comment
Java code executed on the JSP page]
Syntax:
<% Java code %>
[Define variables or methods on the JSP page]
Syntax:
<%! Java code %>
Expressions executed on the JSP page]
Syntax:
<% = Expression %> // Note: The expression does not end with a semicolon
[JSP page lifecycle]
The user sends the request index. jsp;
If (the first request) the JSP Engine converts the JSP file into a Servlet, generates a bytecode file, and executes jspInit ();
Generate a bytecode file;
Parsing execution, jspService ().
[JSP built-in object]
JSP built-in objects are a set of objects created by Web containers. They can be used without the new keyword.
<%
Int [] value = {60, 70, 80 };
For (int I: value ){
Out. println (I );
}
%>
The out here is a built-in object.
Nine built-in JSP objects: out, request, response, session, application, Page, pageContext, exception, config
[Request Response Mode of Web programs]
Request)
Response from the server to the user)
[Buffer zone]
Buffer: Buffer, which is a part of the memory used to save temporary data.
[Out object]
An instance of the JspWriter class when an out object is used to output content to the client.
The common method is as follows:
1. void println () prints a string to the client
2. void clear () indicates the buffer content. If it is called after flush, an exception is thrown.
3. void clearBuffer () indicates the buffer content. If it is called after flush, no exception is thrown.
4. void flush () outputs the buffer content to the client
5. int getBufferSize () returns the size of the number of buffer bytes. If no buffer is set, the value is 0.
6. int getRemaining () returns how much available the buffer is.
7. boolean isAutoFlush () indicates whether to automatically clear or throw an exception when the returned buffer is full.
8. void close () to close the output stream
[Difference between get and post]

Two forms can be submitted: get and post.
1. get: submit data through URL in plaintext mode. The data can be seen in the URL. The data submitted cannot exceed 2 kb at most. Low Security, but more efficient than post


High mode. Suitable for submitting data with low data volume and low security. Such as L search and query.
2. post: encapsulate the information submitted by the user in the html header. It is suitable for submitting user information with large data volumes and high security. For example, register, modify, and upload


Upload and other functions.
[Request object]
The request information of the client is encapsulated in the request object, so that the client can understand the customer's requirements and then respond. It is HttpServletRequest


Class. The request object has a request domain, that is, the object remains valid until the client completes the request. The common method is as follows:
String getParameter (String name) returns the parameter value of the specified name parameter.
String [] getParameterValues (String name) returns an array containing all values of the parameter name
Void setAttribute (String, Object) Stores attributes in this request
Object getAttribute (String name) returns the attribute value of the specified attribute.
String getContentType () Get the MIME type of the Request body
String getProtocol () returns the protocol type and version number of the request.
String getServerName () returns the server host name that receives the request
Int getServerPort () returns the port number used by the server to accept this request.
String getCharacterEncoding () returns the character encoding method
Void setCharacterEncoding () sets the character encoding method of the request.
Int getContentLength () returns the length of the Request body (in bytes)
String getRemoteAddr () returns the IP address of the client sending this request.
String getRealPath (String path) returns a real virtual path.
String request. getContextPath () returns the context path.
[Response object]
The response object contains information about the response to the customer request, but it is rarely used directly in JSP. It is the actual version of The HttpServletResponse class.


Example. The response object has a page scope, that is, when accessing a page, the response object of the page can only be valid for this access. Other pages


The response object of is invalid for the current page. The common method is as follows:
String getCharacterEncoding () character encoding used to return the response
Void setContentType (String type) sets the MIME type.
PrintWriter getWriter () returns an object that can output characters to the client (Note: The difference between printWriter and built-in out object)
SendRedirect (java. lang. String location) Redirects client requests
[Difference between request forwarding and request redirection]
Request redirection: client behavior, response. sendRedirect (), essentially equivalent to two requests. The previous request object will not be saved.


The URL in the address column is changed.
Request forwarding: Server behavior. request. getRequestDispatch (). forward (req, resp); is a request. After forwarding, the request object is saved,


The URL in the address bar does not change.
For example, if you want to apply for a passport
Redirection: you first went to Bureau A, and the person in Bureau A said, "This is not my responsibility. Go to Bureau B." Then, you will return from Bureau, I took a bus to Bureau B.
Forward: You went to Bureau A. After Bureau A saw it, you should know that bureau B was responsible for this matter, but they didn't return you back. Instead, they asked you to sit down for A while.


I contacted B's staff in the back office and sent them to the back office.
[Session]
Session indicates a session between the client and the server.
The session in the Web refers to the period from when a user browses a website to when the user closes the website, that is, when the user browses the website


The time spent on the website.
From the above definition, we can see that session is actually a specific concept of time.
The server memory stores sessions of different users.
[Session Object]
The session object is a JSP built-in object.
The session object is automatically created when the first JSP page is loaded to complete session Period Management.
A session starts when a client opens a browser and connects to the server, and ends when the client closes the browser and leaves the server.
When a customer accesses a server, it may switch between several pages of the server. The server should know in some way that this is a customer,


The session object is required.
The session object is an instance of the HttpSession class.
Common Methods for session objects are as follows:
Long getCreationTime (): returns the session creation time.
Public String getId (): return the unique ID number set by the JSP Engine when the session is created.
Public Object setAttribute (String name, Object value): Use the specified name to bind the Object to this session
Public Object getAttribute (String name): returns the Object bound with the specified name in this dialog. If no Object is bound


If the name is specified, null is returned.
String [] egtValueNames (): returns an array containing all available attributes of this session.
Int getMaxInactiveIntervals (): the interval between two requests returned. The session is canceled (in seconds)
[Session lifecycle]
Create:
When the client accesses a JSP or Servlet for the first time, the server creates a SessionId for the current session.


When a request is sent, the SessionId is carried in the past, and the server verifies the SessionId.
Activity:
A new page opened through a hyperlink in a session belongs to the same session.
As long as the current session page is not all closed, re-open a new browser window to access resources of the same project belongs to the same session.
Unless all the pages of this session are closed and then re-access a JSP or Servlet will create a new session.
Note: The original session still exists, but the old SessionId still exists on the server, but no client will carry it


And then submit it to the server for verification.
Destruction:
There are only three methods for Session destruction:
1. The session. invalidate () method is called.
2. Session expiration (timeout)
3. Restart the server
The default session timeout time for Tomcat is 30 minutes.
You can set session timeout in either of the following ways:
1. session. setMaxInactiveInterval (time); // The unit is seconds.
2. Configure in web. xml


10

// The unit is minute.
[Application Object]
The application Object shares user data and stores global variables.
The application starts from the start of the server and ends with the shutdown of the server.
You can perform operations on the same attribute of the application object in the user's frontend and backend connections or connections between different users.
Any operation on application object attributes affects access by other users.
The startup and shutdown of the server determine the life of the application object.
Instance of the ServletContext class when the application object is used.
The common method is as follows:
Public void setAttribute (String name, Object value) binds the Object to this session with the specified name.
Public Object getAttribute (String name) returns the Object bound to the specified name in this session. If no Object is bound to this


Return null.
Enumeration getAttributeNames () returns the Enumeration of all available attribute names
String getServerInfo () returns the JSP (SERVLET) engine name and version number.
[Page Object]
The page Object points to the current JSP page itself, a bit like the this pointer in the class. It is an instance of the java. lang. Object Class. The common method is as follows:
Class getClass () returns the class of this Object
Int hashCode () returns the hash code of this Object
Boolean equals (Object obj) determines whether the Object is equal to the specified Object
Void copy (Object obj) copies the Object to the specified Object.
Object clone () clone this Object
String toString () converts the Object to a String Object.
Void y () Wake up a waiting thread
Void policyall () Wake up all waiting threads
Void wait (int timeout) enables a thread to wait until the timeout ends or is awakened.
Void wait () enables a thread to wait until it is awakened.
[PageContext object]
The pageContext object provides access to all objects and namespaces on the JSP page.
The pageContext object can access the session on this page, or take a property value of the application on this page.
The pageContext object is equivalent to the aggregator of all functions on the page.
This class name of the pageContext object is also called pageContext.
The common method is as follows:
JspWriter getOut () returns the JspWriter stream (out) in use in the current client response)
HttpSession getSession () returns the HttpSession object (session) on the current page)
Object getPage () returns the Object (page) of the current page)
ServletRequest getRequest () returns the ServletRequest object (request) of the current page)
ServletResponse getResponse () returns the ServletResponse object (response) of the current page)
Void setAttribute (String name, Object attribute) set attributes and attribute values
Object getAttribute (String name, int scope) obtains the attribute value within the specified range
Int getAttributeScope (String name) returns the scope of an attribute.
Void forward (String erlativeUrlPath) causes the current page to be re-exported to another page
Void include (String relativeUrlPath) contains another file at the current position
[Config object]
The config object is used by the JSP Engine to transmit information to a Servlet during initialization. This information includes the parameters used during Servlet initialization (


Attribute names and attribute values) and server-related information (by passing a ServletContext object). Common methods are as follows:
ServletCOntext getServletContext () returns the ServletContext object containing server-related information.
String getInitParameter (String name) returns the value of the initialization parameter.
Enumeration getInitParameterNames () returns the Enumeration of all parameters required for Servlet initialization.
[Exception object]
An exception object is an exception object. This object is generated when a page encounters an exception during running. If a JSP page needs to apply this


The isErrorPage must be set to true; otherwise, compilation fails. It is actually a java. lang. Throwable object. The common method is as follows:
Stirng getMessgae () returns a message describing an exception.
String toString () returns a brief description message about the exception.
Void printStackTrace () displays exceptions and stack traces
Throwable FillStackTrace () overwrites the execution stack track of an exception


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.