Summary of JSP basic statement usage and JSP statement usage
This example describes the usage of JSP basic statements. Share it with you for your reference. The details are as follows:
1> JSP commands
JSP commands (Directive) are used to communicate with the JSP Engine and set global variables and sound for the JSP page.
Class and the methods and types of output content to be implemented by JSP.
The JSP command is valid throughout the page and does not generate any output from the client.
Format: <% @ directivename attribute = "value" %>
<% @ Directivename attribute1 = "value1" ...... attributeN = "valueN" %>
2> page command
Defines the global attributes and related functions of JSP pages, and communicates with the JSP engine through this command.
Format: <% @ page attribute1 = "value1",... %>
Available attributes: language import contentType session buffer autoFlush
IsThreadSafe info errorPage isErrorPage extends.
A JSP Page can contain multiple Page commands.
Except the import attribute, each attribute can only be defined once; otherwise, an error occurs.
Language attribute: language = "scripting language" declares the type of scripting language used on the JSP page
Extends = "ClassName" defines the class inherited by the Servlet generated by the JSP page.
The superclass provided by the consumer
Import = "importList" and java import mean the same, import package file
Session = "true | false" specifies whether the JSP page participates in an Http session.
Buffer = "none | sizeKB" specifies the buffer mode of the client output stream. none indicates no buffer.
False "the system will automatically refresh when the buffer is full. If it is false, the buffer is full.
An overflow exception occurs.
IsThreadSafe = "true | false" multithreading is supported.
Info = "info_text" defines an arbitrary string to describe the information described in JSP.
Inbound translation page
ErrorPage = "error_url" sets the JSP file for handling exception events
IsErrorPage = "true | false" sets whether this page is an exception page"
ContentType = "type; charset = CHARSET" defines the MIME type and JSP page of the JSP page.
Character encoding (only the type part can be written)
PageEncoding = "peinfo" is used to process Chinese characters. Generally, charset = GB2312
IsELIgnored = "true | false" is used to set whether the EL expression is ignored.
3> include command
Used to specify the resources to be inserted when JSP is compiled. It can be text, code, HTML file or JSP
File
Format: <% @ include file = "URL"> once compiled, the resource content cannot be changed.
The include command can be used to divide a complex JSP page into several parts, such as head. jsp.
Body. jsp tail. jsp is then called using the include command on different JSP pages of the same website
4> taglib command
Using custom tags, you can define some content that needs to be repeatedly displayed as a tag to add
Add code reuse and make the page easy to maintain
Step 1 define a tag processing class to implement the tag Function
Step 2 define the tag library description file, and describe the tag-related information after the. tld
Step 3 configure the web. xml file
Format: <% @ taglib uri = "tagligURL prefilx =" tagPrefix "%>
5> Scriptlet script elements
Declaration is used to define the variable method <%! Int I, a, B = 0; %> declare each statement to end;
Declaration method <%! String getDate () {}%> (a declaration can only be valid on one JSP page)
Expression format: <% = expression %> (the expression cannot end)
<% = 1 + 2 + 3%> output 6
<% = New java. util. Date (). toString () %> output Date
Scriptlet: java code included in <%>
JSP provides many action elements:
<Jsp: useBean> <jsp: setProperty> <jsp: getProperty> <jsp: fallback>
<Jsp: param> <jsp: include> <jsp: forward> <jsp: plugin>
<Jsp: params> <jsp: root> <jsp: expression_r_r> <jsp: text>
<Jsp: output> <jsp: declaration> <jsp: scriptlet>... more than 20
<Jsp: param> to pass one or more parameters to a specified dynamic file
<Jsp: include> <jsp: forward> <jsp: plugin>
<Jsp: param name = "paramName" value = "paramValue"/>
<Jsp: include page = "HelloWorld.html"/>
<Jsp: forward> allows you to forward the current request to another static file or JSP page.
Servlet with the same content on the previous page
<Jsp: forward page = "confirm. jsp">
<Jsp: param name = "user" value = "aaa"/>
<Jsp: param name = "password" value = "12345"/>
</Jsp: forward> switch to the confirm. jsp page and pass two parameters: user and password.
<Jsp: plugin> is used to play or display an object in the client browser, which is usually an Applet or
Bean, which is replaced with <object> or <embed> according to the browser version.
Format:
<Jsp: plugin type = "bean | applet" code = "objectCode"
Codebase = "objectCodebase" archive = "archiveList"
Name = "componentName" align = "alignment"
Vspace = "vspace" hspace = "hspace"
Height = "height" width = "width"
Nspluginurl = "url" iepluginurl = "url"
Jreversion = "jreversion" myscript = "true | false"/>
<Jsp: params name = "paramName" value = "paramValue">
<Jsp: fallback> artistmtext </jsp: fallback> (when the display Bean | Applet fails,
Shows this string
6> embedded JSP objects
JSP provides some built-in objects implemented and managed by containers, which can be directly used on the JSP page.
It needs to be instantiated. By accessing these built-in objects, you can access each other in the Servlet environment of the JSP page.
JSP provides a total of nine built-in objects: out request repnse session pageContext
Application config page exception
JSP is built on Servlet. Each built-in object of JSP is a class in the assumervletapi package.
Phase Object, automatically generated when the server is running
JSP provides developers with a data transmission mechanism, that is, using setAttribute () and
GetAttribute () method
JSP has four scopes: Page Request Session Application
The Page range indicates that the range of a single Page JSP Page is invalid when it leaves the Page.
PageContext. setAttribute ("Name", "abc"); set the value of attribute Name to abc.
Valid within the range of this page. Call (String) PageContext. getAttribute ("Name") on this page
Return "abc"
The Request range refers to the Request sent between one JSP page and another JSP page.
, Forward Command, etc.), and then the range becomes invalid.
Request. setAttribute () and Request. getAttribute ()
The Session range is the duration for a user to connect to the server. However, after the Session is disconnected from the server, the attribute
It becomes invalid.
The scope of Application takes effect immediately after the server runs the service until the server is shut down.
So far
The storage and attribute acquisition methods that can be used by the above four built-in objects:
Void setAttribute (String name, Object value): set the value of the name attribute to value.
Enumeration getAttributeNamesInscope (int scope) Get all scope attributes
Object getAttribute (String name) obtains the value of the name attribute.
Void removeAttribute (String name) removes the value of the name attribute.
Note: pageContext does not have the getAttributeNames () method.
The out object is encapsulated in the javax. servlet. jsp. JspWriter interface and can be buffered by the out object
Operation
Generally, the out object is obtained through the pageContext. getOut () method.
Common method: public abstract void print ()
Public abstract void println ()
Public abstract void newLine () // output a linefeed
Public abstract void close () // close the output stream
Public abstract void clearBuffer () // clear the buffer content and
Send to client
Public abstract void clear () // clear the buffer content and do not send data
Client
Public int getBufferSize () // obtain the buffer size
Public abstract int getRemaining () // obtain the size of the remaining buffer space
Public abstract void flush () // output buffer data
Public boolean is AutoFlush () // gets the value of AutoFlush
The request object encapsulates the information submitted by the user and is encapsulated in
Javax. servlet. http. HttpServletRequest Interface
There are four main methods:
1. Methods for accessing attributes:
Object getAttribute (String)
Enumeration getAttributeNames (int)
Void setAttribute (String, Object)
2. Methods for obtaining Request parameters:
String getParameter (String) gets the specified parameter name
Enumeration getParameterNames () Get all parameter names
String [] getParameterNames (String name) Get the parameter values of all names
Map getParameterMap () gets a Map that requires Parameters
3. methods to obtain the HTTP header of the request:
String getHeader (String name) gets the name header
Enumeration getHeaderNames () get all header names
Enumeration getHeaders (String name) gets the headers of all names
Int getIntHeader (String name) gets the header of the integer name
Long getDateHeader (String name) gets the date type name header
Cookie [] getCookies () get cookies related to requests
4. Other methods:
String getContextPath () obtains the Context path
String getMethod () Get Http method (Get | Post)
String getServletPath () page for receiving information submitted by the customer
String getProtocol () gets the used protocol (Http/1.1 Http/1.0)
String getQueryString () gets the request parameter String (the Http method must be GET)
String getRequestedSessionId () obtains the Session ID of the user end.
String getRequestURI () gets the request URL, excluding the request parameter String
String getRemoteAddr () gets the user's IP address
String getRemoteHost () obtains the host name of the user.
Int getRemotePort () gets the user's host port
String getRemoteUser () Get the user name
Void setCharacterEncoding (String encoding) is used to set the encoding format for form transmission.
Chinese problems
Response object: The result generated after JSP processing data, encapsulated in
Javax. servlet. http. HttpServletResponse Interface
Void addCookie (Cookie cookie) adds a cookie
Void addDateHeader (String name, long date) adds the value of the long type to the name header.
Void addHeader (String name, String value) adds a String type value to the name header.
Void addIntHeader (String name, int value) adds the int type value to the name header.
Void setDateHeader (String name, long date) specifies the value of the long type to the name header.
Void setHeader (String name, String value) specifies the String type value to the name header
Void setIntHeader (String name, int value) specifies the String type value to the name header
Void sendError (int SC) Transfer status code
Void sendError (int SC, String msg) transmits status codes and error messages
Void setStatus (int SC) Status Code
String encodeRedirectURL (String url) is edited using the URL of the sendRedirect () method.
Code
Response. setContentType ("text/htmlcharset = Big5") is the same as <% @ page
ContentType = "text/html; charset =" Big5 "%> equivalent
Cookie technology:
Cookie enables the site to track the number of visits of a specific visitor, the last visit time, the way visitors enter the site
Path
Cookie tells online advertisers the number of clicks
Cookies can help Websites collect users' personal data for various personalized services.
Create Cookie
Cookie demoCookie = new Cookie ("CookieName", "Cookiue ")
The get method in Cookie:
String getComment () returns the comment in the cookie
String getDomain () returns the cookie domain name in the Cookie. The domain name starts with ".yesky.com)
Int getMaxAge () returns the maximum time before the Cookie expires, in seconds.
String getName () returns the Cookie name.
String getPath () returns the applicable Cookie Path. If this parameter is not specified, the Cookie is returned to the current page.
All pages in the directory and Its subdirectories
Boolean getSecure () if the browser sends cookies through the security protocol, true is returned.
The quasi-Protocol returns false.
String getValue () returns the Cookie value.
Int getVersion () returns the Protocol version of the Cookie.
Set Method in Cookie:
Void setComment (String purpose)
Void setDomain (String pattern)
Void setMaxAge (int expiry)
Void setPath (String uri)
Void setSecure (boolean flag)
Void setValue (String newValue)
Void setVersion (int v)
Cookie sample code:
String sessionID = makeUniqueString (); HashMap sessionInfo = new HashMap (); HashMap globaTable = findTableStoringSessions (); globeTable. put (sessionID, sessionInfo); Cookie sessionCookie = new Cookie ("JSESSION", sessionID); cookie setMaxAge (30*60); // The survival time is 30 minutes response. addCookie (cookie); // write to the customer's hard disk
Difference between session and cookie:
Sessions are stored in the server memory.
The session is generated when the user logs on and disappears after the User goes offline.
The session is stored on the server. Users cannot modify the session and the session is safe.
A session is a continuous action and a session.
Session object, which records the access status of each client to track the operation status of each client.
Installed as the javax. servlet. http. HttpSession interface, you can use pageContext. getSession ()
Method to obtain a session Object
Methods In the session object:
Long getCreationTime () obtains the time when the session is generated.
String getId () obtains the session ID.
Long getLastAccessedTime () gets the time when the user finally sends the request through this session,
Unit: milliseconds
Long getMaxInactiveInterval () gets the maximum time when the session is not active.
In seconds.
Void invalidate () cancels the session object
Boolean isNew () determines whether the session is new
Void setMaxInactiveInterval (int interval) sets the maximum time when the session is not active,
If this time is exceeded, the session will expire in seconds.
The application object that provides global information about the application running on the server
The server is closed and encapsulated in the javax. servlet. SertletContext interface.
Int getMarorVersion () gets the main Servlet API version of the iner.
Ing getMinorVersion () obtains the minor Servlet API version of the iner.
String getServerInfo () gets the name and version of the Container.
String getMimeType (String file) gets the MIME type of the specified file
ServletContext getContext (String uripath) obtains
ApplicationContext
String getRealPath (String path) obtains the absolute Path of the local path.
Void log (String message) writes information to the log file
Void log (String message, Throwable throwable) exception caused by stacktrace
Information is written to the log file.
The pageContent object is generally used for setting. It obtains some attributes of the current JSP page and can also access the page.
Other hidden objects (out, request, response, session, application, etc.) and all their attributes,
Encapsulated in the javax. servlet. jsp. PageContext Interface
Four Range parameters provided by the javax. servlet. jsp. PageContext class: PAGE_SCOPE
REQUEST_SCOPE SESSION_SCOPE APPLICATION_SCOPE
Exception getException () returns an Exception to the current webpage. However, this webpage must be an error page.
JspWriter getOut () returns the output stream of the current webpage, such as out
Object getPage () returns the Servlet Object of the current webpage
ServletRequest getRequest () returns the current webpage request
ServletResponse getResponse () returns the current webpage response
ServletConfig getServletConfig () returns the current page's ServletConfig object
ServletContext getServletContext () returns the execution environment of this webpage
HttpSession getSession () returns the session currently associated with the webpage
Config object, which is used to obtain server configuration information and is encapsulated in
Javax. servlet. servletConfig interface, the pageContext. getServletConfig () method
You can obtain a config object that provides access to servlet class initialization parameters and related server environment information.
ServletContext object
Common Methods for config objects:
Public String getInitParatemer (String name) obtains
Initial Value
Public Enumeration getInitParameterNames () obtains the names of all the initial parameters of the server.
Word
Public ServletContext getServletContext () Get the Servlet context
Public String getServletName () Get the Servlet server name
The page Object, which represents the Servlet class Object after the JSP file is compiled. In essence, it is an instance of the Object.
Exception object, mainly used to display singing information, representing exceptions generated during JSP file running
Object, which is an instance of the java. lang. Throwable class and only contains <% @ page
The isErrorPage = "true" %> page can be used.
Compile JSP files
I hope this article will help you with JSP program design.