When the bill amount exceeds Rs. 1000 then else part of calc.jsp gets executed and it forwards the request to discount.jsp page . [Read more…] about Bill Discount JSP Program
<j sp: forward page= “desturl” />
This tag is used to forward the request from one JSP program to another JSP program, which participate in the chaining. This tag internally uses rd.forward(-,-) method. The task of this tag is similar to that of the forward mode of the servlet chaining. By using this tag, it can forward the request from source JSP program to the destination web resource program. But this tag discards the HTML output of the source JSP program and displays the HTML output of the destination JSP program.
<body bgcolor=”cyan” >
ENTER NUMBER <input type=”text” name=”t1″ />
<input type=”submit” value=”Find” />
<input type=”reset” value=”Reset” />
input.html takes the request from user and then forwards it to Square.jsp page.
<font color=”red” size=”5″>
SQUARE OF <%=request.getParameter(“t1”) %> IS:
String num=request.getParameter(“t1”) ;
<jsp:param name=”num” value=”<%=n %>” />
After getting the given number from the input.htrnl page, Square.jsp, calculates the
square of the program.
When an user enters a number more than 50, then the else block of Square.jsp gets
executed, where the following logic is written:
<jsp:forward page=”Cube.jsp” >
<jsp:param name::;”num” value::”<%:=n %>” />
for forwarding the request to Cube.jsp page. Then Cube.jsp code gets executed.
<font color=”red” size=”5″>
CUBE OF <%=request.getParameter(“num”) %> IS:
<% @ include file= “desturl” %>
<JSP: directive. include file= “desturl” />
This tag is given to include the code of the destination web resource program to the source code of the JSP equivalent servlet program that belongs to the source JSP program. In this case, the destination web resource will not be executed separately, rather by using this concept, the code of the destination web resource program is included within the JSP’ equivalent servlet program of the source JSP program.
The directive include tag does not perform output inclusion rather it performs code inclusion.
The <]SP: include> tag is given to include the output of the destination web resource program. The <]SP: include> tag is used for output, not the code of the destination web resource program. In this case, there are two separate ]SP equivalent servlet programs, which are generated and executed separately and the output generated for the destination web resource program aSp program) that is included in the output of the source web resource program which is also a ]SP program. So, we can say that <]SP: include>tag is a tag based alternate for “rd. include” of the servlet program. These action tags of ]SP can be used only with XML syntax as compared to the other tags of the JSP.
<font color=”red” size=”5″ >
BEGINNING OF FIRST JSP
PASSING SOME DATA FROM FIRST.JSP TO SECOND. JSP
<jsp:include page=”Second.jsp” >
<jsp:param name=”name” value=”Neeraj Dadwal” />
<jsp:param name=”roll” value=”1″ />
<font color=”red”>END OF FIRST JSP</font>
<%@ taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c” %>
<title> jsp include</title>
<font color=”green” size=”5″ >
BEGINNING OF SECOND JSP
NAME : <%=request.getParameter(“name”) %>
END OF SECOND JSP
Here, the output comes from First.jsp by including the output of Second.jsp inside its body.
The intention is to introduce the communication in between the servlet and JSP. The welcome page is designed by the HTML code.
<center><font color=”black” size=”8″>Enter A Number:</font>
<input type=’text’size=’50’ name=”t1″><br><br>
<input type=’submit’ value=’submit’ name=”b1″ />
<input type=’reset’ value=’reset’ name=’b2’/>
out.println(“<center><font color=’red’ size=’8′>”);
out.println(“Square of The Number is=”+res);
out.println(“<br><br><center><font color=’red’ size=’6′>Your selection Does
not Vary The Condition..”);
Explanation of the above program
The aim of this program is to find out the square of the number if the result is greater than 100, then it goes to the JSP program, otherwise it goes to servlet program.
As the JSP program communicates, with the servlet program, the URL pattern of the servlet program is passed into the form action.
• int no=Integer.parseInt(request.getParameter(“tl”));
The number which is passed that is read by the getParameter() and assign in the no variable of int type.
• int res=no*no;
The square of the number is calculated and assigned to the res variable of int type.
out.println(“<center><font color=’red’ size=’8′>”) ;
out.println(“Square Of The Number Is=”+res);
If the result requested is greater than 100, then it calculates the square of the number.
If the result is less than 100,we pass the request then through the RequestDispatcher object to the servlet program, where the cube of the number is calculated.
• catch(Exception e)
The exception is handled by the catch block.
The square of the number 25 is 625 and it is greater than 100, so the request goes to the SP page and processing is done.
But if the square of the number is greater than or less than 100, then the request goes to the servlet program and calculates the cube of the number.
This time we pass the number 2 and the square of the number is 4 and it is less than 100, so the request goes to the Servlet program through the RequestDispatcher object that’s why we pass the URL pattern of the servlet program in RequestDispatch method.
In the below JSP program the aim is to understand how JSP communicates with the database. The designing is done by HTML.
<form action= “DB-JSP.jsp”>
<body bgcolor= ‘white’>
<h1 align=”center”><font color= ‘Black’ size=’8′ >Search Employee Details</font></h1>
<br><Center><font color= ‘Gray’ size= ‘6’ >Enter Employee Id</font>
<input type=’text ‘ size= ’20’ name=’t1′>
<input type=’Submit’ value=’Submit’ name=”b1″ />
<input type=’Reset’ value= ‘RESET’ name= ‘b2’/>
<%@ page import=”java.sql.*” %>
String uid = “root”;
String psw = “root”;
Connection con=DriverManager.getConnection (url,uid,psw) ;
Statement st=con.createStatement ();
ResultSet rs = st.executeQuery(“select * from emp where EMPNO=”+empno);
if (rs.next ())
out.println(“<center><table border=’15’ color=’red’><tr><th>EMPNAME
out.println(“<center><font color=’red’ size=’7′>Invalid Id Try Again</font></center>”);
Explanation of the above program
• Class.forName(“oracle.jdbe.driver.Oracle Driver”);
It loads the type-4 driver.
It establishes the connection.
• Statement st=con.createStatement();
It creates the statement.
• String empno=request.getParameter(“tl”);
It reads the employee number through the getParameter(); of the request interface.
• ResuItSet rs=st.exeeuteQuery(“select * from EMP where EMPNO=” +empno);
This statement executes the query and retrieves the information from the EMP table and stores all the value in the ResultSet object.
If (rs.next) returns true then a table will be formed and all the values which are retrieved from the EMP table of the database are stored in that table and displayed on the browser through the out.println () ;.
• out.println(“<center><font color=’red’ size=’7′>Invalid Id Try Again</font></center>”);
If (rs.next) returns falls then it print “Invalid Id Try again” on the browser window as the response.
• catch(Exception ee)
The generated exception is handled by the catch block.
When we send any request to the JSP program from the browser window, we pass the request URL in the browser window. In this process to send the data along with the request, the programmer also requires adding the query string to request URL explicitly. But this task is highly of technical. For that a graphical user interface is required which can generate a request which mayor may not hold the data. For this purpose, the programmer can use either HTML form or hyperlink to generate the request with or without data. The example of HTML to JSP communication is given below:
<title>HTML TO JSP COMM</title>
<font color=”blue” size=”8″><b>Date & Time is :</b></Font></center>
Explanation of the above program
In order to display the date and time within the scriptlet tag (<%——-%>) we use the Date class, which prints the current date and time in the browser window. This Date class present in the util package, that’s why it needs to be imported.
<% java.util.Date d=new java.util.Date();
In this Example we will discuss about how to read text file with the JSP objects. First we create a text file that contains strings in it. In the program we use input and output stream for execute the expression.
We put the text file in the WEB/INF folder where it will be fetched in the program we just give the reference of this folder. For storing the content of a file we also use the buffered reader function. readLine method also used to read the content of text file stored in WEB/INF folder.
<%@ page import=”java.io.* “%>
<title><ReadingTextFile> In JSP</title>
String fileName = “/WEB-INF/Reading.txt”;
InputStream instrm = application.getResourceAsStream(fileName);
if(instrm == null)
BufferedReader bfrdr = new BufferedReader((new InputStreamReader(instrm)));
while((cntnt= bfrdr.readLine())!= null)
<table border=”1″ align=”center” cellpadding=”2px” cellspacing=”2px” align=”center”>
<span><h2 align=”center”>Server Information</h2></td></span>
<td>Server Name:</td> <td><%=request.getServerName() %></td>
<td>ServerPort: </td> <td><%=request.getServerPort() %></td>
<td>Query String: </td> <td><%= request.getQueryString() %></td>
<td>Servlet Path: </td> <td><%= request.getServletPath() %></td>
<td>Server Protocol:</td> <td><%= request.getProtocol() %></td>
<td>Server Scheme:</td> <td><%=request.getScheme() %></td>
<td>RemotePort = </td> <td> <%=request.getRemotePort() %></td>
<td>Remote Host = </td> <td> <%=request.getRemoteHost() %></td>
<td>Request URI: = </td> <td><%= request.getRequestURI() %></td>
<td>Request Method: = </td> <td><%= request.getMethod() %></td>
<td>Content Length: = </td> <td><%= request.getContentLength() %></td>
In this example we will define that about page counter every time a user visit the page will be counted. In this we made a program where i static click variable initialize and the value declare 0. If any user visit site any tym it will display the visit number. With help of for loop it will increase the visits one by one.
<title><Jsp Page Counter></title>
<%!static int click=0; %>
if (click == 0)
<br><h3 align=”center”><% click ++;
out.println(“Welcome To Java Server Page Counter”); %> </br>
<% out.println(“Visitor Number : “);%> <%=click %>.</h3>
<br><h3 align=”center”><% out.print(“Welcome…!”);%></br>
<h3 align=”center”><% out.print(“You are Visitor Number : “);%> <%=click %>.</h3>
Jsp expressions known as those kind of expressions that are containing the scripting language values. To Display the expression value we create a HTML tags page that will use to fill the required fields that will be displayed according to need.
Here we redirect the html page on an actual page where all the functions will be elaborate. As for this we made two forms like first which will use as the HTML code then second that will take the reference of first page. The value which it will receive from first form will displayed on the web browser as Output both form contains the required attribute and java packages to for io exceptions etc..let’s take a look on the program we made.
<form action=”Expression.jsp” method=”get”>>
<table cellpadding=”2px” cellspacing=”1px” bgcolor=”#f7f9fb” width=”400px”align=”center”>
<td align=”center” colspan=”2″>
<td align=”center” width=”60%”>User Name: <input type=”text” name=”text”maxlength=”40″/></td>
<td align=”center”><input type=”submit” value=”Submit” /></td>
<%String identity= request.getParameter(“text”);%>
Does not support buffering
Does not use BufferWriter internally
Uses BufferWriter, PrintWriter internally
Can create class of java.io.* package
Abstract class of javax.servlet.jsp package
Its print (-) method does not throw IOException
Its print (-) method throw
Useful for servlet programming
It is the type of implicit object out in JSP
We know servlet program is placed in WEB-INF folder. WEB-INF is a private directory of deployed web application. So any web resource program that is placed in WEB-INF folder or its subfolder (like classes) must be configured in web.xml file to make the underlying container and server recognizing web resource program.
A JSP program can have two types of objects.
• Explicit objects
• Implicit objects [Read more…] about Exploring Implicit Objects
Used for commenting JSP tags base code (or JSP code) of JSP program. A JSP page compiler recognizes JSP comments. As JSP comments are visible in source, code of JSP program and not visible in any other process of JSP program execution so these are called hidden comments. They are written like this:
Used for commenting html code and text of JSP program. Html interceptor recognizes this type of comments. We use html comment on scripting JSP tags (scriptlet, declaration and expression) but we cannot use these comments on other JSP tags. They are written like this:
<!– ……………..–>Script comments
Java compiler recognizes this type of comments.
//:-used for commenting one line of code
/*….* /: -used for commenting multiple line of code
Visibility Chart of JSP Comments
Compiled of java equivalent Servlet
Html code that comes to browser
A JSP page contains tags. The tags are in the form of scripting tags, directive tags and comments. Tags help programmers to develop Java codeless JSP program. Implicit objects increase the functionality of JSP page. Scripting element also helps in generating dynamic content and displaying dynamic content. [Read more…] about JSP Scripting Elements
Life cycle of a program includes the phases starting from creating objects for the class, execution, and at last destruction of objects. For this life cycle, JSP needs some life cycle methods.
The method that is called by container automatically and directly when event is raised is called life cycle method. The methods which are called internally from this life cycle methods are called life cycle convince helper methods.
Life cycle of JSP is similar to Servlet life cycle.
In the execution phase of JSP page, first JSP page is translated into an equivalent Servlet, then the source file of the Servlet is compiled into a .class file. Every time a JSP page is requested, its corresponding Servlet will be executed. So life cycle of JSP is similar to Servlet life cycle.
JSP Life-Cycle Methods
The methods called by the container automatically when event is raised are called life-cycle methods.
As you know, JSP page is first converted into an equivalent Servlet program, so life cycle method of JSP is same as Servlet life-cycle method. But Sun Microsystems has given three life-cycle convince methods as alternatives to original life-cycle methods.
for init(-) _jspInit()
destroy () ……._jspDestroy ()
init(-) method internally calls the convince method _jsplnit() from super class of JSP equivalent servlet class.
service(-,-) internally calls the convince method _jspService(-,-) from super class of JSP equivalent servlet class.
destroy() internally calls the convince method _jspDestroy() from super class of JSP equivalent servlet class.
The super class for JSP equivalent Servlet is server dependent. In Tomcat server, the super class is org.apache.jasper.runtime.Http]spBase. Every JSP equivalent Servlet is HttpServlet by default.
Main Stages of The Life-Cycle Of A JSP Page
• JSP Page compilation
• Source Code Compilation
• Life Cycle ConvinceMethodExecution
JSP Page Compilation
Page compilation: The process of converting JSP code into an equivalent Servlet program code is called JSP page compilation.
In this phase, web container translates the JSP page into an equivalent Servlet code. The main objective of page translation is to convert the tag based code into more Java code for smooth execution by the JVM. The translation of JSP is automatically done by the server at the time of deploying web application or JSP receives the request for the first time.
In this phase, web container performs the activity like locating requested JSP page, validating the syntactic correctness of the JSP pages, and generating source code of equivalent Servlet code for JSP page.
i. Source code compilation:
In this stage, JSP container compiles the Java source code i.e. the equivalent servlet code and converts into Java byte (.class) code. Generally, most servers like web logic, discard the generated source code after compilation phase.
ii. Life cycle convinces methods execution:
Initialization: After the compilation phase, web container loads the class file. To create instance of Servlet class, ISP container uses the no-argument constructor. After that the container initializes the objects by invoking the init(ServletConfig) method. This method is called jsplnit() method.
Request processing: In this stage, web container uses the successfully initialized ISP equivalent Servlet objects to process client request. As per Servlet life cycle web container invokes service(-,-) method on the Servlet object by passing the request object of HttpServletRequest and response object of HttpServletResponse. In case of JSP equivalent Servlet. the container invokes the _jspService() method.
Destroying: If Servlet container wants to destroy the instances then it performs the following activities-First it allows time to currently executing threads to complete their operations and simultaneously it makes Servlet instance unavailable for other requests. After the current threads complete their operations on service( -,-) method, then the container calls the destroy() method on a Servlet instance, which invokes the jspDestroy() method.
Creating a Simple JSP Page
Here we are creating a simple web application which will show current system date and addition of numbers. Till know we have not discussed the various tags like scriptlets, directives. So this will give you an idea about how ISP program is designed, used, deployed in server, and accessed through browser windows.
Procedure to Develop and Deploy JSP-based Web Application
Settings needed: A web server or application server (here we have taken Tomcat
Jar file to be set in the CLASSPATH: Servlet-api.jar or jsp-api.jar file have to be set to the CLASSPATH.
To set jar file to CLASSPATH: Copy the path of the jar file from the address bar of folder where Tomcat is installed as shown:
F:\ Tomcat 6.0\lib \servlet-apLjar
Right click on my computer
Click advanced tab
Click environment variables
Click ‘new’ button of system variables and set
variable name: CLASSPATH
variable value: F:\ Tomcat 6.0\lib \servlet-api.jar; (paste and insert ‘;’ at the end) click OK for installation Tomcat server.
Development of Web Application
Step 1 Create a deployment directory structure like this
Here WEB-INF, web.xml is case sensitive and .jsp file should be placed parallel to WEB-INF folder
Step 2 Welcome.jsp
<hl> <center> Welcome to JSP </center> </hl>
<b> <center> <font size=5>Systems date and time is :- </font> </center> </b>
<% java.util.Date d=new java.util.Date (); %>
<body> <font color=“red” size=6/> <center>
out.println (d.toString ());
Save this file as Welcome.jsp, the extension is .jsp
Step 3 Configuration of web.xml in JSP program is optional
You can make web.xml as
Deploy the web application
Step 4 Start the Tomcat server
Click F:\Tomcat 6.0\bin\tomcat6.exe file (or) Open command prompt and specify the path of bin folder of Tomcat and type as given below:
F:\Tomcat 6.0\bin>java -jar bootstrap.jar and press enter
Step5 Copy the JspApp folder and paste in F:\ Tomcat 6.0\ webapps folder
Step6 Testing of web application
Open browser window and write in the address bar of browser as follows:
localhost: Because system is not in network, if system is in network then type IP address of the system in place of local host.
8080: It is the port number of Tomcat. You can give any 4-digit number at the time of Tomcat installation.
JspApp: is the JSP application folder name.
After giving request to browser window, the JSP equivalent Servlet code (JES) and .class file will create in F:\Tomcat 6.0\work\catalina\localhost\jspApp\org\apache\jsp
And the JES code will like this…
public final class Welcome_jspextends org.apache.jasper.runtime.HttpJsp
Base implements org.apache.jasper.runtime.JspSourceDependent
private static final JspFactory_jspxFactory =
private static java.util.List_jspx_dependants;
public object getDependants ()
public void_jsplnit ()
_el_expressionfactory = _jspxFactory.getJspApplicationContext
(getServletConfig ().getServletContext ()).getExpressionFactory ();
_jsp_annotationprocessor = (org.apache.Annotationprocessor)
getServletConfig ().getServletContext ().getAttribute
public void_jspDestroy ()
public void_jspService (HttpServletRequest request, HttpServlet
Response response) throws java.io.IOExcption, Servletexception
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null”;
JspWriter out= null;
Object page= this;
JspWriter_jspx_out = null;
PageContext_jspx_page_context = null;
pageContext = _jspxFactory.getPageContext (this, request,
response, null, true, 8192, true);
_jspx-page_context = pageContext;
application = pageContext.getServletContext ();
config = pageContext.getServletConfig ();
session = pageContext.getSession ();
out = pageContext.getOut ();
_jspx_out = out;
out.write (“<hl> <center> Welcome to JSP </center> </hl>\r\n”);
out.write (“<b> <center> font size=5>Systems date and time is:-
</font> </center> </b>\r\n”);
java.util.Date d=new java.util.Date();
out.write (“\r\n”) ;
out.write (“<body> <font color=\“red\” size=6/> <center>\r\n”);
out.println (d.toString ());
catch (Throwable t)
if (! (t instanceof SkipPageException))
out = _jspx_out;
if (out != null && out.getBufferSize () !=0)
catch (java.io.IOException e)
if (_jspx-page_context != null)_jspx_page_context.handlePage
_jspxFactory.releasePageContext (_jspx_page_context) ;
Here the point to consider is that the JES file name is Welcome_jsp.java and class name is Welcome_jsp.class and all implicit object is visible in _jspService (-,-) method. You can see the implicit objects are visible inside _jspService (-,-) method.
A JSP page mainly comprises the following types of code.
• HTML Code
HTML code is used for displaying the HTML output like text field, check box, option menu where user can give requested data to the web application and also for generating other static content of the web page. HTML codes can be embedded easily in the JSP page.
• Scripting Code
• Scripting Tags
Java codes are placed inside the scripting tags. There are three types of scripting tags in JSP: Scriptlet Tag, Declaration Tag, Expression Tag.
Template text is a combination of normal text and HTML code. It is the uninterrupted data of a JSP page. It is guides the end user when entering data in the required fields.
For web application development JSP generally supports two types of architecture.
i. Model 1 and
ii. Model 2 architecture
JSP Model-I Architecture
In model 1 architecture, the web browser directly accesses the JSP pages. If there is need of, generating output from database jsp page interacts with JavaBeans, which is present inside the web container of model 1 architecture.
JSP Model II Architecture
In model 2 architecture, the browser accesses the JSP page indirectly. The Servlet program acts as controller between JSP page and browser window. If JSP page needs to interact with database for response then servlet program creates the instances of JavaBeans, and JavaBeans invokes the database server.
• Supports tags based programming
JSP supports tag-based programming. As it is a tag-based programming extensive knowledge of Java is not required. Non-Java users can learn it easily. This tag increases the readability of code. Gives built-in JSP tags and also allows to develop custom JSP tags and also to use third party supplied JSP tags.
• Implicit objects
JSP gives nine implicit objects. We can use them directly in our program without writing any additional code to access.
• Code separation
It allows separate presentation logic (html code) and business logic (java code). So does not look bulky. Here we do not have to put html code inside pw.printin() .
• Exception handling
Exception handling is optional in JSP. Container takes care of exception handling. And also implicit object exception is given to get the exception type, but it is only visible inside error page.
• Easy loading
After modifications we do not need to recompile and reload it. We just have to save it and then directly we can send request; and the modifications will be visible. JSP also contains many more features like Standard directives, Scripting elements, Tag extension mechanism, Template content.
We know that Servlet is a server side technology, so why has Sun Microsystems given JSP?
Servlet is a Java code based programming. To know servlet, strong Java knowledge is required. However, while working with ASP.net, PHP like technologies we can go for tag-based programming which is easier. So in initial days programmer did not like Servlet. To attract non-java programmers like ASP.net programmers and PHP programmer Sun Microsystems has introduced a server side technology which is tag based all features of servlet.
JSP enables us to mix up static HTML with dynamically generated content of servlet. the Take example of an online-shopping website, its initial page is mostly same for all visitors, except small changes like welcome message “Hi Mr / Ms Xxx” for registered users. When we develop this by servlet then we have to develop this entire page by writing coding in the Servlet program. However, JSP makes separate parts for static content and dynamic content.
Advantage of JSP over Servlet
Allows tag based programming. So extensive java knowledge is not required.
Does not allow tag based programming. So extensive java knowledge is required.
Suitable for both java and non java programmer.
Not suitable for non java programmer.
Use nine implicit objects, which we can use directly in our JSP program
Implicit objects are present but we can’t use them directly. We need write additional code to use
Modification done in JSP program will be recognized by underlying server automatically without reloading of web application.
Here we need to compile and reload manually.
Takes care of exception handling.
Does not take care of exception handling. Programmers have to explicitly handle this .
Allows us to use separate presentation logic (html code) from Java code(business logic).
Does not allow.
Increases readability of code because of tags.
Readability of code is less
Gives built-in JSP tags and also allows to develop custom JSP tags and to use third party supplied tags.
Does not allow tag based programming.
Easy to learn and easy to apply.
Not easy compared to JSP.
Advantages over All Other Technologies
• Versus active server pages (ASP)
ASP is given by Microsoft. It is also a tag-based programming language. ASP code is not portable. However, JSP code is portable because it is written in Java (i.e., we can reuse the code in other operating systems and also in other web server). We can use Java for JSP, so we need not stick with a particular server product or IIS.
• Versus PHP
It is an HTML embedded scripting language and it is also open source software like Java. It is similar to JSP and ASP. It is not suitable for large scale application and banking applications where money transaction occurs because of security reasons. For PHP we have to learn one new language.
• Versus HTML
Regular HTML, that is static HTML, does not contain dynamic information. So it does not react to user input and is also not fit for accessing server side resources. JSP contains both static and non-static content. As static part, it contains HTML.
There are some problems with Servlet programming.
For non-java programmers Servlet is not suitable as they need to have extensive knowledge of Java Servlet. The presentation logic (HTML code) will be mixed up with Java code (pw.println()). Lots of coding is written inside pw.println() to write html code. Modification done in one code may affect another code. Writing HTML code in Servlet programming is a complex process and it makes Servlet looks bulky.
In Servlet programming implicit objects are there but we need to write some additional code to get them access. Modifications done in source code of servlet program will be effected only after recompilation and reloading of the web application in case of most of servers. Programmers should explicitly take care of exception handling. Servlet programming is not thread safe by default. So we need to write additional codes to make the Servlet program thread safe.
JSP technology is the Java Platform Technology (enterprise technology) for delivering dynamic content to web user (the person who is giving request from browser window) in a portable, secure and well-defined way. JSP has been built on top of the Servlet API and utilizes Servlet semantics. It uses HTML and XML templates and Java code to generate JSP page. JSP is secure, fast and independent of server platforms.
Most Servlets contain codes to handle application logic and to handle output formatting. This can make it difficult to separate and reuse portions of the code when a different output format is needed. For these reasons, web application developers turn towards JSP as their preferred servlet environment. It also contains many more features like platform independent, server independent.
Evolution of Web Applications
Over the past few years, web server applications have evolved from static to dynamic application. This evolution became necessary due to some deficiencies in earlier website design. For example, to put more business processes on the web, both in business-to-consumer (B2C) or business-to-business (B2B) markets, conventional website design technologies are not enough.
The main issues every developer faces while developing web applications are as follows:
1. Scalability – A successful web site will have more users and as the number of users increase, the web applications have to scale correspondingly.
2. Integration of data and business logic – The web is just another way to conduct business, and so it should be able to use the same middle-tier and data-access code.
3. Manageability – Websites just keep getting bigger and we need some viable mechanism to manage the ever-increasing content and its interaction with business systems.
4. Personalization – Adding a personal touch to the web page becomes an essential factor to retain customers. Knowing their preferences, allowing them to configure the information they view, remembering their past transactions or frequent search keywords are all important in providing feedback and interaction from what is otherwise a fairly one-sided conversation.
Apart from these general needs of a business-oriented website, the necessity for new technologies to create robust, dynamic and compact server-side web applications has been realized. The main characteristics of today’s dynamic web server applications are as follows:
• Serve HTML and XML, and stream data to the web client
• Separate presentation, logic and data
• Interface to databases, other Java application server middleware to provide transactional support
• Track client sessions
Now let us have a look on the role of Java technology and platform in this regard.
Java’s Role for Server Applications
Sun Microsystems, having consulted many expert partners from other IT related industries, has come out with a number of open APIs for the technologies and services on server side. This collection of APIs is named as Java 2 Enterprise Edition (J2EE). The J2EE specification provides a platform for enterprise applications, with full API support for enterprise code and guarantees of portability between server implementations. Also, it brings a clear division between code which deals with presentation, business logic and data.
The J2EE specification meets the needs of web applications because it provides the following:
• Rich interaction with a web server via servlets and built-in support for sessions available in both Servlets and EJBs.
• The use of EJBs to mirror the user interaction with data by providing automatic session and transaction support to EJBs operating in the EJBs server.
• Entity EJBs to represent data as an object and seamless integration with the Java data access APIs.
• Flexible template-based output using JSP and XML.
This family of APIs means that the final web page can be generated from a user input request, which was processed by a Servlet or JSP and a session EJB, which represents the user’s session with the server, using data extracted from a database and put into an entity EJE. Thus, the Java revolution of portable code and open APIs is married with an evolution in existing products such as database, application, mail and web servers. The wide availability of products to run Java applications on the server has made Java lucrative in a very competitive market. This makes server-side Java a very exciting area.
The Java Server Pages 1.2 specification provides web developers with a framework to build applications containing dynamic web content such as HTML, DHTML and XML. A JSP page is a text based document containing static HTML and dynamic actions which describe how to process a response to the client in a more powerful and flexible manner. Most of a JSP file is plain HTML but it also has, interspersed with it, special JSP tags.
There are many JSP tags such as:
• <%@page language=”java” %> – this is a JSP directive denoted by <%@,
• scrip lets indicated by <%..%> tags and
• <%@include file=”sample.html”%>- this directive includes the contents of the file sample.html in the response at that point.
To process JSP file, we need a JSP engine that can be connected with a web server or can be accommodated inside a web server. Firstly when a web browser seeks a JSP file through an URL from the web server, the web server recognizes the .jsp file extension in the URL requested by the browser and understands that the requested resource is a JavaServer Page. Then the web server passes the request to the JSP engine. The JSP page is then translated into a Java class, which is then compiled into a Servlet.
This translation and compilation phase occurs only when the JSP file is requested for the first time, or if it undergoes any changes to the extent of getting retranslated and recompiled. For each additional request of JSP page thereafter, the request directly goes to the Servlet byte code, which is already in memory. Thus when a request comes for a Servlet, an init() method is called when the Servlet is first loaded into the virtual machine, to perform any global initialization that every request of the Servlet will need. Then the individual machine requests are sent to a service() method, where the response is put together. The Servlet creates a new thread to run service() method for each request. The request from the browser is converted into a Java object that is used to send the response back to the browser. The Servlet code performs the operations specified by the JSP elements in the .jsp file.
TAG Based Programming
Programming may be code based or tag based. Code-based programming is difficult to write and understand. However, tag-based program is easier and program length is less as compared to codes based programming. Tags reduce the development time and maintenance cost and increases the reusability of code.