Three script elements in JSP:
Expression format <% = expression %> JAVA expression. Calculate the expression and output the result.
The result obtained by calculating the Java expression is converted to a string and inserted to the page. Computing is performed at runtime (when the page is requested), so you can access all the information related to the request. For example, the following code shows the date/time requested by the page:
Current Time: <% = new java. util. Date () %>
To simplify these expressions, JSP predefines a set of object variables that can be used directly. For JSP expressions, the most important objects and their types are as follows:
Request: httpservletrequest;
Response: httpservletresponse;
Session: The httpsession associated with the request
Out: printwriter (buffer version, jspwriter), used to send the output to the client
The following is an example:
Your hostname: <% = request. getremotehost () %>
The scriptlet format <% code %> inserts the code into the Servlet's _ jspservice method. Corresponds to the code snippet in the _ jspservice (httpservletrequest, httpservletresponse) method of the servlet class.
Like JSP expressions, scriptlet can also access all predefined variables. For example, if you want to output content to the result page, you can use the out variable:
<%
String querydata = request. getquerystring ();
Out. println ("attached get data:" + querydata );
%>
Note that the code in scriptlet will be copied to the servlet, and the static html (template text) before and after the scriptlet will be converted to the println statement. This means that the Java statements in the scriptlet are not necessarily complete. blocks that are not closed will affect static html outside the scriptlet. For example, the following JSP snippets mix template text with scriptlet:
<%
If (math. Random () <0.5 ){
%>
Have a <B> nice </B> day!
<%
} Else {
%>
Have a <B> lousy </B> day!
<%
}
%>
The preceding JSP code is converted into the following servlet code:
If (math. Random () <0.5) {<br/> out. println ("have a <B> nice </B> day! "); <Br/>}else {<br/> out. println (" have a <B> lousy </B> day! "); <Br/>}< br/>
Declaration format <%! Code %> Add the declaration to the servlet class (except any method ).
Since the Declaration does not have any output, they are often used together with JSP expressions or scriptlet. For example, the following JSP code snippet outputs the number of requests on the current page since the server is started (or the servlet class has been modified and reloaded:
<%! Private int accesscount = 0; %>
Page access times since the server is started:
<% = ++ Accesscount %>