Java Forums

Main Menu
Home
Today's Posts
FAQ
Search
Contact Us

Java Network
Java Tips
Java Tips Blog

Sponsored Links





Welcome to the Java Forums.

You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community, you will:

  • have access to post topics
  • communicate privately with other members (PM)
  • not see advertisements between posts
  • have the possibility to earn one of our surprises if you are an active member
  • access many other special features that will be introduced later.

Registration is fast, simple and absolutely free so please, join our community today!

If you have any problems with the registration process or your account login, please contact us.

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 02-17-2008, 12:17 PM
Member
 
Join Date: Nov 2007
Posts: 23
Java Tutorial is on a distinguished road
Java Server Pages (I)
This is the age of dynamic web sites. Gone are the days when people used to feel proud of their static sites. Now even business is done online and you need dynamic web sites to deal with this.

Java provides JavaServer Pages (JSP), which enables the development of dynamic web sites. JSP files are simple text files with JSP extension. These include HTML code along with Java code. Java code is executed on the server and the user only gets HTML code in the browser.
JSP is multi platform and also it can be used as a component by using JavaBeans and EJB.

Web servers

You need to web server on your machine to start running JSP pages. There are many JSP supported web servers available. Few of them are as follows:

Blazix from Desiderata Software (1.5 Megabytes, JSP, Servlets and EJBs)
TomCat from Apache (Approx 6 Megabytes)
WebLogic from BEA Systems (Approx 40 Megabytes, JSP, Servlets and EJBs)
WebSphere from IBM (Approx 100 Megabytes, JSP, Servlets and EJBs)

Hello World JSP

JSP page comprises of HTML code along with Java code. Server side code is enclosed under <%%> tags.
Code:
<HTML> <BODY> <% out.println( "Hello World" ); %> </BODY> </HTML>

JSP Tags

There are 5 different types of JSP tags.

- Declaration tag
- Expression tag
- Directive tag
- Scriptlet tag
- Action tag

Declaration tag

Declaration tag is used to declare variables and methods. Declarations are enclosed under
Code:
<%! %>
All the code written in this declaration tag must end in a semicolon ( ; ).
<%!
private int counter = 0 ;
private String getName ( int id) ;
%>

Expression tag

Extression tag ( <%= %>) is used to execute Java expressions. It is a shot form of out.println(). Thing to remember is that you should not place a semicolon ( at the end of code inside this tag.

Code:
Date : <%= new java.util.Date() %>
Directive tag

A JSP directive ( <%@ directive ... %>) gives JSP engine some special information about the page. There are different types of directives:

- page directive (for processing information for the page)
-include directive (to mention the files to be included)
-tag library (to mention the tag library to be used in the page)


JSP directives change the way the JSP Engine processes the page but do not produce any visible output when the page is requested.

Page directive

The page directive has many optional attributes. One should use only the ones that are needed. Syntax of page directive is as follows:

Code:
<%@ page [ language="java" ] [ extends="package.class" ] [ import="{package.class | package.*}, ..." ] [ session="true | false" ] [ buffer="none | 8kb | sizekb" ] [ autoFlush="true | false" ] [ isThreadSafe="true | false" ] [ info="text" ] [ errorPage="relativeURL" ] [ contentType="mimeType [ ;charset=characterSet ]" | "text/html ; charset=ISO-8859-1" ] [ isErrorPage="true | false" ] %>
Lets take few examples:

Code:
<%@ page import="java.util.*, java.lang.*" %> <%@ page buffer="5kb" autoFlush="false" %> <%@ page errorPage="error.jsp" %>

Presented below is an example that shows how to import a class from a package and how to use it.

Code:
<%@page import="package1.Class1" %> <html> <head><title>Example</title></head> <body> <font size="20" color="red"> <% Class1 obj = new Class1(); out.print(obj.show()); %> </font> </body> </html> … package package1; public class Class1{ public String show(){ return "JSP Tutorial"; } }
Include directive

We use include directive to include files into our JSP. An example would be header or footer files.


Code:
<%@ include file = "include/privacy.html" %> <%@ include file = "navigation.jsp" %>
Tag Lib directive

Tag lib contains custom tags that can be used in JSP. There are some standard taglibs available. You may write your own taglib as well. These taglibs are included into JSP using taglib directive.

Code:
<%@ taglib uri = "tag library URI" prefix = "tag Prefix" %>


@page buffer example
The buffer attribute sets the buffer size in kilobytes that is used by the out object to handle output generated by the JSP page on the client web browser.
Code:
<%@page buffer="5kb" autoFlush="false" %> <% for(int i = 0; i < 10; i++){ out.println("<html><body><img src=images/marijuana_leaf.jpg /> </body></html>"); } %>
IsThreadSafe attribute

isThreadSafe attribute of the page directive supports the facility of maintaining thread for sending multiple and concurrent requests from the JSP container to the JSP page. The default value for this is true. If it is specified as false, then the JSP container can send only one request at one time. Review the example below:

Code:
<%@page isThreadSafe="true" %> <html> <head><title>Example of isThreadSafe attribute of page directive in JSP.</title></head> <body> <table border="1" cellspacing="0" cellpadding="0" bgcolor="ffff00"> <tr> <td><strong>This is the example of isThreadSafe attribute of page directive.</strong></td> </tr> </table> </body> </html>
info Attribute

Page directive has an info attribute that simply sets the information of the JSP page which is retrieved later by using Servlet.getServletInfo() method. The value of the attribute will be a text string.

Code:
<%@page info="This is the example of info attribute of the page directive." %> <html> <head><title>Info Attribute of page directive in JSP.</title></head> <body> <% out.println("Example of the info attribute of the page directive in JSP."); %> </body> </html>
errorPage attribute

JSP page directive includes an errorPage attribute which sets a url for an error page. If any exception is generated then the attribute refers to the file which is mentioned in the given url. What if you do not mention errorPage attribute since it is optional? Then exception will be displayed in the current page.

Code:
<%@page errorPage="error.jsp" %> <html> <head><title>Showing Error Page.</title></head> <body> <form method="post"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td>Enter a number: </td> <td><input type="text" name="txtNum" /> </tr> <tr> <td>&nbsp;</td> <td><input type="submit" name="B1" value= "Divide by zero" /> </tr> </table> </form> <% if(request.getParameter("txtNum") != null){ if(!request.getParameter("txtNum").equals("")){ int div = Integer.parseInt(request. getParameter("txtNum")) / 0; out.println("Answer is: " + div); } else{ out.println("<html><font color=red>Please enter a number.</font></html>"); } } %> </body> </html>
error.jsp

Code:
<%@page isErrorPage="true" %> <html> <head><title>Error Page.</title></head> <body bgcolor="blue"> <font size="16" color="white">Your page generated an error:"<br/> Exception:<br/></font> <%= exception.toString() %> </body> </html>
contentType Attribute

The contentType attribute of the page directive in JSP specifies the MIME type and the character encoding that is used for the JSP response. The default MIME type is "text/html" and the default character set is "ISO-8859-1".


Code:
<%@page contentType="text/html" %> <html> <head><title>Example of contextType attribute of page directive in JSP.</title></head> <body> <table border="1" cellspacing="0" cellpadding="0" bgcolor="ffff00"> <tr> <td><strong>This is the html page.</strong></td> </tr> </table> </body> </html>
The above example was a simple one, which displays the contents in the browser in normal web form.

Now lets try to set the type to xml and see what happens.

Code:
<%@page contentType="text/xml" %> <html> <head><title>Example of contextType attribute of page directive in JSP.</title></head> <body> <table border="1" cellspacing="0" cellpadding="0" bgcolor="ffff00"> <tr> <td><strong>This is the xml page.</strong></td> </tr> </table> </body> </html>
The output of the above example will be in XML form on the browser.

Scriptlet tag

Scriptlet tag ( <% ... %> ) is used to write valid Java code in a JSP. This code can access variables and methods or even bean that is declared.

Code:
<% String username = "Dave" ; out.println ( username ) ; %>
Action tag

Action tag is used to enable the use of JavaBeans, to transfer control between pages and for browser independent support for applets.

To use a JavaBeans in a JSP page use the following syntax:


Code:
<jsp : usebean id = " ...." scope = "application" class = "com..." />
As you must have noted, we have used application scope in the example below. There are 4 different scopes you may use.

page - valid until page completes.

request - bean instance lasts for the client request

session - bean lasts for the client session.

application - bean instance created and lasts until application ends.

JSP loop example

Presented below is a simple JSP loop example.

Code:
<HTML> <HEAD> <TITLE> JSP loop</TITLE> </HEAD> <BODY> <font face=verdana color=darkblue> JSP loop <BR> <BR> <%! public String writeThis(int x) { String myText=""; for (int i = 1; i < x; i ) myText = myText "<font size=" i " color=darkred face=verdana> JSP Tutorial</font><br>" ; return myText; } %> This is a loop example from the <br> <%= writeThis(8) %> </font> </BODY> </HTML>
Implicit objects

There are several objects that are automatically available in JSP called implicit objects. You are not required to declare or instantiate them, they are ready to use. JSP includes following implicit objects:

Request (Javax.servlet.http.httpservletrequest)
Response (Javax.servlet.http. httpservletresponse)
Out (Javax.servlet.jsp.JspWriter)
Session (Javax.servlet.http.httpsession)
PageContent (Javax.servlet.jsp.pagecontext)
Application (Javax.servlet.http.ServletContext)
Config (Javax.servlet.http.ServletConfig)
Page (Java.lang.Object)

Request object is used to access to information associated with a request. This object is normally used in looking up parameter values and cookies.

Code:
<% String str = request.getParameter("username"); %> User = <%= str %>
The code snippet presented above gets the parameter named username and displays it.

A from example

Presented below is a simple HTML form with a text field.

Code:
<html> <head> <title>Welcome</title> </head> <body> <form action="welcome.jsp" method="post"> Enter your name:<br> <input type="text" name="name"><br> <input type="submit" name="submit"> </form> </body> </html>
The form posts to welcome.jsp which is used for processing.

welcome.jsp

Code:
<html> <head> <title>Welcome</title> </head> <body> <font size=3> We received your information. <br><br> <% String sName = request.getParameter("name"); out.print(sName); %> </font> </body> </html>
Session example

Lets make the example a bit complex. Presented below is a simple HTML form which posts to session.jsp.

Code:
<html> <head><title>Disable Session Environment.</title></head> <body> <form action="session.jsp" method="post"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td>User Name: </td> <td><input type="text" size="20" name="txtUserName" /> </tr> <tr> <td>Password: </td> <td><input type="password" size="20" name="txtPassword" /> </tr> <tr> <td>&nbsp;</td> <td><input type="submit" value="Submit" name="B1" /></td> </tr> </table> </form> </body> </html>
Now lets review session.jsp. It gets the username and password from the posted form. If the username and password are not null, then they are stored in the session variables and a link is provided to navigate to.

Code:
<%@page language="java" %> <% String userName = request.getParameter("txtUserName"); String password = request.getParameter("txtPassword"); if(userName == null) userName = ""; if(password == null) password = ""; if(!userName.equals("") && !password.equals("")){ session.setAttribute("SessionUser", userName); session.setAttribute("SessionPassword", password); out.println("Welcome " + userName + "!"); out.println("<br/><a href=sessionresult.jsp> Next Page with session true.</a>"); out.println("<br/><a href=ShowFalseSession.jsp> Next Page with session false.</a>"); } else if(userName.equals("")){ out.println("<font color=red><b>User name required.</b></font>"); out.println("<br/><a href=sessionForm.jsp>Go back!</a>"); } else if(password.equals("")){ out.println("<font color=red><b>Password required.</b></font>"); out.println("<br/><a href=sessionForm.jsp>Go back!</a>"); } %>
sessionresult.jsp simply prints the username and password stored in the session variables.


Code:
<%@page language="java" session="true" %> <% String username = (String)session.getAttribute("SessionUser"); String password = (String)session.getAttribute("SessionPassword"); out.println("<b>Welcome " + username + "!</b>"); %>
ShowFalseSession.jsp

Code:
<%@page language="java" session="false" %> <% out.println("The value of session attribute is false!"); %>
Request object – getQueryString

This getQueryString method of equest object is used for getting the query string which comprises of value of the attribute of the html from where the jsp page is referenced. There all attribute of the form with form attributes is available in the query string.

Code:
<html> <head><title>getQueryString() method of request object.</title></head> <body> <form method="get"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td>User Name: </td> <td><input type="text" size="20" name="txtUserName" /> </tr> <tr> <td>Password: </td> <td><input type="password" size="20" name="txtPassword" /> </tr> <tr> <td>&nbsp;</td> <td><input type="submit" value="Submit" name="B1" /></td> </tr> </table> </form> <% if(request.getQueryString() != null) out.println(request.getQueryString()); %> </body> </html>
Request object – getRequestURI

Request object provides getRequestURI method for getting the information of the URI of the current page of your JSP application. It returns the URI of the current page from the URL (Unified Resource Locator). The retrieved URI is the string, which is mentioned in the URL after the host name up to the current page. The retrieved URI does not contain the host name or any parameter mentioned from the query string after the page name in the URL.
Review the example below:

Code:
<html> <body> <form action="GetRequestURIMethod.jsp" method="get"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td>User Name: </td> <td><input type="text" size="20" name= "txtUserName" /> </tr> <tr> <td>Password: </td> <td><input type="password" size="20" name="txtPassword" /> </tr> <tr> <td>&nbsp;</td> <td><input type="submit" value="Submit" name="B1" /></td> </tr> </table> </form> </body> </html>

GetRequestURIMehtod.jsp

Code:
<% out.println("<b>" + request.getRequestURI() + "</b>"); %>
Bookmark Post in Technorati
Reply With Quote
Sponsored Links
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Java Server Pages (II) Java Tutorial Java Tutorials 0 03-12-2008 07:03 PM
JSP pages with no caching Java Tip Java Tips 0 01-31-2008 01:53 PM
Getting all the pages from a domain eva New To Java 0 12-25-2007 12:41 PM
Help with IRC server in java mathias Networking 1 08-07-2007 07:51 AM
Java Server Pages - Introduction JavaForums Java Blogs 0 08-06-2007 04:41 PM


All times are GMT +3. The time now is 07:43 PM.


VBulletin, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2007, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org