Monday 21 March 2011

JSP


First JSP



Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server side scripting support for creating database driven web applications. JSP enable the developers to directly insert java code into jsp file, this makes the development process very simple and its maintenance also becomes very easy.  JSP pages are efficient, it loads into the web servers memory  on receiving the request very first time and the subsequent calls are served within a very short period of time. 
    In today's environment most web sites servers dynamic pages based on user request. Database is very convenient way to store the data of users and other things. JDBC provide excellent database connectivity in heterogeneous database environment. Using JSP and JDBC its very easy to develop database driven web application. 
   Java is known for its characteristic of "write once, run anywhere." JSP pages are platform independent. Your port your .jsp pages to any platform.     
Installing JSP
First of all download JavaServer Web Development Kit (JSWDK1.0.1) fromhttp://java.sun.com/products/servlet/download.html. JSWDK comes with full documentation and it's very easy to install, so the installation process is not mentioned here. The JSWDK is the official reference implementation of the servlet 2.1 and JSP 1.0 specifications. It is used as a small stand-alone server for testing servlets and JSP pages before they are deployed to a full Web server that supports these technologies. It is free and reliable, but takes quite a bit of effort to install and configure.
Other Servers that support JSP
  • Apache Tomcat.
    Tomcat is the official reference implementation of the servlet 2.2 and JSP 1.1 specifications. It can be used as a small stand-alone server for testing servlets and JSP pages, or can be integrated into the Apache Web server. 
  • Allaire JRun.
    JRun is a servlet and JSP engine that can be plugged into Netscape Enterprise or FastTrack servers, IIS, Microsoft Personal Web Server, older versions of Apache, O’Reilly’s WebSite, or StarNine WebSTAR.
  • New Atlanta’s ServletExec.
    ServletExec is a fast servlet and JSP engine that can be plugged into most popular Web servers for Solaris, Windows, MacOS, HP-UX and Linux. You can download and use it for free, but many of the advanced features and administration utilities are disabled until you purchase a license.
  • Gefion's LiteWebServer (LWS). LWS is a small free Web server that supports servlets version 2.2 and JSP 1.1.
  • GNU JSP. free, open source engine that can be installed on apache web server.
  • PolyJSP. PolyJsp is based on XML/XSL and has been designed to be extensible. Now supports WebL  
  • JRUN. Available for IIS server.
  • WebSphere. IBM's WebSphere very large application server now implements JSP.

Java Server Pages are save with .jsp extension. Following code which generates a simple html page.   
 Execute the example. <html>
<head>
<title>
First JSP page.</title>
</head>
<body>
<p align=
"center"><font color="#FF0000" size="6"><%="Java Developers Paradise"%></font></p>
<p align=
"center"><font color="#800000" size="6"><%="Hello JSP"%> </font></p>
</body>
</html>
   
     In jsp java codes are written between '<%and '%>tags. So it takes the following form :<%= Some Expression %> In this example we have use 
          <%="Java Developers Paradise"%>
JavaServer Pages

JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web clients in a portable, secure and well-defined way. The JavaServer Pages specification extends the Java Servlet API to provide web application developers with a robust framework for creating dynamic web content on the server using HTML, and XML templates, and Java code, which is secure, fast, and independent of server platforms. JSP has been built on top of the Servlet API and utilizes Servlet semantics. JSP has become the preferred request handler and response mechanism. Although JSP technology is going to be a powerful successor to basic Servlets, they have an evolutionary relationship and can be used in a cooperative and complementary manner.
Servlets are powerful and sometimes they are a bit cumbersome when it comes to generating complex HTML. Most servlets contain a little code that handles application logic and a lot more code that handles 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.
Evolution of Web Applications
Over the last few years, web server applications have evolved from static to dynamic applications. This evolution became necessary due to some deficiencies in earlier web site design. For example, to put more of business processes on the web, whether in business-to-consumer (B2C) or business-to-business (B2B) markets, conventional web site design technologies are not enough. The main issues, every developer faces when developing web applications, are:
1. Scalability - a successful site will have more users and as the number of users is increasing fastly, 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 - web sites 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 keep our customer coming back again. 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 for a business-oriented web site, 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:
1. Serve HTML and XML, and stream data to the web client
2. Separate presentation, logic and data
3. Interface to databases, other Java applications, CORBA, directory and mail services
4. Make use of application server middleware to provide transactional support.
5. 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 related IT 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:
1. Rich interaction with a web server via servlets and built-in support for sessions available in both servlets and EJBs.
2. The use of EJBs to mirror the user interaction with data by providing automatic session and transaction support to EJBs operating in the EJB server.
3. Entity EJBs to represent data as an object and seamless integration with the Java data access APIs
4. Flexible template-based output using JSP and XML
This family of APIs mean 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 EJB. 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 this a fast-moving and very competitive market, but the essential compatibility through specifications, standard APIs and class libraries has held. This makes server-side Java a very exciting area.
JavaServer Pages - An Overview
The JavaServer Pages 1.2 specification provides web developers with a framework to build applications containing dynamic web content such as HTML, DHTML, XHTML 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:
  • JSP directive denoted by <%@,
    2. scriplets indicated by <% ... %> tags and
  • directive includes the contents of the file sample.html in the response at that point.
To process a 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 the 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 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 of type HttpServletRequest, which is passed to the Servlet along with an HttpServletResponse 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.
The Components of JSPs
JSP syntax is almost similar to XML syntax. The following general rules are applicable to all JSP tags.
1. Tags have either a start tag with optional attributes, an optional body, and a matching end tag or they have an empty tag possibly with attributes.
2. Attribute values in the tag always appear quoted. The special strings &apos; and " can be used if quotes are a part of the attribute value itself.
Any whitespace within the body text of a document is not significant, but is preserved, which means that any whitespace in the JSP being translated is read and preserved during translation into a servlet.
The character \ can be used as an escape character in a tag, for instance, to use the % character, \% can be used.
JavaServer Pages are text files that combine standard HTML and new scripting tags. JSPs look like HTML, but they get compiled into Java servlets the first time they are invoked. The resulting servlet is a combination of HTML from the JSP file and embedded dynamic content specified by the new tags. Everything in a JSP page can be divided into two categories:
1. Elements that are processed on the server
2. Template data or everything other than elements, that the engine processing the JSP engines.
Element data or that part of the JSP which is processed on the server, can be classified into the following categories:
1. Directives
2. Scripting elements
3. Standard actions
JSP directives serve as messages to the JSP container from the JSP. They are used to set global values such as class declaration, methods to be implemented, output content type, etc. They do not produce any output to the client. All directives have scope of the entire JSP file. That is, a directive affects the whole JSP file, and only that JSP file. Directives are characterized by the @ character within the tag and the general syntax is:
The three directives are page, include and taglib.
Scripting elements are used to include scripting code (Java code) within the JSP. They allow to declare variables and methods, include arbitrary scripting code and evaluate an expression. The three types of scripting element are: Declaration, Scriptlets and Expressions.
A declaration is a block of Java code in a JSP that is used to define class-wide variables and methods in the generated class file. Declarations are initialized when the JSP page is initialized and have class scope. Anything defined in a declaration is available throughout the JSP, to other declarations, expressions or code.
A scriptlet consists of one or more valid Java statements. A scriptlet is a block of Java code that is executed at request-processing time. A scriptlet is enclosed between "<%" and "%>". What the scriptlet actually does depends on the code, and it can produce output into the output stream to the client. Multiple scriptlets are combined in the compiled class in the order in which they appear in the JSP. Scriptlets like any other Java code block or method, can modify objects inside them as a result of method invocations.
An expression is a shorthand notation for a scriptlet that outputs a value in the response stream back to the client. When the expression is evaluated, the result is converted to a string and displayed, An expression is enclosed within <%= and %> "<%=" and "%>". If any part of expression is an object, the conversion is done using the toString() method of the object.
Standard actions are specific tags that affect the runtime behavior of the JSP and affect the response sent back to the client. The JSP specification lists some standard action types to be provided by all containers, irrespective of the implementation. Standard actions provide page authors with some basic functionality to exploit; the vendor is free to provide other actions to enhance behavior.
How JSP and JSP Container function
A JSP page is executed in a JSP container or a JSP engine, which is installed in a web server or in a application server. When a client asks for a JSP page the engine wraps up the request and delivers it to the JSP page along with a response object. The JSP page processes the request and modifies the response object to incorporate the communication with the client. The container or the engine, on getting the response, wraps up the responses from the JSP page and delivers it to the client. The underlying layer for a JSP is actually a servlet implementation. The abstractions of the request and response are the same as the ServletRequest and ServletResponse respectively. If the protocol used is HTTP, then the corresponding objects are HttpServletRequest and HttpServletResponse.
The first time the engine intercepts a request for a JSP, it compiles this translation unit (the JSP page and other dependent files) into a class file that implements the servlet protocol. If the dependent files are other JSPs they are compiled into their own classes. The servlet class generated at the end of the translation process must extend a superclass that is either
1. specified by the JSP author through the use of the extends attribute in the page directive or
2. is a JSP container specific implementation class that implements javax.servlet.jsp.JspPage interface and provides some basic page specific behavior.
Since most JSP pages use HTTP, their implementation classes must actually implement the javax.servlet.jsp.HttpJspPage interface, which is a sub interface of javax.servlet.jsp.JspPage.
The javax.servlet.jsp.JspPage interface contains two methods:
1. public void jspInit() - This method is invoked when the JSP is initialized and the page authors are free to provide initialization of the JSP by implementing this method in their JSPs.
2. public void jspDestroy() - This method is invoked when the JSP is about to be destroyed by the container. Similar to above, page authors can provide their own implementation.
The javax.servlet.jsp.HttpJspPage interface contains one method:
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
This method generated by the JSP container is invoked, every time a request comes to the JSP. The request is processed and the JSP generates appropriate response. This response is taken by the container and passed back to the client.
JSP Architecture
There are two basic ways of using the JSP technology. They are the client/server (page-centric) 2-tier approach and the N-tier approach (dispatcher).
The Page-Centric Approach
Applications built using a client-server (2-tier) approach consist of one or more application programs running on client machines and connecting to a server-based application to work. With the arrival of Servlets technology, 2-tier applications could also be developed using Java programming language. This model allows JSPs or Servlets direct access to some resource such as database or legacy application to service a client's request. The JSP page is where the incoming request is intercepted, processed and the response sent back to the client. JSPs differ from Servlets in this scenario by providing clean code, separating code from the content by placing data access in EJBs. Even though this model makes application development easier, it does not scale up well for a large number of simultaneous clients as it entails a significant amount of request processing to be performed and each request must establish or share a potentially scarce/expensive connection to the resource in question.
Page-view - This basic architecture involves direct request invocations to a server page with embedded Java code, and markup tags which dynamically generate output for substitution within the HTML. This approach has been blessed a number of benefits. It is very straightforward and is a low-overhead approach from a developerment perspective. All the Java code may be embedded within the HTML, so changes are confined to a very limited area, reducing complexity drastically.
The big trade-off here is in the level of sophistication. As the scale of the system grows, some limitations begin to surface, such as bloating of business logic code in the page instead of factoring forward to a mediating Servlet or factoring back to a worker bean. It is a fact that utilizing a Servlet and helper beans helps to separate developer roles more cleanly and improves the potential for code reuse.
Page-view with bean - This pattern is used when the above architecture becomes too cluttered with business-related code and data access code. The Java code representing the business logic and simple data storage implementation in the previous model moves from the JSP to the JavaBean worker. This refactoring leaves a much cleaner JSP with limited Java code, which can be comfortably owned by an individual in a web-production role, since it encapsulates mostly markup tags.
The Dispatcher Approach
In this approach, a Servlet or JSP acts as a mediator or controller, delegating requests to JSP pages and JavaBeans. There are three different architectures. They are mediator-view, mediator-composite view and service to workers.
In an N-tier application, the server side of the architecture is broken up into multiple tiers. In this case, the application is composed of multiple tiers, where the middle tier, the JSP, interacts with the back end resources via another object or EJBs component. The Enterprise JavaBeans server and the EJB provide managed access to resources, support transactions and access to underlying security mechanisms, thus addressing the resource sharing and performance issues of the 2-tier approach.
The first step in N-tiered application design should be identifying the correct objects and their interaction and the second step is identifying the JSPs or Servlets. These are divided into two categories.
Front end JSPs or Servlets manage application flow and business logic evaluation. They act as a point to intercept the HTTP requests coming from the users. They provide a single entry point to an application, simplifying security management and making application state easier to maintain.
Presentation JSPs or Servlets generate HTML or XML with their main purpose in life being presentation of dynamic content. They contain only presentation and rendering logic.
These categories resemble to the Modal-View design pattern, where the front-end components is the model and the presentation component the view. In this approach, JSPs are used to generate the presentation layer and either JSPs or Servlets to perform process-intensive tasks. The front-end component acts as the controller and is in charge of the request processing and the creation of any beans or objects used by the presentation JSP, as well as deciding, depending on the user's actions, which JSP to forward this request to. There is no processing logic within the presentation JSP itself and it simply responsible for retrieving any objects or beans that may have been previously created by the Servlet and extracting the dynamic content for insertion within static templates.
Benefits of JSP
One of the main reasons why the JavaServer Pages technology has evolved into what it is today and it is still evolving is the overwhelming technical need to simplify application design by separating dynamic content from static template display data. Another benefit of utilizing JSP is that it allows to more cleanly separate the roles of web application/HTML designer from a software developer. The JSP technology is blessed with a number of exciting benefits, which are chronicled as follows:
1. The JSP technology is platform independent, in its dynamic web pages, its web servers, and its underlying server components. That is, JSP pages perform perfectly without any hassle on any platform, run on any web server, and web-enabled application server. The JSP pages can be accessed from any web server.
2. The JSP technology emphasizes the use of reusable components. These components can be combined or manipulated towards developing more purposeful components and page design. This definitely reduces development time apart from the At development time, JSPs are very different from Servlets, however, they are precompiled into Servlets at run time and executed by a JSP engine which is installed on a Web-enabled application server such as BEA WebLogic and IBM WebSphere.
Conclusion
JSP and Servlets are gaining rapid acceptance as means to provide dynamic content on the Internet. With full access to the Java platform, running from the server in a secure manner, the application possibilities are almost limitless. When JSPs are used with Enterprise JavaBeans technology, e-commerce and database resources can be further enhanced to meet an enterprise's needs for web applications providing secure transactions in an open platform. J2EE technology as a whole makes it easy to develop, deploy and use web server applications instead of mingling with other technologies such as CGI and ASP. There are many tools for facilitating quick web software development and to easily convert existing server-side technologies to JSP and Servlets.
Many application server vendors are aggressively deploying JSP within their products. This results in developing robust e-commerce applications as JSP provides XML functionality and scalability. By providing a clear separation between content and coding, JSP solves many problems attached with existing server-side applications.

JSP ARCHITECTURE


JSP pages are high level extension of servlet and it enable the developers to embed java code in html pages. JSP files are finally compiled into a servlet by the JSP engine. Compiled servlet is used by the engine to serve the requests.
javax.servlet.jsp package defines two interfaces:
  • JSPPage
  • HttpJspPage
These interfaces defines the three methods for the compiled JSP page. These methods are:
  • jspInit()
  • jspDestroy()
  • _jspService(HttpServletRequest request,HttpServletResponse response)
      
In the compiled JSP file these methods are present. Programmer can define jspInit() andjspDestroy() methods, but the _jspService(HttpServletRequest request,HttpServletResponse responsemethod is generated by the JSP engine.

JSP Actions



In this section we will explain you about JSP Action tags and in the next section we will explain the uses of these tags with examples. We will also show how to use JSP Action Tags in the JSP application.
What is JSP Actions?
Servlet container provides many built in functionality to ease the development of the applications. Programmers can use these functions in JSP applications. The JSP Actions tags enables the programmer to use these functions. The JSP Actions are XML tags that can be used in the JSP page.
Here is the list of JSP Actions:
  • jsp:include 
    The jsp:include action work as a subroutine, the Java servlet temporarily passes the request and response to the specified JSP/Servlet. Control is then returned back to the current JSP page.
      
  • jsp:param
    The jsp:param action is used to add the specific parameter to current request. The jsp:param tag can be used inside a jsp:include, jsp:forward or jsp:params block.
     
  • jsp:forward
    The jsp:forward tag is used to hand off the request and response to another JSP or servlet. In this case the request never return to the calling JSP page.
      
  • jsp:plugin
    In older versions of Netscape Navigator and Internet Explorer; different tags is used to embed applet. The jsp:plugin tag actually generates the appropriate HTML code the embed the Applets correctly.
      
  • jsp:fallback
    The jsp:fallback tag is used to specify the message to be shown on the browser if applets is not supported by browser.
    Example:
     <jsp:fallback>
          <p>Unable to load applet</p>
       </jsp:fallback>
          
  • jsp:getProperty 
    The jsp:getPropertyB is used to get specified property from the JavaBean object.
      
  • jsp:setProperty
    The jsp:setProperty tag is used to set a property in the JavaBean object.
      
  • jsp:useBean
    The jsp:useBean  tag is used to instantiate an object of Java Bean or it can re-use existing java bean object.

INTRODUCTION TO JSP TAGS


In this lesson we will learn about the various tags available in JSP with suitable examples. In JSP tags can be devided into 4 different types. These are:
    
  1. Directives
    In the directives we can import packages, define error handling pages or the session information of the JSP page.
        
  2. Declarations
    This tag is used for defining the functions and variables to be used in the JSP.
       
  3. Scriplets
    In this tag we can insert any amount of valid java code and these codes are placed in _jspService method by the JSP engine.
       
  4. Expressions
    We can use this tag to output any data on the generated page. These data are automatically converted to string and printed on the output stream.
       
Now we will examine each tags in details with examples. DIRECTIVES
Syntax of JSP directives is:
<%@directive attribute="value" %>
Where directive may be:
  1. page: page is used to provide the information about it.
    Example: <%@page language="java" %>
       
  2. include: include is used to include a file in the JSP page.
    Example: <%@ include file="/header.jsp" %>
      
  3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own tags).
    Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>
       
and attribute may be:
  1. language="java"
    This tells the server that the page is using the java language. Current JSP specification supports only java language.
    Example: <%@page language="java" %>
       
  2. extends="mypackage.myclass"
    This attribute is used when we want to extend any class. We can use comma(,) to import more than one packages.
    Example: <%@page language="java" import="java.sql.*,mypackage.myclass" %>
       
  3. session="true"
    When this value is true session data is available to the JSP page otherwise not. By default this value is true.
    Example: <%@page language="java" session="true" %>
      
  4. errorPage="error.jsp"
    errorPage is used to handle the un-handled exceptions in the page.
    Example: <%@page language="java" session="true" errorPage="error.jsp"  %>
       
  5. contentType="text/html;charset=ISO-8859-1"
    Use this attribute to set the mime type and character set of the JSP.
    Example: <%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1"  %> 

JSP DECLARATIVES


Syntax of JSP Declaratives are:
  <%!
  //java codes
   %>
JSP Declaratives begins with <%! and ends %> with .We can embed any amount of java code in the JSP Declaratives. Variables and functions defined in the declaratives are class level and can be used anywhere in the JSP page

<%@page contentType="text/html" %>
<html>
<body>
<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>
<p>Values of Cnt are:</p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
</body>
</html>

JSP SCRIPTLETS


Syntax of JSP Scriptles are:
  <%
  //java codes
   %>
JSP Scriptlets begins with <% and ends%> .We can embed any amount of java code in the JSP Scriptlets. JSP Engine places these code in the _jspService()method. Variables available to the JSP Scriptlets are
  • request:
    request represents the clients request and is a subclass of HttpServletRequest. Use this variable to retrieve the data submitted along the request.
    Example:
      <%
      //java codes
       String userName=null;
       userName=request.getParameter("userName");
       %>
  • response:
    response is subclass of HttpServletResponse.
     
  • session:
    session represents the HTTP session object associated with the request.
     
  • out:
    out is an object of output stream and is used to send any output to the client.
Other variable available to the scriptlets are pageContext, application,config and exception.
INTRODUCTION TO JSP EXPRESSIONS
Syntax of JSP Expressions are:
  <%="Any thing"   %>
JSP Expressions start with 
Syntax of JSP Scriptles are with <%= and ends with  %>Between these this you can put anything and that will converted to the String and that will be displayed.
Example:  <%="Hello World!" %>Above code will display 'Hello World!'.

JSP date example


Till now you learned about the JSP syntax, now I will show you how to create a simple dynamic JSP page that prints the current date and time. So the following code accomplish this

<%@page contentType="text/html" import="java.util.*" %>
<!--
-->
<html>
<body>
<p>
&nbsp;</p>
<div align=
"center">
<center>
<table border=
"0" cellpadding="0" cellspacing
=
"0" width="460" bgcolor="#EEFFCA">
<tr>
<td width=
"100%"><font size="6" color
=
"#008000">&nbsp;Date Example</font></td>
</tr>
<tr>
<td width=
"100%"><b>&nbsp;Current Date
and time is:&nbsp; 
<font color="#FF0000">

<%= new java.util.Date() %>
</font></b></td>
</tr>
</table>
</center>
</div>

</body>
</html>

The heart of this example is Date() function of the java.util package which returns the current data and time. 
In the JSP Declaratives 
<%@page contentType="text/html" import="java.util.*" %>
we are importing the java.util package and following JSP Expression code 
<%= new java.util.Date() %>
prints the current date on the page.

Reading Request Information

When an HTTP client such as web browser sends a request to a wen server, along with the request it also sends some HTTP variables like Remote address, Remote host, Content type etc. In some cases these variables are useful to the programmers. So here is the code of the jsp file which prints the HTTP request information:
<%@page contentType="text/html" import="java.util.*" %>
<!--
-->
<html>
<body>
<p><font size="5" color="#800000">Request Information:</font></p>
<div align="left">
<table border="0" cellpadding="0" cellspacing="0" width="70%" bgcolor="#EEFFCA">
<tr>
<td width="33%"><b><font color="#800000">Request Method:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getMethod()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Request URI:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRequestURI()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Request Protocol:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getProtocol()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Path Info:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getPathInfo()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Path translated:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getPathTranslated()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Query String:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getQueryString()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Content length:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getContentLength()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Content type:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getContentType()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Server name:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getServerName()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Server port:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getServerPort()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Remote user:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRemoteUser()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Remote address:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRemoteAddr()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Remote host:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRemoteHost()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Authorization scheme:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getAuthType()%></font></td>
</tr>
</table>
</div>
</body>
</html>
Retrieving data posted to jsp from html
Now I will show you how to retrieve the data posted from a HTML file in a JSP page. Consider an html page that prompts the user to enter his/her name, let's call it getname.htm. Here is the code of the html file:
<html>
<head>
<title>
Enter your name</title>
</head>
<body>

<p>&nbsp;</p>

<form method=
"POST"action="showname.jsp">

<p><font color=
"#800000" size="5">Enter your name:</font><input type
=
"text" name="username" size="20"></p>

<p><input type=
"submit" value="Submit"name="B1"></p>
</form>
</body>
</html>
The target of form is "showname.jsp", which displays the name entered by the user. To retrieve the value entered by the user we uses the
request.getParameter("username");
code.

Here is the code of "showname.jsp" file:
<%@page contentType="text/html" %>
<!--
-->
<html>
<body>
<p><font size="6">Welcome :&nbsp; <%=request.getParam
eter("username")%></font></p>
</body>
</html>

Accessing database from JSP



In This article I am going to discuss the connectivity from MYSQL database with JSP.we take a example of Books database. This database contains a table named books_details. This table contains three fields- idbook_nameauthor. we starts from very beginning. First we learn how to create tables in MySQl database after that we write a html page for inserting the values in 'books_details' table in database. After submitting values a table will be showed that contains the book name and author name.
Database
The database in example consists of a single table of three columns or fields. The database name is "books" and it contains information about books names & authors.



Table:books_details
          ID  Book Name                  Author
           1. Java I/O Tim Ritchey
           2.
 Java & XML,2 Edition   
 Brett McLaughlin
           3. Java Swing, 2nd Edition
 Dave Wood, Marc Loy,
Start MYSQL prompt and type this SQL statement & press Enter-
                                MYSQL>CREATE DATABASE `books` ;
This will create "books" database.
Now we create table a table "books
_details" in database "books".
                             
                      
           MYSQL>CREATE TABLE `books_details` (
                                                `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,
                                                `book_name` VARCHAR( 100 ) NOT NULL ,
                                               `author` VARCHAR( 100 ) NOT NULL ,
                                                PRIMARY KEY ( `id` )
                                                ) TYPE = MYISAM ;

This will create a table "books_details" in database "books"
JSP Code
The following code contains  html for user interface & the JSP backend-
<%@ page language="java" import="java.sql.*" %>
<%
 String driver = "org.gjt.mm.mysql.Driver";
 Class.forName(driver).newInstance();
 
 Connection con=null;
 ResultSet rst=null;
 Statement stmt=null;
 
 try{
  String url="jdbc:mysql://localhost/books?user=
<user>&password=<password>";
  con=DriverManager.getConnection(url);
  stmt=con.createStatement();
 }
 catch(Exception e){
  System.out.println(e.getMessage());
 }
 if(request.getParameter("action") != null){ 
  String bookname=request.getParameter("bookname");
  String author=request.getParameter("author");
  stmt.executeUpdate("insert into books_details(book_name,
author) values('"+bookname+"','"+author+"')");
  rst=stmt.executeQuery("select * from books_details");
  %>
  <html>
  <body>
  <center>
   <h2>Books List</h2>
   <table border="1" cellspacing="0" cellpadding
="0">
   <tr>
    <td><b>S.No</b></td>
    <td><b>Book Name</b></td>
    <td><b>Author</.b></td>
   </tr>
     <%
    int no=1;
    while(rst.next()){
    %>
    <tr>
      <td><%=no%></td>
      <td><%=rst.getString("
book_name")%></td>
      <td> <%=rst.getString("author")
%> </td>
    </tr>
    <%
    no++;
 }
 rst.close();
 stmt.close();
 con.close();
%>
   </table>
   </center>
  </body>
 </html>
<%}else{%>
 <html>
 <head>
  <title>Book Entry FormDocument</title>
  <script language="javascript">
      function validate(objForm){
   if(objForm.bookname.value.length==0){
   alert("Please enter Book Name!");
   objForm.bookname.focus();
   return false;
   }
   if(objForm.author.value.length==0){
   alert("Please enter Author name!");
   objForm.author.focus();
   return false;
   }
   return true;
    }
   </script>
  </head>
  
  <body>
   <center>
<form action="BookEntryForm.jsp" method="post" 
name="entry" onSubmit="return
 validate(this)">
 <input type="hidden" value="list" name="action">
 <table border="1" cellpadding="0" cellspacing="0">
 <tr>
  <td>
   <table>
    <tr>
    <td colspan="2" align="center">
<h2>Book Entry Form</h2></td>
    </tr>
    <tr>
    <td colspan="2">&nbsp;</td>
    </tr>
    <tr>
    <td>Book Name:</td>
    <td><input name="bookname" type=
"text" size="50"></td>
    </tr>
    <tr>
    <td>Author:</td><td><input name=
"author" type="text" size="50"></td>
    </tr>
    <tr>
     <td colspan="2" align="center">
<input type="submit" value="Submit"></td>
     </tr>
    </table>
   </td>
  </tr>
 </table>
</form>
   </center>
  </body>
 </html>
<%}%>

Now we explain the above  codes.
Declaring Variables: Java is a strongly typed language which means, that variables must be explicitly declared before use and must be declared with the correct data types. In the above example code we declare some variables for making connection. Theses variables are- 
Connection con=null; ResultSet rst=null; Statement stmt=null; The objects of type ConnectionResultSet and Statement are associated with the Java sql. "con" is a Connection type object variable that will hold Connection type object. "rst" is a ResultSet type object variable that will hold a result set returned by a database query. "stmt" is a object variable of Statement .Statement Class methods allow to execute any query.  
Connection to database: The first task of this programmer is to load database driver. This is achieved using the single line of code :-
String driver = "org.gjt.mm.mysql.Driver"; Class.forName(driver).newInstance();
The next task is to make a connection. This is done using the single line of code :-
String url="jdbc:mysql://localhost/books?user=<userName>&password=<password>"; con=DriverManager.getConnection(url);
When url is passed into getConnection() method of DriverManager class it  returns connection object.   
Executing Query or Accessing data from database:
This is done using following code :- stmt=con.createStatement(); //create a Statement object  rst=stmt.executeQuery("select * from books_details");
stmt is the Statement type variable name and rst is the RecordSet type variable. A query is always executed on a Statement object. A Statement object is created by calling createStatement() method on connection object con. 
The two most important methods of this Statement interface are executeQuery() and executeUpdate(). The executeQuery() method executes an SQL statement that returns a single ResultSet object. The executeUpdate() method executes an insert, update, and delete SQL statement. The method returns the number of records affected by the SQL statement execution.
After creating a Statement ,a method executeQuery() or  executeUpdate() is called on Statement object stmtand a SQL query string is passed in method executeQuery() or  executeUpdate(). This will return a ResultSet rst related to the query string.
Reading values from a ResultSet:
while(rst.next()){    %>          <tr><td><%=no%></td><td><%=rst.getString("book_name")%></td><td><%=rst.getString("author")%></td></tr>   <%  }
The ResultSet  represents a table-like database result set. A ResultSet object maintains a cursor pointing to its current row of data. Initially, the cursor is positioned before the first row. Therefore, to access the first row in the ResultSet, you use the next() method. This method moves the cursor to the next record and returns true if the next row is valid, and false if there are no more records in the ResultSet object.
Other important methods are getXXX() methods, where XXX is the data type returned by the method at the specified index, including Stringlong, and int. The indexing used is 1-based. For example, to obtain the second column of type String, you use the following code:
resultSet.getString(2);
You can also use the getXXX() methods that accept a column name instead of a column index. For instance, the following code retrieves the value of the column LastName of type String.
resultSet.getString("book_name");
The above example shows how you can use the next() method as well as the getString() method. Here you retrieve the 'book_name' and 'author' columns from a table called 'books_details'. You then iterate through the returned ResultSet and print all the book name and author name in the format " book name | author " to the web page.
Summary:
This article presents JDBC and shows how you can manipulate data in a relational database from your  JSP page. To do this, you need to use  the java.sql package: DriverManagerConnectionStatement, andResultSet. Keep in mind, however, that this is only an introduction. To create a Web application, you need  JDBC to use more features such as prepared statements and connection pooling.
To Download Example click here When you click on the above link a Book Entry Form will open
Fill the book name and author fields and press Submit button. A page will open and show  a table of book name and authors like...




Implement JavaScript with JSP



In this section we are going to implement  insert data, delete data, and update data using with JDBC database and also using of JavaScript.
Step 1: Create employee form (EmployeeInformation.jsp) .
In this step first of all create Employee information form and retrieved employee id from database using with JDBC database.  
Here is the  code EmployeeInformation.jsp

<%@ page language="java" import="java.lang.*" import="java.sql.*" %>

<html>
<body border="1" bgcolor="pink" width="650">
<%
Connection con = null;
String url = "jdbc:mysql://192.168.10.211:3306/";
String db = "amar";
String driver = "com.mysql.jdbc.Driver";
String userName ="amar";
String password="amar123";
Class.forName(driver);
con = DriverManager.getConnection(url+db,userName,password);
Statement stmt=null;
%>

<form method="GET" ACTION="ProcessAction.jsp">
<h3> <P ALIGN="CENTER"> <FONT SIZE=5> EMPLOYEE INFORMATION </FONT> </P> </h3> </br> </br>
<br>
<br>
<table callspacing=5 cellpadding=5 bgcolor="lightblue" colspan=2 rowspan=2 align="center">
<tr>
<td> <font size=5> Enter Employee ID </td>
<td> <input type="TEXT"  ID="id" name="empid"> </font>
<select name="empIds" onchange="document.getElementById('id').value=this.options[this.selectedIndex].text"> <option>Select One</option>
<%
String rec="SELECT empid,empname FROM Employee ORDER BY empid";
try {
stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(rec);
while(rs.next())
{
%>
<option><%= rs.getInt(1)%></option>
<%}
}
catch(Exception e){
System.out.println(e);
}
%>
</select>
</font> </td>
</tr>
<tr>
<td> <font size=5> Enter Employee Name </td>
<td><input type="text" name="empname"> </font> </td>
</tr>
<tr> <font size=5> <B>
<td><input type="RADIO" name="r1" VALUE="add" >Insert </td>
</tr>
<tr>
<td><input type="RADIO" name="r1" VALUE="del" >Delete </td>
</tr>
<tr>
<td><input type="RADIO" name="r1" VALUE="mod" >Modify </td>
</tr>
</font> </b>
<tr> <td><input type="SUBMIT" VALUE="Submit">
<input type="RESET" value="Reset"> </TD>
</tr>
</body>
</html>

Step 2 : Create "ProcessAction.jsp"  for Process the Data and forward  according to user requirement.
In this step first of all we will create ProcessAction.jsp for getting all string value using withgetParameter() method and forward on different page like JSPInsertAction.jsp, ClearAction.jsp, and update.jsp. 

<%@ page language="java" %>
<%@ page import="java.lang.*" %>
<%@ page import="java.sql.*" %>
<%
String str=request.getParameter("r1");
String name=request.getParameter("empname");
String code=request.getParameter("empid");

if(str.equals("add")) {
%>
<jsp:forward page="JSPInsertAction.jsp"/>

<%
}
else if(str.equals("del")) {
%>
<jsp:forward page="ClearAction.jsp" />
<%
}
else if(str.equals("mod")) {
%>
<jsp:forward page="update.jsp" />
<%
}
else {
%>
<jsp:forward page="Noresponse.html" />
<%
}
%>

Step 3: Create data insert action page ("JSPInsertAction.jsp").
This code using for insert data into database by using JDBC database. When you will select same employee id and employee name then massage will display employee id already exit in database.

<%@ page language="java" import="java.lang.*" import="java.sql.*" %>

<HTML>
<BODY>
<FORM NAME="f1" ACTION="EmplyeeInformation.jsp">
<%
Connection con = null;
String url = "jdbc:mysql://192.168.10.211:3306/";
String db = "amar";
String driver = "com.mysql.jdbc.Driver";
String userName ="amar";
String password="amar123";

String str=request.getParameter("r1");
String empname=request.getParameter("empname");
String code=request.getParameter("empid");
int ent=0;
String failed="";
try{
String click="SELECT COUNT(*) FROM Employee WHERE empid='"+code+"' and empname='"+empname+"'";
Class.forName(driver);
con = DriverManager.getConnection(url+db,userName,password);
Statement stmt=null;
stmt=con.createStatement();
ResultSet ok = stmt.executeQuery(click);
while(ok.next()) {
ent=ok.getInt(1);
}
if(ent==0) {
String insertQry = "insert Employee values('"+code+"','"+empname+"')";
int val = stmt.executeUpdate(insertQry);

%>
<script language="javascript">
alert("Insertion successful");
document.location="EmplyeeInformation.jsp";
</script>
<%
}
if(ent==1) {
%>
<script language="javascript">
alert("This Emp ID already Exists");
document.location="EmplyeeInformation.jsp";
</script>
<%
}
stmt.close();
con.close();
}
catch(Exception e) {
out.println(e.toString());
}
%>
</FORM>
</BODY>
</HTML>

Step 4: Create data deletion code from database ("ClearAction.jsp").
In this step you will learn how to delete data from database. When,  you will select employee id and employee name then select delete radio button after selecting delete radio button when you will click on submit button then data will successfully delete from database.

<%@ page language="java" import="java.lang.*" import="java.sql.*" %>

<%
Connection con = null;
String url = "jdbc:mysql://192.168.10.211:3306/";
String db = "amar";
String driver = "com.mysql.jdbc.Driver";
String userName ="amar";
String password="amar123";

String str=request.getParameter("r1");
String name=request.getParameter("empname");
String code=request.getParameter("empid");
int EmpID=Integer.parseInt(code);
try {
Class.forName(driver);
con = DriverManager.getConnection(url+db,userName,password);
String sql = "delete from Employee where empid= ?";
PreparedStatement stmt=null;
stmt=con.prepareStatement(sql);
stmt.setInt(1,EmpID);
int erase=stmt.executeUpdate();
if(erase==0) { %>
<script language="javascript">
alert("Deletion successful");
</script>
<%
}
if(erase==1) { %>
<script language="javascript">
alert("Deletion successful");
</script>
<%
}

stmt.close();
con.close();
out.println("Data delete successfully from database.");
}
catch(Exception e) {
out.println(e);
}
%>

Step 5: Create update data code ("update.jsp").
In this step you will learn, how to modify data in database by using JDBC database. 

<%@ page language="java" import="java.lang.*" import="java.sql.*" %>

<HTML>
<BODY>
<%
Connection con = null;
String url = "jdbc:mysql://192.168.10.211:3306/";
String db = "amar";
String driver = "com.mysql.jdbc.Driver";
String userName ="amar";
String password="amar123";


String rep=request.getParameter("empname");
String code=(String)request.getParameter("empid");
int ID=Integer.parseInt(code);
try {
Class.forName(driver);
con = DriverManager.getConnection(url+db,userName,password);
String rec="UPDATE Employee SET empname='"+rep+"' where empid='"+ID+"'";

Statement stmt=null;
stmt=con.createStatement();
int mod=stmt.executeUpdate(rec);
if(mod==0) { %>
<script language="javascript">
alert("This Emp ID already Exists");
</script>
<%
}
if(mod==1) { %>
<script language="javascript">
alert("Record Updated Successfully");

</script>
<%
}
con.commit();
stmt.close();
con.close();

}
catch(Exception e) { %>
<script language="javascript">
alert("Please Enter New Name");
document.location="EmplyeeInformation.jsp";
</script>
<%
}

%>
</BODY>
</HTML>


Here is the output of this program:
When you will enter new employee id and employee name and select insert button after selecting insert button click on submit button then data will insert successfully in database.

If  you will select same employee id then massage will display like this.





If you want to modify record then select employee id and enter new employee name. When you will select modify radio button then click on submit button then massage will display like this.








sessions

This JSP Tutorial shows you how to track the session between different JSP pages. In any web application user moves from one page to another and it becomes necessary to track the user data and objects throughout the application. JSP provide an implicit object "session", which can be use to save the data specific the particular to the user.
In this tutorial we will create an application that takes the user name from the user and then saves into the user session. We will display the saved data to the user in another page.
Here is the code of the JSP file (savenameform.jsp) that takes the input from user:

<%@ page language="java" %>
<html>
<head>
<title>Name Input Form</title>
</head>
<body>
<form method="post" action="savenametosession.jsp">
<p><b>Enter Your Name: </b><input type="text" name="username"><br>
<input type="submit" value="Submit">

</form>

</body>

The above page prompts the user to enter his/her name. Once the user clicks on the submit button, savenametosession.jsp is called. The JSP savenametosession.jsp retrieves the user name from request attributes and saves into the user session using the functionsession.setAttribute("username",username);. Here is the code of savenametosession.jsp:

<%@ page language="java" %>
<%
String username=request.getParameter("username");
if(username==null) username="";

session.setAttribute("username",username);
%>

<html>
<head>
<title>Name Saved</title>
</head>
<body>
<p><a href="showsessionvalue.jsp">Next Page to view the session value</a><p>

</body>

<%@ page language="java" %>
<%
String username=(String) session.getAttribute("username");if(username==null) username="";
%>
<html>
<head>
<title>Show Saved Name</title>
</head>
<body>
<p>Welcome: <%=username%><p>

</body>

The function session.getAttribute("username") is used to retrieve the user name saved in the session.

JSP Cookies

This tutorial shows how to handle cookies in JSP pages. In this tutorial you will learn how to add cookies through jsp page and then show the value of the same cookie in another JSP page.

Let's understand the cookies. Cookies are short pieces of data sent by web servers to the client browser. The cookies are saved to clients hard disk in the form of small text file. Cookies helps the web servers to identify web users, by this way server tracks the user. Cookies pay very important role in the session tracking.


Cookie Class
In JSP cookie are the object of the class javax.servlet.http.Cookie. This class is used to creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
The getCookies() method of the request object returns an array of Cookie objects. Cookies can be constructed using the following code:
Cookie(java.lang.String name, java.lang.String value)
Cookie objects have the following methods.
Method
Description
getComment()
Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.
getMaxAge()
Returns the maximum specified age of the cookie.
getName()
Returns the name of the cookie.
getPath()
Returns the prefix of all URLs for which this cookie is targeted.
getValue()
Returns the value of the cookie.
setComment(String)
If a web browser presents this cookie to a user, the cookie's purpose will be described using this comment.
setMaxAge(int)
Sets the maximum age of the cookie. The cookie will expire after that many seconds have passed. Negative values indicate the default behavior: the cookie is not stored persistently, and will be deleted when the user web browser exits. A zero value causes the cookie to be deleted
setPath(String)
This cookie should be presented only with requests beginning with this URL.
setValue(String)
Sets the value of the cookie. Values with various special characters (white space, brackets and parentheses, the equals sign, comma, double quote, slashes, question marks, the "at" sign, colon, and semicolon) should be avoided. Empty values may not behave the same way on all browsers.
Example Using Cookies
No we will write code in JSP file to set and then display the cookie.
Create Form
Here is the code of the form (cookieform.jsp) which prompts the user to enter his/her name.
<%@ page language="java" %>
<html>
<head>
<title>Cookie Input Form</title>
</head>
<body>
<form method="post" action="setcookie.jsp">
<p><b>Enter Your Name: </b><input type="text" name="username"><br>
<input type="submit" value="Submit">

</form>

</body>
Above form prompts the user to enter the user name. User input are posted to the setcookie.jsp file, which sets the cookie. Here is the code of setcookie.jsp file:
<%@ page language="java" import="java.util.*"%>
<%
String username=request.getParameter("username");
if(username==null) username="";


Date now = new Date();
String timestamp = now.toString();
Cookie cookie = new Cookie ("username",username);
cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);


%>

<html>
<head>
<title>Cookie Saved</title>
</head>
<body>
<p><a href="showcookievalue.jsp">Next Page to view the cookie value</a><p>

</body>
Above code sets the cookie and then displays a link to view cookie page. Here is the code of display cookie page (showcookievalue.jsp):
<%@ page language="java" %>
<%
String cookieName = "username";
Cookie cookies [] = request.getCookies ();
Cookie myCookie = null;
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if (cookies [i].getName().equals (cookieName))
{
myCookie = cookies[i];
break;
}
}
}

%>
<html>
<head>
<title>Show Saved Cookie</title>
</head>
<body>


<%
if (myCookie == null) {
%>
No Cookie found with the name <%=cookieName%>
<%
} else {
%>
<p>Welcome: <%=myCookie.getValue()%>.
<%
}
%>
</body>
When user navigates to the above the page, cookie value is displayed.



Disabling Session in JSP 
In this tutorial you will learn how to disable session creation in the JSP pages. Disabling the session in some pages will improve the performance of your JSP container.
Every time a JSP is requested, JSP creates an HttpSession object to maintain state for each unique client. The session data is accessible in the JSP as the implicit session object. In JSPs, sessions are enabled by default.

Session object uses the server resources. Each session object uses up a small amount of system resources as it is stored on the server side. This also increases the traffic as the session ID is sent from server to client. Client also sends the same session ID along with each request. If some of the JSP pages on your web site are getting thousands of hits from internet browser and there is not need to identify the user, so its better to disable the session in that JSP page.

You can tell the container to disable session in the JSP file by setting the session attribute to false. Set the session attribute of the page directive to false, as shown in the following example:
<%@ page session="false" %>
Here is the full code of jsp file in which session is disabled:
<%@ page language="java" session="false"%>
<html>
<head>
<title>Session Disabled</title>
</head>
<body>
<p>Session is Disabled in this page
</body>
</html>






No comments:

Post a Comment