Home Tutorial Java Jsp JSP Scriptlets Example

 
 

Share on Google+Share on Google+
JSP Scriptlets Example
Posted on: June 10, 2010 at 12:00 AM
Advertisement
In this section, we will understand Scriptlets with the help of an Example.

JSP Scriptlets Example

In this section, we will understand  Scriptlets with the help of an Example. JSP allows you embed java code inside JSP page. The java code is written inside <% and %> , This block is known as Scriplets. Scriplets is executed every time a JSP page is invoked.The syntax to declare JSP Scriplets to include valid Java code is:   

<%   Java code    %>

Scriptlets can't generate HTML itself . Using "out" variable , it can generate HTML. This variable does not need to be declared.  It is already predefined for Scriptlets, along with some other variables. The "out" variable is of type "javax.servlet.jsp.JspWriter". 

Scriptlets Example

<HTML>

<BODY>

<%

// This scriptlet declares and initializes "date"

System.out.println( "Evaluating date now" );

java.util.Date date = new java.util.Date();

%>

Hello! The time is now

<%

// This scriptlet generates HTML output

out.println( String.valueOf( date ));

%>

</BODY>

</HTML>

 

Output

Predefined Scriptlet variable "request"

The JSP "request" variable is used to obtain information from the request as sent by the browser.  For instance, you can find out the name of the client's host (if available, otherwise the IP address will be returned.)  Let us modify the code as shown :

<HTML>

<BODY>

<%

// This scriptlet declares and initializes "date"

System.out.println( "Evaluating date now" );

java.util.Date date = new java.util.Date();

%>

Hello! The time is now

<%

out.println( date );

out.println( "<BR>Your machine's address is " );

out.println( request.getRemoteHost());

%>

</BODY>

</HTML>

 

OUTPUT

A similar variable is "response".  This can be used to affect the response being sent to the browser.  For instance, you can call response.sendRedirect( anotherUrl ) to send a response to the browser that it should load a different URL

Advertisement

Related Tags for JSP Scriptlets Example:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 10, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com