Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
238
Chapter 10 JSP Scripting Elements
10.3 JSP Scriptlets
If you want to do something more complex than insert a simple expression,
JSP scriptlets let you insert arbitrary code into the servlet's 
_jspService
method (which is called by 
service
). Scriptlets have the following form: 
<% Java Code %>
Scriptlets have access to the same automatically defined variables as
expressions (
request
, 
response
, 
session
, 
out
, etc.; see Section 10.5). So,
for example, if you want output to appear in the resultant page, you would
use the 
out
 variable, as in the following example.
<% 
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData); 
%>
In this particular instance, you could have accomplished the same effect
more easily by using the following JSP expression:
Attached GET data: <%= request.getQueryString() %>
In general, however, scriptlets can perform a number of tasks that cannot
be accomplished with expressions alone. These tasks include setting response
headers and status codes, invoking side effects such as writing to the server
log or updating a database, or executing code that contains loops, condition 
als, or other complex constructs. For instance, the following snippet specifies
that the current page is sent to the client as plain text, not as HTML (which is
the default).
<% response.setContentType("text/plain"); %>
It is important to note that you can set response headers or status codes
at various places within a JSP page, even though this capability appears to
violate the rule that this type of response data needs to be specified before
any document content is sent to the client. Setting headers and status codes
is permitted because servlets that result from JSP pages use a special type
of 
PrintWriter
 (of the more specific class 
JspWriter
) that buffers the
document before sending it. This buffering behavior can be changed, how 
ever; see Section 11.6 for a discussion of the 
autoflush
 attribute of the
page
 directive.
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

jsp web hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Jsp Web Hosting Cheapest Web Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved