The example of this article tells the JSP Basic statement usage. Share to everyone for your reference. Specifically as follows:
1>jsp directives
The JSP Directive (Directive) function is communicates with the JSP engine, sets the global variable for the JSP page, the sound
The types of methods and output content that the JSP is to implement
JSP directives are valid throughout the page and do not produce any output on the client
Format: <%@ directivename attribute= "value"%>
<%@ directivename attribute1= "value1" ... attributen= "Valuen"%>
2>page directives
Used to define global properties and related functionality for JSP pages, and to communicate with this directive and the JSP engine
Format: <%@ page attribute1= "value1",........%>
Available properties: Language Import contentType Session buffer AutoFlush
IsThreadSafe Info errorpage iserrorpage extends.
A JSP page can contain multiple page directives
Except for the Import property, each property can only be defined once, otherwise an error
Language property: Language= script language declares the type of scripting language used in a JSP page
extends= "ClassName" defines classes that are inherited by the servlet generated by the JSP page, restricting the JSP primer
Super class provided by the engine
Import= "Importlist" and Java import means that the package file is imported
Session= "True|false" Specifies whether the JSP page participates in an HTTP session
Buffer= "NONE|SIZEKB" specifies the buffer mode for the client output stream, none means no buffering
False "automatically refreshes when the buffer is full, and if false, the buffer is full
There will be an overflow exception
Isthreadsafe= "True|false" can use multithreading
info= "Info_text" defines an arbitrary string that describes the information of the JSP description and will be directly added to the
into the translated page
Errorpage= "Error_url" set up JSP files to handle exception events
Iserrorpage= "True|false" sets whether this page is an exception page "
Contenttype= "Type;charset=charset" defines the corresponding MIME type of the JSP page and the JSP page
The character encoding of the face (you can write only the type part)
pageencoding= "peinfo" processing Chinese characters are usually charset=gb2312
Iselignored= "True|false" is used to set whether an El expression is ignored
3>include directives
Used to specify the resources that the JSP needs to be inserted when it is compiled, which can be text, code, HTML file, or JSP
File
Format: <%@ include file= "URL" > Resource content cannot be changed once the compilation is completed
Use the include directive to divide a complex JSP page into parts, such as: head.jsp
Body.jsp tail.jsp then call with the include instruction on different JSP pages on the same web site
4>taglib directives
By defining tags, you can define a number of content that needs to be repeatedly displayed as a label, increasing
Add code reuse and make pages easy to maintain
Step 1 defines a label processing class that implements the function of the label
Step 2 defines the tag library description file, after which the most relevant information about the tag is described.
Step 3 Final configuration file Web.xml
Format: <%@ taglib uri= "Tagligurl prefilx=" TagPrefix "%>"
5>scriptlet script elements
Declaration to define variable methods <%! 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%> (expression cannot; end)
<%=1+2+3%> Output 6
<%=new java.util.Date (). toString ()%> Output date
Scriptlet: Java code enclosed in <%%>
JSP provides a number of 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 kinds of
<jsp:param> pass one or more parameters to the specified dynamic file, requiring and
<jsp:include><jsp:forward><jsp:plugin> come together to use
<jsp:param name= "paramname" value= "Paramvalue"/>
<jsp:include page= "helloworld.html"/>
<jsp:forward> allows forwarding of current requests to another static file or JSP page or contains a
Servlet with same content as previous page
<jsp:forward page= "confirm.jsp" >
<jsp:param name= "User" value= "AAA"/>
<jsp:param name= "Password" value= "12345"/>
</jsp:forward> turn to confirm.jsp page and pass two parameters user and password
<jsp:plugin> used to play or display an object in the client browser, typically an applet or
Bean, which eventually replaces the browser version with the <object> or <embed>
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>artibute text</jsp:fallback> (When displaying bean| Applet fails to display
Shows this string
6>jsp's built-in objects
JSP provides some built-in objects that are implemented and managed by the container, which can be used directly in the JSP page, not
needs to be instantiated to enable access to the servlet environment of JSP pages by accessing these built-in objects
JSP offers a total of 9 built-in objects: Out of request Repnse session PageContext
Application Config Page exception
The JSP is built on the servlet, and each of the JSP's built-in objects are the classes in the JAVASERVLETAPI package
object, automatically generated when the server is run
JSP provides developers with a mechanism to pass data, using setattribute () and
GetAttribute () method
JSP has four ranges: page Request session Application
Page range refers to the range of JSP pages that are simply a page away from the page.
Pagecontext.setattribute ("Name", "abc"); The value of setting property Name is ABC, which only
Valid in the scope of this page, call (String) Pagecontext.getattribute ("Name") on this page will
Return to "ABC"
The request scope refers to a JSP page that issues requests to another JSP page (include
Order, forward instruction, etc..
Request.setattribute () and Request.getattribute ()
The session range is a period of time that the user continues to connect to the server, but when disconnected from the server, the property
Will fail
The scope of the application takes effect at the start of the server running, and until the server shuts down
So far
The methods for storing and obtaining properties that can be used by the above four types of built-in objects:
void setattribute (String name,object value) sets the value of the Name property to
Enumeration Getattributenamesinscope (int scope) obtains all scope scope properties
Object getattribute (String name) Gets the value of the Name property
void RemoveAttribute (String name) removes the value of the Name property
Note: PageContext does not have a getattributenames () method.
The Out object is encapsulated in the Javax.servlet.jsp.JspWriter interface and can be buffered by an out object
Area to operate
Out objects are usually obtained by the Pagecontext.getout () method
Common method: Public abstract void print ()
public abstract void println ()
public abstract void newline ()//output a newline character
public abstract void Close ()//closes the output stream
public abstract void Clearbuffer () clears the contents of the buffer and the data
Send to Client
public abstract void Clear () clears the contents of the buffer and does not send data to
Client
public int getbuffersize ()//Get the size of the buffer
public abstract int getremaining ()//Get the size of the buffer remaining space
Data for the public abstract void flush ()/Output buffer
Public boolean is AutoFlush ()//Gets AutoFlush value
The request object encapsulates the information submitted by the user and is encapsulated in the
Javax.servlet.http.HttpServletRequest interface
There are four main types of methods:
1. Methods of accessing properties:
Object getattribute (String)
Enumeration Getattributenames (int)
void SetAttribute (String,object)
2. The method of obtaining the parameters of the request itself:
String GetParameter (String) to get the specified parameter name
Enumeration Getparameternames () get all parameter names
String[]getparameternames (String name) gets the parameter value of all name
Map Getparametermap () Gets a map that requires parameters
3. The ability to obtain request HTTP headers:
String GetHeader (string name) gets the header of name
Enumeration Getheadernames () get all the header names
Enumeration Getheaders (String name) gets the headers for all the name
int Getintheader (String name) Gets the header of the integer type name
Long Getdateheader (String name) Gets the header of the date type name
Cookie[] GetCookies () obtain cookies related to the request
4. Other methods:
String Getcontextpath () Gets the context path
String GetMethod () Gets the HTTP method (get| Post)
String Getservletpath () Gets the page that accepts customer submission information
String Getprotocol () acquisition of the protocol used (http/1.1 http/1.0)
String getquerystring () gets the requested parameter string (the HTTP method must be get)
String Getrequestedsessionid () Gets the session ID of the client
String Getrequesturi () Gets the request URL, excluding the requested parameter string
String getremoteaddr () Gets the user's IP address
String Getremotehost () Gets the user's host name
int Getremoteport () Gets the user's host port
String Getremoteuser () Gets the name of the user
void setcharacterencoding (String encoding) encoding format used to resolve form passing
Questions about Chinese
Response object: Is the result of encapsulating JSP processing data, encapsulated in
Javax.servlet.http.HttpServletResponse interface
void Addcookie (Cookie cookie) New cookie
void Adddateheader (String name,long date) New Long value to name header
void AddHeader (string name,string value) new String value to name header
void Addintheader (String name,int value) new value of int type to name header
void Setdateheader (String name,long date) specifies a long value to the name header
void SetHeader (string name,string value) specifies a string of values to the name header
void Setintheader (string name,int value) specifies a string of values to the name header
void Senderror (int sc) pass State Code
void senderror (int sc,string msg) pass status code and error message
void SetStatus (int sc) set state code
String encoderedirecturl (string URL) is compiled using the URL of the Sendredirect () method
Code
Response.setcontenttype ("Text/htmlcharset=big5") change the statement with <%@ page
Contenttype= "text/html;charset=" Big5 "%> equivalence
Cookie technology:
Cookies enable the site to track the number of visits to a particular visitor, the last access time, and the way visitors enter the site
Diameter
Cookie tells the online advertiser how many times the ad has been clicked
Cookies can help the site to count user profiles to achieve a wide variety of personalized services
Creating cookies
Cookie Democookie=new Cookies ("CookieName", "Cookiue")
The Get method in the cookie:
String getcomment () returns a comment in a cookie
String GetDomain () returns the domain name of the cookie in the cookie, and the domain name begins with a point (. yesky.com)
int Getmaxage () returns the maximum time before the cookie expires, measured in seconds
String GetName () returns the name of the cookie
String GetPath () returns the path that the cookie applies to, and if not specified, the cookie is returned to the current page
All pages in the directory and subdirectories of the face
Boolean getsecure () if the browser sends cookies through the security protocol, returns TRUE, using the standard
Quasi-protocol will return false
String GetValue () returns the value of a cookie
int GetVersion () returns the protocol version of the cookie
The set method in the 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);
Cookies sessioncookie=new Cookies ("Jsession", SessionID);
Cookie Setmaxage (30*60);//Survival time is 30 minutes
Response.addcookie (cookie);//write to Customer hard drive
The difference between session and Cookie:
Session is stored in server-side memory
Session with the user's landing and generated, the user offline after the disappearance
Session stored in the server, users can not modify, good security
Session is a continuation of an action state, is a conversation
Session object, which records the access status of each client to track the operational status of each client, is blocked
Installed as Javax.servlet.http.HttpSession interface, you can pass Pagecontext.getsession ()
Method gets a Session object
Methods in the Session object:
Long GetCreationTime () Gets the time the session was generated
String getId () Gets the ID of the session
Long Getlastaccessedtime () Gets the time the user finally sent the request through this session,
Unit: MS
Long Getmaxinactiveinterval () gets the maximum session inactivity time, if more than this
, session will fail unit: seconds
void Invalidate () Cancel Session Object
Boolean isnew () to determine whether the session is a new
void setmaxinactiveinterval (int interval) sets the maximum session inactivity time,
If more than this time, session will be back to failure unit: seconds
Application object, which is responsible for providing some global information about the application running on the server until the
The service is closed and is encapsulated in the Javax.servlet.SertletContext interface
int getmarorversion () obtains container main servlet API version
ing getminorversion () get container minor servlet API version
String Getserverinfo () gets the name and version of container
String GetMimeType (string file) gets the MIME type of the specified file
ServletContext getcontext (String Uripath) obtains the specified localurl
ApplicationContext
String Getrealpath (string path) obtains the local path absolute path
void log (String message) writes the information to the log file
void log (String message,throwable throwable) will stacktrace the resulting exception
The information is written to the log file
The PageContent object is typically used for setting, getting some of the properties of the current JSP page, and being able to access the page
Other suppressed objects (out,request,response,session,application, etc.) and all of its properties,
is encapsulated in the Javax.servlet.jsp.PageContext interface
The four range parameters provided by the Javax.servlet.jsp.PageContext class: Page_scope
Request_scope Session_scope Application_scope
Exception getexception () return the exception to the current page, but this page is for the error page
JspWriter getout () to return the current page output stream, such as out
Object GetPage () The servlet entity that is returning the current page
ServletRequest getrequest () request to return the current Web page
Servletresponse GetResponse () return the response to the current web page
ServletConfig Getservletconfig () return the ServletConfig object of the current page
ServletContext Getservletcontext () return the execution environment of this web page
HttpSession getsession () return current conversations with Web pages
Config object, the main role is to obtain the server configuration information, is encapsulated in
Javax.servlet.servletConfig interface, pain multiple Pagecontext.getservletconfig () method
You can obtain a config object that provides access to the Servlet class initialization parameters and the server environment letter
ServletContext object of Interest
Config object's common methods:
public string Getinitparatemer (string name) gets the server-specified name parameter
Initial value
Public enumeration Getinitparameternames () Gets the name of all the initial parameters of the server
Word
Public ServletContext Getservletcontext () Gets the context of the servlet
Public String Getservletname () Gets the server name of the servlet
A Page object that represents a Servlet class object that is compiled by a JSP file, essentially an instance of object
Exception object, the main function is to display the chant information, representing the JSP file runtime generated by the exception
Object that is an instance of the Java.lang.Throwable class, only if the containing <%@ page
Iserrorpage= "True"%> pages can be used, and using the object in a normal JSP page cannot
Compiling JSP files
I hope this article will help you with the JSP program design.