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
JSP:forward tag
Standard syntax
<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.
“input.htm”
<body bgcolor=”cyan” >
<center>
<form action=”Square.jsp”>
ENTER NUMBER <input type=”text” name=”t1″ />
<br>
<input type=”submit” value=”Find” />
<input type=”reset” value=”Reset” />
</form>
input.html takes the request from user and then forwards it to Square.jsp page.
“Square.jsp”
<center>
<font color=”red” size=”5″>
SQUARE OF <%=request.getParameter(“t1”) %> IS:
<%
String num=request.getParameter(“t1”) ;
int n=Integer.parseInt(num);
if(n<50)
{
out.println(n*n);
}
else
{
%>
<jsp:forward page=”Cube.jsp”>
<jsp:param name=”num” value=”<%=n %>” />
</jsp:forward>
<%
}
%>
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 %>” />
</jsp:forward>
for forwarding the request to Cube.jsp page. Then Cube.jsp code gets executed.
“Cube.jsp”
<center>
<font color=”red” size=”5″>
CUBE OF <%=request.getParameter(“num”) %> IS:
<%
String num=request.getParameter(“num”);
int n=Integer.parseInt(num);
int z=n*n*n;
out.println(z);
%>
</font>
</center>
JSP Action Include Tag
Standard syntax
<% @ include file= “desturl” %>
XML syntax
<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.
“First.jsp”
<center>
<font color=”red” size=”5″ >
<br><br>
BEGINNING OF FIRST JSP
<BR>
PASSING SOME DATA FROM FIRST.JSP TO SECOND. JSP
<BR></FONT>
<jsp:include page=”Second.jsp” >
<jsp:param name=”name” value=”Neeraj Dadwal” />
<jsp:param name=”roll” value=”1″ />
</jsp:include>
<BR>
<font color=”red”>END OF FIRST JSP</font>
</center>
“Second.jsp”
<%@ taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c” %>
<html>
<head>
<title> jsp include</title>
</head>
<body>
<center>
<font color=”green” size=”5″ >
<br><br>
BEGINNING OF SECOND JSP
<br>
NAME : <%=request.getParameter(“name”) %>
<br>
END OF SECOND JSP
<br>
</font>
</center>
</body>
</html>
Here, the output comes from First.jsp by including the output of Second.jsp inside its body.
Servlet to JSP Communication
The intention is to introduce the communication in between the servlet and JSP. The welcome page is designed by the HTML code.
<html>
<title>Srv-Jsp Communication</title>
<form action=”a.jsp”>
<body>
<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’/>
</center>
</body>
</form>
</html>
Output:
“a.jsp”
<html>
<%
try
{
int no=Integer.parseInt(request.getParameter(“t1”));
int res=no*no;
if(res>=100)
{
out.println(“<center><font color=’red’ size=’8′>”);
out.println(“Square of The Number is=”+res);
out.println(“</font></center>”);
}
else
{
out.println(“<br><br><center><font color=’red’ size=’6′>Your selection Does
not Vary The Condition..”);
}
}
catch(Exception e)
{
System.out.println(e);
}
%>
</html>
Output:
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.
• if(res>=100)
{
out.println(“<center><font color=’red’ size=’8′>”) ;
out.println(“Square Of The Number Is=”+res);
out.println(“</font></center>”) ;
}
If the result requested is greater than 100, then it calculates the square of the number.
• else
{
RequestDispatcher=request.getRequestDispatcher{“/Srv·);
rd.forward(request,response);
}
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)
{
System.out.println(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.
Database To JSP Communication
In the below JSP program the aim is to understand how JSP communicates with the database. The designing is done by HTML.
HTML Program
<html>
<title>DB-JSP</title>
<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’/>
</center>
</body>
</form>
</html>
Output:
JSP Program
<%@ page import=”java.sql.*” %>
<%
try
{
String driver = “com.mysql.jdbc.Driver”;
String url = “jdbc:mysql://localhost/dbase”;
String uid = “root”;
String psw = “root”;
Class.forName(driver) ;
Connection con=DriverManager.getConnection (url,uid,psw) ;
Statement st=con.createStatement ();
String empno=request.getParameter(“t1”);
ResultSet rs = st.executeQuery(“select * from emp where EMPNO=”+empno);
if (rs.next ())
{
out.println(“<center><table border=’15’ color=’red’><tr><th>EMPNAME
</th><th>EMPNO</th><th>SAL</th>
<th>EMPADD</th><th>MAILID</th><th>PHNO.</th>< /tr>”);
out.println(“<tr><td>”+rs.getString(1)+”</td>”);
out.println(“<td>”+rs.getString(2)+”</td>”);
out.println(“<td>”+rs.getString(3)+”</td>”);
out.println(“<td>”+rs.getString(4)+”</td>”) ;
out.println(“<td>”+rs.getString(5)+”</td>”) ;
out.println(“<td>”+rs.getString(6)+”</td></tr>”);
out.println(“</table></center>”);
}
else
{
out.println(“<center><font color=’red’ size=’7′>Invalid Id Try Again</font></center>”);
}
}
catch(Exception ee)
{
System.out.println(ee);
}
%>
Output:
Explanation of the above program
• Class.forName(“oracle.jdbe.driver.Oracle Driver”);
It loads the type-4 driver.
• Connection
con=DriverManager.getConnection(” jdbe:oraele:thin:@localhost:1521:xe”,”system”,”manager”);
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())
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 () ;.
else{
• 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)
{
• System.out.println(ee);
}
The generated exception is handled by the catch block.
Html To JSP Communication
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:
Program:
<html>
<title>HTML TO JSP COMM</title>
<body>
<center>
<font color=”blue” size=”8″><b>Date & Time is :</b></Font></center>
<h3 align=”center”><%java.util.Date d=new java.util.Date();out.println(d.toString());%>
</center>
</body>
</html>
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();
out.println(d.toString()) ;%>
Jsp readingTextFile Example
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.* “%>
<html>
<head>
<title><ReadingTextFile> In JSP</title>
</head>
<body bgcolor=”#E1EDF3″>
<h3 align=”center”><br><%
String fileName = “/WEB-INF/Reading.txt”;
InputStream instrm = application.getResourceAsStream(fileName);
try
{
if(instrm == null)
{
response.setStatus(response.SC_NOT_FOUND);
}
Else
{
BufferedReader bfrdr = new BufferedReader((new InputStreamReader(instrm)));
String cntnt;
while((cntnt= bfrdr.readLine())!= null)
{
out.println(cntnt+”<br>”);
}
}
}
catch(IOException e1)
{
out.println(e1.getMessage());
}
%></h3></br>
</body>
</html>
Jsp serverSnoop Example
This Example is use to get the Information about Server’s Information. Like port number, server name.
<html>
<head>
<title><SnoopServer></title>
</head>
<body bgcolor=”#CAE0EC”>
<table border=”1″ align=”center” cellpadding=”2px” cellspacing=”2px” align=”center”>
<tr>
<span><h2 align=”center”>Server Information</h2></td></span>
</tr>
<tr>
<td>Server Name:</td> <td><%=request.getServerName() %></td>
</tr>
<tr>
<td>ServerPort: </td> <td><%=request.getServerPort() %></td>
</tr>
<tr>
<td>Query String: </td> <td><%= request.getQueryString() %></td>
</tr>
<tr>
<td>Servlet Path: </td> <td><%= request.getServletPath() %></td>
</tr>
<tr>
<td>Server Protocol:</td> <td><%= request.getProtocol() %></td>
</tr>
<tr>
<td>Server Scheme:</td> <td><%=request.getScheme() %></td>
</tr>
<tr>
<td>RemotePort = </td> <td> <%=request.getRemotePort() %></td>
</tr>
<tr>
<td>Remote Host = </td> <td> <%=request.getRemoteHost() %></td>
</tr>
<tr>
<td>Request URI: = </td> <td><%= request.getRequestURI() %></td>
</tr>
<tr>
<td>Request Method: = </td> <td><%= request.getMethod() %></td>
</tr>
<tr>
<td>Content Length: = </td> <td><%= request.getContentLength() %></td>
</tr>
</table>
</body>
</html>
jsp pageCount Example
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.
<html>
<head>
<title><Jsp Page Counter></title>
</head>
<body bgcolor=”#F8E4E4″>
<%!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>
<%
click++;
}
else
{
%>
<br><h3 align=”center”><% out.print(“Welcome…!”);%></br>
<h3 align=”center”><% out.print(“You are Visitor Number : “);%> <%=click %>.</h3>
<%
click++;
}
%>
</body>
</html>
Jsp Expression Example
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.
<html>
<head>
<title><jsp_Expression></title>
</head>
<body>
<form action=”Expression.jsp” method=”get”>>
<table cellpadding=”2px” cellspacing=”1px” bgcolor=”#f7f9fb” width=”400px”align=”center”>
<tr>
<td align=”center” colspan=”2″>
<span class=”text”><h2>Identity</h2></span></td>
</tr>
<tr>
<td align=”center” width=”60%”>User Name: <input type=”text” name=”text”maxlength=”40″/></td>
</tr>
<tr>
<td align=”center”><input type=”submit” value=”Submit” /></td>
</tr>
</form>
</table>
</body>
</html>
Expression.jsp
<html>
<head>
<title><Expression></title>
</head>
<body>
<%String identity= request.getParameter(“text”);%>
<%
if(identity!=null)
{
%>
<b><br><br><h2 align=”center”>
<%=identity %></h2></b></br>
<%
}
%>
</body>
</html>
What is the difference between PrintWriter and JspWriter?
PrintWriter | JspWriter |
Does not support buffering | supports 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 IOException |
Useful for servlet programming | It is the type of implicit object out in JSP |
Why is it optional to configure web.xml file in case of JSP as it is mandatory for servlet program?
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.
Exploring Implicit Objects
A JSP program can have two types of objects.
• Explicit objects
• Implicit objects [Read more…] about Exploring Implicit Objects
Commenting Code in JSP
JSP comment
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:
<%–……..–>
HTML Comments
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
Comments | In JSP program | Compiled of java equivalent Servlet | Html code that comes to browser | Output | |
JSP comments | Yes | – | – | – | – |
Html | Yes | Yes | Yes | Yes | – |
Java comments | Yes | Yes | – | – | – |
JSP Scripting Elements
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 JSP
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.
Like:
for init(-) _jspInit()
service(-,-)….._jspService(-,-)
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
server)
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
then
Right click on my computer
Click properties
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
<html>
<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 ());
%>
</center>
</html>
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
web.xml
<web-app/>
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:
https://ecomputernotes.com:8080/JspApp/Welcome.jsp
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…
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class Welcome_jspextends org.apache.jasper.runtime.HttpJsp
Base implements org.apache.jasper.runtime.JspSourceDependent
{
private static final JspFactory_jspxFactory =
JspFactory.getDefaultFactory();
private static java.util.List_jspx_dependants;
private javax.el.ExpressionFactory_el_expressionfactory;
private org.apache.AnnotationProcessor_jsp_annotationprocessor;
public object getDependants ()
{
return_jspx_dependants;
}
public void_jsplnit ()
{
_el_expressionfactory = _jspxFactory.getJspApplicationContext
(getServletConfig ().getServletContext ()).getExpressionFactory ();
_jsp_annotationprocessor = (org.apache.Annotationprocessor)
getServletConfig ().getServletContext ().getAttribute
(org.apache.Annotationprocessor.class.getName ());
}
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;
try
{
response.setContentType (“text/html”);
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 (“<html>\r\n”);
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 ());
out.write (“\r\n”);
out.write(“</center>\r\n”) ;
out.write(“</html>\r\n”) ;
}
catch (Throwable t)
{
if (! (t instanceof SkipPageException))
{
out = _jspx_out;
if (out != null && out.getBufferSize () !=0)
try
{
out.clearBuffer ();
}
catch (java.io.IOException e)
{
}
if (_jspx-page_context != null)_jspx_page_context.handlePage
Exception (t);
}
}
finally
{
_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.
JSP Program Structure
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 code means the codes which have nested in some other code without any extension. Like JavaScript code it is used in JSP page to get some more dynamism like email id validation, password field length validation, etc.
• 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
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.
Architecture of JSP
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.
Features of JSP Programming.
• 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.
What are Advantages of JSP?
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
JSP | 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 them. |
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 JavaScript
JavaScript is in no way related with Java programming. It is normally used to generate HTML dynamically on the client machine. JavaScript is not suitable for network programming and to access server-side resources. Java is more powerful, flexible, reliable and portable than PHP.
• 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.
What are disadvantages of servlet?
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.
What is JSP?
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.
Although JSP technology is going to be a powerful successor to basic Servlets, there is a relation between JSP and Servlet. Servlets are powerful and sometimes they are a bit cumbersome when it comes to generating complex HTML. But JSP is handy with HTML and JavaScript. JSP is also powerful compared to other web technologies like PHP, ASP as it is developed as per Java specifications.
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.
We have some ideas on tag-based programming like HTML, JavaScript and CSS, etc. JSP is also totally tag based. JSP tags implement the functionality of tags into tag implementation classes. So to develop JSP page, large amount of Java code is not needed. So this helps the programmer to develop java codeless JSP program by which developing separate presentation logic and business logic has become easier.