R4R
Right Place For Right Person TM
 
R4R Java JSP

R4R
provide basic JSP Tutorials concept with JSP Examples . Through R4R you can develop JSP programming concept. R4R provide JSP Interview Questions with answers.R4R provide JSP Languages study materials in easy way.

JSP Tutorials

1.1    JSP Basic Tutorials

JSP Examples

2.1    JSP Basic Example

JSP Hot Topics

4.1    JSP Basic Topics
4.2    JSP Tag Library

 

JAVA SERVER PAGES(JSP)

Java server pages (JSP) is based on java languages and used to develop dynamic web pages  JSP was developed by Sun Microsystems to allow server side development. JSP files are HTML files with special Tags containing Java source code that provide the dynamic content.JSP provide excellent server side scripting support for creating database driven web applications. JSP is a java technology which allows developers to create wide ranges of  web services like ecommerce, banking ,corporate intranet banking.  JSP combines HTML, XML, Java Servlet and JavaBeans technologies into one highly productive technology which allow  web developers to develop reliable, high performance and platform independent web applications .

WHY JSP?

JSP is easy to learn. as JSP is based on java it provide robust plateform for web development. JSP file contains the HTML , XML , Java Servlet and Java Beans technologies. you can take one JSP file move it to the different plateform. web server or JSP servlet engine.

ADVANTAGES OF JSP

1.Write once run anywhere:- As JSP is based on java so , it provide it plateform independent functionality .once the program of JSP is written it can be deployed or run on any JSP enabled server. without rewriting the changes

2.Uses Servlet API:-If you are a servlet developer, then it is easy to  move over to JSP. In fact, servlet developers are at a distinct advantage because JSP is nothing but a high-level abstraction of servlets. You can do almost anything that can be done with servlets using JSP in a easy way.

3.Separate dynamic part from the static:- JSP provide  a new feature that it separate a dynamic part of program from the static HTML part

4. JSP container provide easy way for accessing objects and actions.

Compatibility of JSP with ASP , ASP.net ,and Servlet

Comparison between JSP and ASP
Functionally both the languages are same  with some differences. JSP is developed by Sun Microsystems so it acquire the features of  java .while ASP is developed by Microsoft .JSP is plateform independent it run on any operating system that confirm to the J2EE specifications.  Whereas ASP is mostly found on Microsoft platforms i.e. NT, JSP allow component reuse by using JavaBeans and EJBs. ASP provides the use of COM / ActiveX controls.

Comparison of JSP with ASP.net
The  main difference between JSP and ASP .net is that ASP. net is based Microsoft .NET frame work. but  JSP is idependent just like java.

Comparison of JSP with Servlet
A java class which provide special side services is called server.but  t is hard work to write HTML code in Servlets. In Servlets number  of println statements are used  to generate HTML. JSP pages are converted to Servlets so actually can do the same thing as old Java Servlets.

JSP ARCHITECTURE
JSPs are built on SUN Microsystems' servlet technology. JSPs are HTML page with special JSP tags. These JSP tags can contain Java code. The JSP file extension is .jsp . The JSP engine parses the .jsp and creates a Java servlet source file. when first time jsp file compile ,  the JSP is probably slower the first time it is accessed. Any time after this the special compiled servlet is executed and is therefore returns faster.

SETTING UP JSP ENVIRONMENT
1.Download the latest JDK .
2.Setting the path and class path for window  2000 and XP edit the environment variables control panel-->system-->Environment variable 3.Download JSP environment.

FIRST JAVA PAGE
A JavaServer Page,  is a web page which is embedded Java code. Java code is executed in the server side and merge with the static elements of the web page such as HTML tags then returns the result which is plain old HTML code, JavaScript and CSS to the web browser.


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <title>JSP Page!</title>
    </head>
    <body>
        <h1>
            <%
                out.println("Hello to all!");
            %>
        </h1>
    </body>
</html>

JSP is composed of HTML and java code. java code is embedded between the notations <% and %> and it is called Scriplet .Inside the scriptlet block, we call the method println of the out object to print the text "Hello to all"

JSP SCRIPTING ELEMENTS
JSP scripting allows you to add java code the servlet which is generated from the jsp page. These are the forms of scripting elements such ascomments, expression , scriptlet , declaration and expression language.

JSP Comments
JSP comments are used to explain the complicated logic code or to mark some region inside a JSP page for later changes. Comments in JSP is declared inside a JSP page as follows:
comments are embedded inside <%--  and --%>


<%-- This is a JSP comment for single line --%>

<%-- 
   This is a JSP comment for 
   multiple lines
--%>

JSP Expressions
Expression is used to insert values directly to the output. Syntax of expression is as follows

<%= expression %> there is no space between <% and =

for example:
To show the current date and time


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

JSP Scriptlet
Scriplet are just like Expressions without having "=" equal sign. any java code can be insert inside the scriplet.

Syntax of Scriptlet


<% // any java source code here %>

JSP Declaration
If you want to define methods or fields you can use JSP declaration. The JSP declaration is surrounded by the sign <%! and %>.
Syntax to declare a variable


<%! int a = 30; %>
here variable a is declare 

JSP Directive tag

JSP directive tag gives special information about the page to the JSP engine.
Syntax of Directive tag


Directive tag ( <%@ directive ... %> )

there are mainly three type of directive tags
 1.page:- used to provide the information about the page
.2.include: - include is used to include a file in a JSP page.
 3.tag library:-taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own tags).

 

JSP LIFE CYCLE
JSP Life cycle can be divided into four phases
1.Translation:-

In translation phase, JSP engine translate JSP page into its page implementation class if the syntax is correct. This class is actually a standard Java servlet. After that, JSP engine compiles the source file into class file and ready for use. When the container get the request, then it checks for the changes in  the JSP page since it was last translated. If no changes was occur, JSP loads the servlet otherwise the process of check occurs ,then it  translate and compile  again. Because the compilation process takes time so JSP engine wants to minimize it to increase the performance of the page processing
.2.Initialization:-
 JSP engine loads the class file and create an instance of of the servlet to handle processing of the initial request. JSP engines will call a method jspInit() to initialize the a servlet. jspInit method is generated during the translation phase which is normally used for initializing application-level parameters and resource


<%!
   public void jspInit()
   {
      // write custom here  
   }
%>

.3.Execution:-
After the initialization phase, the web container calls jspService() to handle the request and returning a response to the client. Each request is handled in  a separate  thread.
4.Finalization:-
In the finalization phase, the web container calls the method jspDestroy(). This method is used to clean up memory and resources.


<%!
   public void jspInit()
   {
      // write custom code here 
	  //to cleanup the resources 
   }
%>

JSP IMPLICIT OBJECTS
These objects are available for the JSP developer and they can use the objects in the JSP files without declaring the objects in the JSP. JSP container provides a list of instantiated objects for you to access different kind of data in a web application. These objects are called implicit objects as they are automatically available for the implement. The following is the list of few implicit objects used in JSP. request object response objectsession objectout objectpagecontext objectconfig object exception objectapplication object

JSP FORM PROCESSING
The browser uses two methods to pass information to web server. These methods are GET Method and POST Method.

GET Method
The GET method is the defualt method to pass information from browser to web server. The GET method is used to send request to the server. The page and the encoded information are separated by the ? character as follows: http://www.r4r.co.in/hello?key1=value1&key2=value2 Don't send sensitive information like password using GET method because they are not safe. POST method is safe to pass sensible information.

POST METHOD
The post method is good method to passing information to a backend program .  it sends information  as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing.
To handle this type of request JSP uses two methods
1.getparameter method to read simple parameter.
2.getInputStream method to read binary data stream coming from the client.

READING OF DATA USING JSP
JSP used form data parsing automatically depending on the situation. following are the methods which used by the JSP
.1.getParameter():-To get the value of a form parameter you use request.getParameter()
2.getParametervalue():-if the parameter appears more than once and returns multiple values, than use this for example in case of chekbox
3.getParametername():- if you want complete list of all parameters in the current request than used this method
.4.getInputStream() :-getInputStream() is used to read binary data comes from the client side.

 

JSP PROGRAM FOR CHECKBOX USING GET METHOD AND POST METHOD

First to create html form using checkbox
<html>
<body>
<form action="form.jsp" method="POST" target="_blank">
<input type="checkbox" name="java" checked="checked" /> java
<input type="checkbox" name=".net" checked=".net" /> .net
<input type="checkbox" name="C#" checked="C#" />
                                                Chemistry
<input type="submit" value="Select languages" />
</form>
</body>
</html>

following is the "form.jsp" jsp program to handle the input given by the web browser.
<html>
<head>
<title>Reading Checkbox Data</title>
</head>
<body>
<center>
<h1>Reading Checkbox Data</h1>
<ul>
<li><p><b>java Flag:</b>
   <%= request.getParameter("java")%>
</p></li>
<li><p><b>.net Flag:</b>
   <%= request.getParameter(".net")%>
</p></li>
<li><p><b>C# Flag:</b>
   <%= request.getParameter("C#")%>
</p></li>
</ul>
</body>
</html>


JSP CUSTOM TAG

JSP is the technology which helps to separate the front end presentation from the middle and backend tiers. The custom tag library is a important feature of JSP  that comes in that separate form. This technology is valuable to anyone who is building production-quality web applications. It  is a user-defined JSP language element. Custom tag allows programmer to hide code in a Java class and access it from a tag in JSP.Some examples of tasks that can be performed by custom tags include operating on implicit objects, processing forms, accessing databases and other enterprise services such as email and directories, and implementing flow control. Custom tags increase productivity because they can be reused in more than one application.

The following steps are to be taken to create a custom tag.

  1. Create Tag Handler
  2. Create Tag Library Descriptor (.TLD )

3Register TLD in JSP and use tags declared in TLD
The first task is creating a simple tag. This is mainly to understand the overall process involved in creating a custom tag in JSP 2.0.

TAG HANDLER
Tag handler is a Java class that responds to events raised by container when custom tag is encountered. Every Tag handler must implement Tag interface or extend TagSupport class provided by JSP API.

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.util.Date;

public class CurrentTime extends SimpleTagSupport
{

 public void doTag() throws JspException , IOException
 {

   JspWriter out = getJspContext().getOut();
   out.println( new Date().toString());
 }
} // end of class

TAG LIBRARY DESCRIPTOR
TLD file is an XML file containing details of tags. TLD file can be placed any where within WEB-INF indirectory.
The  TLD file provides details regarding the library such as its version and the version of JSP it needs and tags.

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
        PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
	"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>2.0</jsp-version>
  <short-name>st</short-name>
  <tag>
     <name>time</name>
     <tag-class>st.CurrentTime</tag-class>
     <body-content>empty</body-content>
  </tag>       
  
  
  <tag>
       <name>formattime</name>
       <tag-class>st.FormatCurrentTime</tag-class>
       <body-content>empty</body-content>
     
       
    </tag>       
  
</taglib>


REGISTERING  TAG
 
Before a custom tag is used, its tag library descriptor (TLD) is to be registered in JSP using taglib directive. 
taglib directive specifies the name of TLD file and prefix to be used while using the tags in the library.

The following JSP registers st.tld and uses time tag with prefix st.


<%@ taglib uri="/WEB-INF/tlds/st.tld" prefix="st"%>

<st:time/>


Full code of JSP page is as follows:

 CustomTag.jsp
<%@ taglib uri="/WEB-INF/taglib.tld" prefix="custom" %>
<html>
<head>
<title>Custom Tag </title>
</head>
   <body bgcolor="fffff">
   <H1>Welocome ! </H1>
              Custom tag work starts here...
   <custom:empty/>
              here Custom tag work ends...
    Body Content of JSP page write here
   </body>
</html>


Tolal:0 Click:
Show All Comments

Post Your Comments

Your Name:

Your Email ID :
Comments :
URL
  =* Enter SUM

Tutorials,Examples,Questions and Answer

R4R
R4R
R4R
R4R
R4R
R4R
R4R
R4R