Browse by Domains

Java Server Pages (JSP)Tutorial

Java Server Pages (JSP) is a programming tool on the application server side that supports platform-independent and dynamic methods to construct Web-based applications.

Much as Servlet technology does, the JSP method provides a web application. It can be considered an expansion of Servlet because it offers more features than servlet. Since we can differentiate design and development, the JSP pages are simpler to manage than Servlet. HTML tags and JSP tags are present in Java Server Pages.

To access enterprise servers, Java Server Pages has an approach to the entire community of Java APIs, including the JDBC API. This tutorial will walk you to the path of building your own web application in convenient and simple steps using Java Server Pages.

Also Read: JSP Interview Questions

Why should we Learn JSP?

There are numerous reasons for us to learn JSP.

1) Its extension to Servlet technology will be the very first reason to learn JSP. In JSP, we can use all the functionality of Servlet. In addition, speech-language, predefined tags, implicit entities and custom tags can be used in JSP, making it easier for JSP to create.

2) The second reason would be that there is no need to redeploy and recompile the project in case the JSP page is modified. If we have to modify the look and sound of the programme, the Servlet code has to be revised and recompiled.

3) Third would be about how easy JSP is to maintain and manage as we can conveniently separate the presentation and business logic.

4) In JSP, we can use several tags which reduce the code, such as action tags, JSTL, custom tags, etc. We may, in addition, use EL, implied objects, etc.

Java Server Pages

JavaServer Pages (JSP) is a Web page development technology that supports dynamic content. This allows programmers to use specific JSP tags to insert Java code into HTML pages. 

A part of JavaServer Pages is a type of Java servlet designed to perform the function of a Java web application user interface. JSPs are written as text files by Web developers that incorporate Html or XHTML script, XML components, and embedded JSP actions and commands.

For many purposes, JSP tags may be used, such as downloading data from the database or recording user interests, accessing modules of JavaBeans, transferring power between sites, exchanging information among queries, etc.

Applications and Advantages of JSP

Standard HTML does not contain dynamic data, whereas JSP does.

JSP’s benefits are fairly straightforward. First of all, the dynamic component is implemented in Java, not Visual Basic or any platform-specific language, so it is smoother and simpler to use. Lastly, it is platform-independent.

If we compare JSP and SSI, Server Side Includes is intended only for basic inclusions, not for actual systems that use form data, build links to databases, and etc.

Writing and modifying standard HTML is more practical than creating lots of HTML-generating println statements to generate HTML.

JavaScript can generate HTML dynamically on the client but can hardly interact with the webserver to perform complex tasks like database access and image processing etc.

Prerequisites

If you have any web application development skills using a certain computer language, it would be perfect. Assuming everyone Is familiar with what a web browser is and how the applications work over HTTP.

Setting up the environment for JSP

Prior to this, I would throw a note at you * Knowing Java Programming beforehand helps *

Taking you to step 1 of the ladder of setting up the environment for JSP.

  1. Set up the Java Development Kit

This move includes installing a Java Software Development Kit (SDK) implementation and properly setting up the PATH environment variable.

You may access SDK from the Web site of Oracle (Java SE Downloads).

Follow the instructions provided for installing and configuring the setup after downloading your Java. Finally, set the Route and JAVA HOME environment to refer to the directory with java and javac; usually, java installs dir/bin and java install dir.

Either you need to apply the following line to your C:\autoexec.bat file if you are running Windows and downloading the SDK in C:\jdk1.5.0_22:

set PATH = C:\jdk1.5.0_22\bin; %PATH%

set JAVA_HOME = C:\jdk1.5.0_22

Or you could also right-click on My Computer    Properties    Advanced Environment Variables. You’ll then change the input PATH and press the OK button.

jdk 5 home variable
jdk 5 edit path variable

On Unix, if the SDK is installed in /usr/local/jdk1.5.0_22 and you use the C shell, you will put the following into your .cshrc file:

setenv PATH /usr/local/jdk1.5.0_22/bin:$PATH

setenv JAVA_HOME /usr/local/jdk1.5.0_22

Scroll to know the second step.

  1. Configuring a Web Server- Tomcat

A variety of Web servers facilitating the creation of JavaServer Pages and Servlets are available on the market. Tomcat is among the servers which are free to download.

Apache Tomcat is a free software JavaServer Pages and Servlet technology deployment software that can act as a standalone server for JSP and Servlets testing and can be combined with the Apache Web Server. Here are the measures on your computer to set up Tomcat:

  • Download the fresh Tomcat update from https://tomcat.apache.org/.
  • Unpack the binary distribution into a decent setting until you have downloaded the installation. 

You can launch Tomcat by running the following commands on a Windows machine:

%CATALINA_HOME%\bin\startup.bat

Or

C:\apache-tomcat-5.5.29\bin\startup.bat 

You can launch Tomcat by performing the following instructions on a Unix machine:

$CATALINA_HOME/bin/startup.sh 

or 

/usr/local/apache-tomcat-5.5.29/bin/startup.sh

The default web applications that are included with Tomcat will be accessible after a promising startup by visiting http://localhost:8080/

On successful installation, you’ll see this page:

TomcatHomePage
  1. CLASSPATH setup

Even though servlets aren’t part of the Standard Edition Java Platform, the programmer must define the servlet classes.

You need to add the following lines into your C:\autoexec.bat file while you are running Windows:

set CATALINA = C:\apache-tomcat-5.5.29

set CLASSPATH = %CATALINA%\common\lib\jsp-api.jar; %CLASSPATH%

If you’re using a C shell on Unix , you’ll add the following lines in your .cshrc file:

setenv CATALINA = /usr/local/apache-tomcat-5.5.29

setenv CLASSPATH $CATALINA/common/lib/jsp-api.jar:$CLASSPATH

JSP – Syntax

We will be addressing Syntax in JSP in this section. We can note the basic use of plain syntax (i.e. elements) associated with the development of JSP.-

JSP’s elements

The JSP elements are listed below:

Scriptlet 

A script may consist of any number of JAVA language statements, declarations of a variable or procedure, or statements that are true in the page script’s language.

The following is the scriptlet syntax −

<% code fragment %>

The XML version of the above syntax can be written as follows :

<jsp:scriptlet>
   code fragment
</jsp:scriptlet>

The text, HTML tags, or JSP components that you write need to be beyond the document. The following is the first and simple illustration of JSP:

<html>   
<head><title>Hello Kitty</title></head>   
<body>    
   Hello Kitty! <br/> 
<%       
  out.println("Your IP address is " + request.getRemoteAddr());    %>
    </body> 
</html>

Let us retain the code above in the hello.jsp JSP file and place this file in the folder C:\apache-tomcat7.0.2\webapps\ROOT.

Using the URL http://localhost:8080/hellokitty.jsp, search via the same.

The mentioned program will create the following –

JSP Declarations   

Declaring one or more methods or variables done by Declaration that can be used later in the JSP file in the Java code. Before you use it in the JSP code, you must declare the variable or process.

The syntax for JSP declarations is below:

<%! declaration; [ declaration; ]+ ... %>

The XML version of the above syntax can be written as follows:

<jsp:declaration>
   code fragment
</jsp:declaration>

For JSP declarations, the following is an example:

<%! int i = 0; %> 

<%! int a, b, c; %> 

<%! Circle a = new Circle(2.0); %>

JSP Expression

In the scripting language, JSP expression components provide an expression that is evaluated, converted into a string, and inserted where the expression appears in a JSP file. Because an expression’s meaning is translated to a string, you can use an expression in a JSP file inside a line of text, whether or not it’s tagged with HTML.

An expression element can include any expression that is legitimate under the Java Language Specification, but you will be unable to use a semicolon to terminate an expression.

The JSP Expression syntax follows :

<%= expression %>

The XML version of the above syntax can be written as follows:

<jsp:expression>
   expression
</jsp:expression>

example showing a JSP Expression:

<html> 
   <head><title>A Commen Test</title></head> 
   
   <body>
      <p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
   </body> 
</html> 

Result:

Today’s date: 20-Jan-2021 12:24:28

JSP – Directives

We will address directives in JSP in this section. These directives supply the container with guidance and instructions, informing them how to manage some JSP processing elements.

The general configuration of the server class is influenced by the JSP directive. It normally has the type below:

<%@ directive attribute = “value” %>

Directives may have a variety of attributes that can be identified, divided by commas, as key-value pairs.

There are optional blanks between the @ symbol and the directive name and between the last attribute and the closing %>.

JSP – The page Directive

The page directive is used to get the container with instructions. These instructions apply to the current section of the JSP. Page directives can be encoded anywhere on the JSP page. By practice, at the top of the JSP list, page instructions are encrypted.

The basic syntax of the page directive follows –

<%@ page attribute = "value" %>

The XML version of the above syntax can be written as follows –

<jsp:directive.page attribute = "value" />

The include Directive

During the conversion process, the inclusion directive is used to add a file. This directive informs the container, during the translation process, to combine the content of other external files with the current JSP. The included directives can be encoded anywhere on your JSP page.

The general form of use for this Directive is as follows –

<%@ include file = “relative url” >

In fact, the filename in the include directive is a relative URL. The JSP compiler assumes that the file is in the same directory as your JSP if you only define a filename with no related path.

The XML version of the above syntax can be written as follows –

<jsp:directive.include file = "relative url" />

The taglib Directive

You can define custom JSP tags that appear like HTML or XML tags using the JavaServer Pages API, and a tag library is a compilation of user-defined tags that enforce custom behaviour.

The taglib directive declares that your JSP page uses a series of custom tags, specifies the library location, and includes a way to define your JSP page’s custom tags:

<%@ taglib uri=”uri” prefix = “prefixOfTag” >

Here, the value of the uri attribute resolves to a position the container knows, and the attribute of the prefix tells a container what custom actions are bits of markup.

The XML version of the above syntax can be written as follows –

<jsp:directive.taglib uri = "uri" prefix = "prefixOfTag" />

JSP – Actions

In this segment, we will answer JSP behaviour. In XML syntax, these actions use structures to control the conduct of the servlet engine. You can dynamically insert a file, reuse components of JavaBeans, forward the consumer to some other site, or create Java plug-in HTML.

The Action feature has only one syntax, since it conforms to the XML standard –

<jsp:action_name attribute = “value” />

Common Attributes

In this segment, we will answer JSP behaviour. In XML syntax, these actions use structures to control the conduct of the servlet engine.

The Action feature has only one syntax since it conforms to the XML standard –

Id attribute

The id attribute defines the Action variable uniquely and enables it to be accessed inside the JSP page. If the Operation generates an instance of an object, you can use the id value to reference it from the PageContext implied object.

Scope attribute

The life cycle of the Action element is defined by this attribute. As the scope attribute specifies the lifetime of the object associated with the id, the id attribute and the scope attribute are closely related. There are four possible values in the scope attribute: (a) page, (b)request, (c)session, and (d) application.

JSP – Implicit Objects

We are going to address the Tacit Objects in JSP in this section. These objects are the Java objects made accessible to the developers on each page by the JSP Container, which can be named directly by the developer without being expressly declared. Often, pre-defined variables are called JSP Implicit Objects.

The request Object

The request object is an example of an object called javax.servlet.http.HttpServletRequest. The JSP engine generates a new object to represent the request whenever a client asks for a page.

The request object offers techniques for extracting information about the HTTP header, including form records, cookies, HTTP methods, etc.

In a corresponding section − JSP – Client Request, we will cover a full range of methods associated with the request object.

Example of Implicit request object:

In the example here, we collect user input on the index.html page and view the same details on the userinfo.jsp page using the implicit request object.

index.html

<html>
<head>
<title>Enter UserName and Password</title>
</head>
<body>
<form action="userinfo.jsp"> 
Enter User Name: <input type="text" name="uname" /> <br><br>
Enter Password: <input type="text" name="pass" /> <br><br>
<input type="submit" value="Submit Details"/> 
</form>
</body>
</html>

userinfo.jsp

<%@ page import = " java.util.* " %>
<html> 
<body> 
<% 
String username=request.getParameter("uname"); 
String password=request.getParameter("pass"); 
out.print("Name: "+username+" Password: "+password);
%> 
</body> 
</html>

You’ll get something like this after running the code:

 

This is the output page for userinfo.jsp. We also obtained the ID and password that the user entered on the login tab.

The response Object

A response object is an instance of an object called javax.servlet.http.HttpServletResponse. And when the request object is generated by the server, it often generates an object to display the client’s answer.

The interfaces that cope with generating new HTTP headers are also specified by the response object. The JSP developer can introduce additional cookies or date stamps, HTTP status codes, etc., from this object.

Example of Implicit response object:

We will get ID and password from the login page in the following example and then we pair them with the right hardcoded ID or password. The sign-in page redirects to the progress page if the credentials are correct, otherwise, it reroutes to the failed JSP page.

index.html

<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="checkdetails.jsp"> 
UserId: <input type="text" name="id" /> <br><br>
Password: <input type="text" name="pass" /> <br><br>
<input type="submit" value="Sign In!!"/> 
</form>
</body>
</html>

checkdetails.jsp

<html> 
<head><title>Check Credentials</title>
</head>
<body> 
<% 
String uid=request.getParameter("id"); 
String password=request.getParameter("pass"); 
session.setAttribute("session-uid", uid);
if(uid.equals("Chaitanya") && password.equals("BeginnersBook"))
{
 response.sendRedirect("success.jsp");
}
else
{
 response.sendRedirect("failed.jsp");
}
%> 
</body> 
</html>

success.jsp

<html> 
<head><title>Success Page</title>
</head>
<body> 
<% 
String data=(String)session.getAttribute("session-uid");
out.println("Welcome "+ data+"!!");
%> 
</body> 
</html>

If the credentials entered by the user are incorrect, the access will be diverted to this tab.

failed.jsp

<html> 
<head><title>Sign-in Failed Page</title>
</head>
<body> 
<% 
String data2=(String)session.getAttribute("session-uid");
out.println("Hi "+ data2+". Id/Password are wrong. Please try Again.");
%> 
</body> 
</html>

You’ll get something like this after running the code:

The login page:

If correct details entered, then you’ll see this:

If entered wrong details then this:

The out Object

The implicit output object is an instance of an object called javax.servlet.jsp.JspWriter, which is used to submit material in a reply.

Based on how much the page is buffered or not, the original JspWriter object gets instantiated differently. Buffering can be quickly shut off by using the page directive’s buffered= ‘false’ value.

The object JspWriter includes much of the same methods as the class java.io.PrintWriter. JspWriter, however, has several different approaches planned to cope with buffering. JspWriter throws IOExceptions as opposed to the PrintWriter object.

You’ll get something like this after running the code:

The login page:

If correct details entered, then you’ll see this:

If entered wrong details then this:

The out Object

The implicit output object is an instance of an object called javax.servlet.jsp.JspWriter, which is used to submit material in a reply.

Based on how much the page is buffered or not, the original JspWriter object gets instantiated differently. Buffering can be quickly shut off by using the page directive’s buffered= ‘false’ value.

The object JspWriter includes much of the same methods as the class java.io.PrintWriter. JspWriter, however, has several different approaches planned to cope with buffering. JspWriter throws IOExceptions as opposed to the PrintWriter object.

Example of Implicit out object:

<HTML>
<HEAD> 
<TITLE> OUT IMPLICIT OBJECT EXAMPLE </TITLE>
</HEAD>
<BODY>
<%
out.print( “print the statement " );
out.println( "println" );
out.print("print another statement");
%>
</BODY>
</HTML>

Result:
print the statement println
print another statement

The Session Object

The session object has been used between client requests to monitor client sessions. 

Example of Implicit session object:

A text box along with a submit button will show the below html tab. The send operation moves the access to the page session.jsp.

index.html

<html> 
<head>
<title>Welcome Page: Enter your name</title>
</head>
<body> 
<form action="session.jsp"> 
<input type="text" name="inputname"> 
<input type="submit" value="click here!!"><br/> 
</form> 
</body> 
</html>

The session.jsp page shows the name entered by the user on the index page and stores the same variable in the session object, so that it can be accessed from any page before the session is disabled.

session.jsp

<html> 
<head>
<title>Passing the input value to a session variable</title>
</head>
<body> 
<% 
String uname=request.getParameter("inputname"); 
out.print("Welcome "+ uname);
session.setAttribute("sessname",uname); 
%> 
<a href="output.jsp">Check Output Page Here </a>
</body> 
</html>

On this tab, we fetch the value of the variable from the session object and show it.

On this tab, we fetch the value of the variable from the session object and show it.

output.jsp

<html> 
<head>
<title>Output page: Fetching the value from session</title>
</head>
<body> 
<% 
String name=(String)session.getAttribute("sessname"); 
out.print("Hello User: You have entered the name: "+name); 
%> 
</body> 
</html>

You’ll get this after running the code:

jsp-welcome-page
User-jsp-page
output-screen

The Application Object

The application object is a direct wrapper for the produced Servlet around the ServletContext object and an instance of the javax.servlet.ServletContext object in fact.

This entity is a JSP page representation across its entire lifespan. This object is generated when the JSP page is initialised and will be deleted when the jspDestroy() method destroys the JSP page.

Example of Implicit application object:

A JSP website that uses the programme to collect the amount of hits. We are counting the number of hits to a JSP page using the implicit object of the application in this case.

counter.jsp

<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Application Implicit Object Example</title>
</head>
<body>
<%
 //Comment: This would return null for the first time
 Integer counter= (Integer)application.getAttribute("numberOfVisits");
 if( counter ==null || counter == 0 ){
 //Comment: For the very first Visitor 
 counter = 1;
 }else{
 //Comment: For Others 
 counter = counter+ 1;
 }
 application.setAttribute("numberOfVisits", counter);
%>
<h3>Total number of hits to this Page is: <%= counter%></h3>
</body>
</html>

You’ll get the following result after running the code:

Number of hits = 1(first time visitor).

application1

After refreshing the page:

application2

The config Object

The config object is a javax.servlet.ServletConfig instantiation, which is a direct wrapper for the produced servlet around the ServletConfig object.

This object provides the JSP programmer access to configuration parameters for the Servlet or JSP generator, such as paths or file addresses.

The configuration method below is the only one you will ever use, and its use is negligible.

config.getServletName();

This returns the name of the servlet, which is the string found in the element <servlet-name> specified in the file WEB-INF\web.xml.

Example of Implicit config object:

web.xml

 Below  I’m just going to be describing the servlet name and the mapping of the servlet in it. Later, I will use the implicit config object to fetch a few pieces of information from this file.

<web-app>

<servlet> 

<servlet-name>BeginnersBookServlet</servlet-name> 

<jsp-file>/index.jsp</jsp-file> 

</servlet> 

<servlet-mapping> 

<servlet-name>BeginnersBookServlet</servlet-name> 

<url-pattern>/index</url-pattern> 

</servlet-mapping> 

</web-app>

index.jsp

We call the getServletName() config object method on this JSP page to retrieve the servlet name from the web.xml file.

<html>
<head> <title> Config Implicit Object</title>
</head>
<body>
<% 
String sname=config.getServletName(); 
out.print("Servlet Name is: "+sname); 
%>
</body>
</html>

You’ll get the following result after running the code:

config

The page Object

This object is a real reference to the page’s case. It can be thought of as an entity representing the whole page of the JSP.

Currently, the page object is a direct synonym of this object.

The exception Object

A wrapper containing an exception tossed from the previous page is the exception property. Usually, it is used to produce an acceptable answer to the state of the error.

Example of Implicit exception object:

In this case, we take two numerical inputs from the user, and then we divide them. In the example below, we have used the exception implicit object to manage some form of exception.

index.html

<html>
<head>
<title>Enter two Integers for Division</title>
</head>
<body>
<form action="division.jsp"> 
Input First Integer:<input type="text" name="firstnum" />
Input Second Integer:<input type="text" name="secondnum" /> 
<input type="submit" value="Get Results"/> 
</form>
</body>
</html>

We have defined exception.jsp as errorPage here, which means that if an exception happens on this JSP page, the authority will be moved automatically to the JSP exception.jsp page. Remember: We have used the Page Directive errorPage attribute to define the JSP page handling exception (< %@ page errorPage= “exception.jsp” % >).

division.jsp

<%@ page errorPage="exception.jsp" %> 
<% 
String num1=request.getParameter("firstnum"); 
String num2=request.getParameter("secondnum"); 
int v1= Integer.parseInt(num1);
int v2= Integer.parseInt(num2);
int res= v1/v2;
out.print("Output is: "+ res);
%>

We also set ErrorPage to true on the JSP page below, which is also a Page Directive attribute used to make a page suitable for exception handling. This page is known as an exception page at the division.jsp, this page will be invoked in the event of an exception condition. This shows an error message to the user using the implicit exception object.

exception.jsp

<%@ page isErrorPage=”true” %> 

Got this Exception: <%= exception %> 

Please correct the input data.

You’ll get a result something like this:

Two entry fields panel for two integer values.

inputPage

The message of Arithmetic Exception because we have supplied the second digit as null.

exceptionPage

JSP – Form Processing

We will address Form Processing in JSP in this section. If you need to transfer some details from your browser to the remote server and eventually to your backend software, you would have experienced several scenarios. Two approaches are used by the browser to transfer this information to the webserver. The GET System and the POST method are these approaches.

The Methods in Form Processing

GET method

Encoded user information attached to the page request is submitted by the GET process.

http://www.test.com/hello?key1=value1&key2=value2

The GET method is the default method for transferring information to the webserver from the browser and generates a long string that appears in the Location:box of your browser. It is proposed that it is safer not to use the GET form. If you have a login to pass on to the computer or any personal information.

The GET method has a size limitation: a request string can only contain 1024 characters.

This data is transferred via the QUERY_STRING header and can be accessed via the QUERY_STRING environment variable that can be managed using the request object methods getQueryString() and getParameter().

POST method

The POST process is usually a more efficient method of transferring information to a downstream application.

This method bundles the data exactly like the GET method. It delivers it as a different message inside the URL. In the type of regular input that you can parse and use for your execution, this message comes to the backend software.

JSP uses the getParameter() method to read basic parameters to address this request and the getInputStream() method to read the client’s binary data stream.

GET Method Example Using URL

The following URL uses the GET method to transfer two values to the HelloForm programme.

The main.jsp JSP software for managing information generated by the web browser is below. We can use the getParameter() process, which makes it much easier to access the data transferred:

<html>
   <head>
      <title>Using GET Method to Read Form Data</title>
   </head>
   
   <body>
      <h1>Using GET Method to Read Form Data</h1>
      <ul>
         <li><p><b>First Name1:</b>
            <%= request.getParameter("first_name1")%>
         </p></li>
         <li><p><b>Last  Name2:</b>
            <%= request.getParameter("last_name2")%>
         </p></li>
      </ul>
   
   </body>
</html>

Now type http://localhost:8080/main.jsp first_name=LARA&last_name=AZAR in the Location: box of your browser and it will yield the following result −

Using GET Method to Read Form DataFirst Name: LARALast Name: AZAR

GET Method Example Using Form

The following is an instance that uses the HTML FORM and the submit button to move two values. Now use the same JSP main.jsp to handle this input.

<html>
   <body>
      
      <form action = "main.jsp" method = "GET">
         First Name1: <input type = "text" name = "first_name1">
         <br />
         Last Name2: <input type = "text" name = "last_name2" />
         <input type = "submit" value = "Submit" />
      </form>
      
   </body>
</html>

Store this HTML in the Hello.htm file and move it in the directory <Tomcat-installation-directory>/webapps/ROOT. You can get the following output when you have access to http://localhost:8080/Hello.htm.

First Name: 
Last Name:  

POST Method Example Using Form

Let us do some modification to manage both the GET and the POST method from the above JSP. Here is the JSP main.jsp programme that uses the GET or POST methods to handle the input given by the web browser.

In fact, the above JSP does not change because the only way to pass parameters is altered and no binary data is passed to the JSP programme.

<html>
   <head>
      <title>Using GET and POST Method to Read Form Data</title>
   </head>
   
   <body>
      <center>
      <h1>Using POST Method to Read Form Data</h1>
      
      <ul>
         <li><p><b>First Name1:</b>
            <%= request.getParameter("first_name1")%>
         </p></li>
         <li><p><b>Last Name2:</b>
            <%= request.getParameter("last_name2")%>
         </p></li>
      </ul>
   
   </body>
</html>

Content of the Hello.htm file −

<html>
   <body>
      
      <form action = "main.jsp" method = "POST">
         First Name1: <input type = "text" name = "first_name1">
         <br />
         Last Name2: <input type = "text" name = "last_name2" />
         <input type = "submit" value = "Submit" />
      </form>
      
   </body>
</html>

Now let’s hold main.jsp and hello.htm in the directory <Tomcat-installationdirectory>/webapps/ROOT. You will generate the following output by visiting http://localhost:8080/Hello.htm.

First Name: 
Last Name:  

Passing Checkbox Data to JSP Program

Checkboxes are used where a list of more than one alternative is needed.

The example of an HTML code, CheckBox.htm, for a type of two checkboxes is below.

<html>
   <body>
      
      <form action = "main.jsp" method = "POST" target = "_blank">
         <input type = "checkbox" name = "English" checked = "checked" /> English
         <input type = "checkbox" name = "Biology"  /> Biology
         <input type = "checkbox" name = "chemistry" checked = "checked" /> Chemistry
         <input type = "submit" value = "Select Subject" />
      </form>
      
   </body>
</html>

Result −

 English  Biology  Chemistry 

The following is the main.jsp JSP software to control the input for the checkbox button generated by the web browser.

<html>
   <head>
      <title>Reading Checkbox Data</title>
   </head>
   
   <body>
      <h1>Reading Checkbox Data</h1>
      
      <ul>
         <li><p><b>English Flag:</b>
            <%= request.getParameter("English")%>
         </p></li>
         <li><p><b>Biology Flag:</b>
            <%= request.getParameter("Biology")%>
         </p></li>
         <li><p><b>Chemistry Flag:</b>
            <%= request.getParameter("Chemistry")%>
         </p></li>
      </ul>
   
   </body>
</html>

result −

Reading Checkbox Data

  • English Flag:: on
  • Biology Flag:: null
  • Chemistry Flag:: on

Reading All Form Parameters

The following is a basic example that uses HttpServletRequest’s getParameterNames() method to read all available type parameters. This procedure returns an enumeration in an unspecified order containing the parameter names.

Until we have an Enumeration, using the hasMoreElements() method to decide when and how to stop using the next element() method to get each parameter name, we will loop down the Enumeration in a standardized way.

<%@ page import = "java.io.*,java.util.*" %>
 
<html>
   <head>
      <title>HTTP Header Request Example</title>
   </head>
 
   <body>
      <center>
         <h2>HTTP Header Request Example</h2>
         <table width = "100%" border = "1" align = "center">
            <tr bgcolor = "#949494">
               <th>Param Name</th>
               <th>Param Value(s)</th>
            </tr>
            <%
               Enumeration paramNames = request.getParameterNames();
               while(paramNames.hasMoreElements()) {
                  String paramName = (String)paramNames.nextElement();
                  out.print("<tr><td>" + paramName + "</td>\n");
                  String paramValue = request.getHeader(paramName);
                  out.println("<td> " + paramValue + "</td></tr>\n");
               }
            %>
         </table>
      </center>
   
   </body>
</html>

Content of the Hello.htm âˆ’

<html>
   <body>
      
      <form action = "main.jsp" method = "POST" target = "_blank">
         <input type = "checkbox" name = "english" checked = "checked" /> english
         <input type = "checkbox" name = "biology"  /> Biology
         <input type = "checkbox" name = "chemistry" checked = "checked" /> Chemistry
         <input type = "submit" value = "Select Subject" />
      </form>
   
   </body>
</html>

We’ll cover filters in JSP in this part. Servlet and JSP Filters are Java classes that can be used for the following purposes in Servlet and JSP Programming:

  • To intercept requests from a customer until they enter a back-end resource.
  • To exploit server responses before being sent back to the client.

In the deployment descriptor file web.xml, filters are configured and then mapped to either servlet or JSP names or URL patterns in the deployment descriptor of the programme. You can find the deployment descriptor file web.xml in the directory <Tomcat-installation-directory>\conf.

When the web application begins using the JSP jar, it generates an instance of each filter you have declared in the deployment descriptor. The filters execute in the order in which they are declared in the descriptor of the deployment.

JSP Filter Example

The following example shows how to print the IP address of the client and the current date-time if a JSP file is downloaded. This example can give you a simple understanding of the JSP filter, but the same principle can be used to write more complex filter applications.

JSP – Cookies Handling

We’ll cover the handling of cookies in JSP in this section. Cookies are text files saved on the client machine that are stored for various purposes of data tracking. HTTP cookies are transparently supported by JSP, using analogous servlet technologies.

In finding and returning consumers, there are three phases involved:

  • The server script gives the browser a series of cookies. Name, age, or identity number, for example, etc.
  • The browser saves this information for potential use on the local desktop.
  • When the browser makes some request to the web server the next time, it sends some cookies to the server, and the server uses the information to identify the user or for some other purpose.

The Anatomy of a Cookie

A cookie-setting JSP might send headers that resemble something like this:

HTTP/1.3 201 OK

Date: Thu, 20 Jan 2021 22:03:38 GMT

Server: Apache/1.3.9 (UNIX) PHP/4.0b3

Set-Cookie: name = xyz; expires = Friday, 20-Jan-21 22:03:38 IST; 

   path = /; domain = https://www.mygreatlearning.com/

Connection: close

Content-Type: text/html

The Set-Cookie header includes, as you can see, a name value pair, a IST date, a path and a domain. The name and value will be encrypted with the URL. The field expires a command for the web browser to “forget” the cookie just after the date and time specified.

Setting Cookies with JSP

Three phases include setting cookies with JSP 

Step 1: How to Create a Cookie object

With a cookie name and a cookie value, all of which are strings, you call the Cookie Constructor.

Cookie cookie = new Cookie(“key”,”value”);

Bear in mind, blank space or any of the following elements does not include either the name or value:

[ ] ( ) = , ” / ? @ : ;

Step 2: Set the max age

Those who use setMaxAge to define how lengthy the cookie should be valid for (in seconds). Within 24hrs, the program automatically will set up a cookie:

cookie.setMaxAge(60*60*24); 

Step 3: Send the Cookie into the HTTP response headers

To add cookies into the HTTP response header, you use response.addCookie as follows:

response.addCookie(cookie);

Taking an Example

Let us change our Sample Form to set the first and last names of the cookies.

<%
   // Create cookies for first and last names.      
   Cookie firstName1 = new Cookie("first_name1", request.getParameter("first_name1"));
   Cookie lastName2 = new Cookie("last_name2", request.getParameter("last_name2"));
   
   // Set expiry date after 24 Hrs for both the cookies.
   firstName.setMaxAge(60*60*24); 
   lastName.setMaxAge(60*60*24); 
   
   // Add both the cookies in the response header.
   response.addCookie( firstName1 );
   response.addCookie( lastName2 );
%>
 
<html>
   <head>
      <title>Setting Cookies</title>
   </head>
   
   <body>
      <center>
         <h1>Setting Cookies</h1>
      </center>
      <ul>
         <li><p><b>First Name1:</b>
            <%= request.getParameter("first_name1")%>
         </p></li>
         <li><p><b>Last  Name2:</b>
            <%= request.getParameter("last_name2")%>
         </p></li>
      </ul>
   
   </body>
</html>

putting the above program in main.jsp file and using it in the below mentioned HTML page −

<html>
   <body>
      
      <form action = "main.jsp" method = "GET">
         first name1: <input type = "text" name = "first_name1">
         <br />
         last name2: <input type = "text" name = "last_name2" />
         <input type = "submit" value = "Submit" />
      </form>
      
   </body>
</html>

Reading Cookies with JSP

One requires to build a collection of javax.servlet.http.Cookie objects to read cookies by calling the getCookies() function of HttpServletRequest. Then loop via the list and use getName() and getValue() methods to reach each cookie and its associated value.

Now let’s place the above code in the main.jsp file and attempt to use it. If you set the first name cookie to “Maria” and the last name cookie to “Lee” then run http://localhost:8080/main.jsp should show the following results −

 Found Cookies Name and Value

Name : first_name, Value: Maria

Name : last_name,  Value: Lee

Delete Cookies with JSP

It’s really easy to erase cookies. If you’d like to uninstall a cookie, you just need to obey these 3 measures.

  • Store the cookie in the cookie object by reading an existing cookie.
  • Set the cookie age to zero using the setMaxAge() function to uninstall an existing cookie.
  • Simply Adding this cookie straight to the message header.

Now run http://localhost:8080/main.jsp again and only one cookie should be seen as follows −

 Found Cookies Name and Value

Name : last_name,  Value: Player

JSP – Session Tracking

In this section, we’re trying to discuss session tracking in the JSP. HTTP is a stateless protocol that implies that every time a client scoops up a Web page, the client opens a separate connection to the Web server, and the server does not automatically keep a record of the prior client request.

Maintaining Session Between Web Client and Server

Now let us evaluate a few possibilities for maintaining a session between both the Web Client and the Web Server.

Cookies

A web server can assign a unique session ID as a cookie to each web client and can be recognised using the cookie received for subsequent requests from the client.

It may not be an efficient method, as the search engine does not promote a cookie on occasions. It is not suggested that this method be used to maintain sessions.

Hidden Form Fields

This entry ensures that a given name and value are immediately included in GET or POST details when the form is sent. The session-id value can be used to keep track of various web browsers every time the web explorer sends the query back.

URL Rewriting

At the end of each URL, you can append any extra info. This data defines the session; the server will connect the session identifier with the data about that session that it has stored.

URL rewriting is a great way to manage sessions; even while cookies are not allowed, it functions with browsers. The downside here is that you would have to dynamically create any URL to add a session ID, while a plain static HTML page is a page.

The Session Object

Besides the above-listed options, JSP enables the use of servlet supported HttpSession Interface. This GUI offers a means for a user to be detected.

  • A query for one website or
  • Visiting a website or a blog
  • Store details for the customer

JSPs have session monitoring allowed by default, and a new HttpSession object is actualized immediately for each new client. Disabling session monitoring includes clear disabling by setting the session attribute of the Page directive to false, as follows−

<%@ page session = “false” %>

Via the implied session object, the JSP engine exposes the HttpSession object to the JSP author. Since the JSP programmer is already supplied with the session item, the programmer may automatically start saving and extracting data from the object without initialization or getSession ().

Deleting the Session Data

You have many choices when you are finished with the session data of a customer,

  • You may call the public void removeAttribute(String name) method to erase the meaning associated with a given key.
  • You can call the public void invalidate() method to discard an entire session by removing the entire session.
  • Setting Session timeout -The public void setMaxInactiveInterval(int interval) method may be called to independently set the timeout for a session.
  • Log out the user -You should call the servers that support servlets 2.4 to log out the client from the Site server and invalidate all sessions that belong to all users.
  • web.xml Setup – When you’re using Tomcat, you may customise the session timeout in the web.xml file as described, except for the methods listed above.

<session-config>

   <session-timeout>15</session-timeout>

</session-config>

In Tomcat, the timeout is expressed as minutes and overrides the default timeout of 30 minutes.

The timeout period for that session is returned in seconds by the getMaxInactiveInterval() method in a servlet. So if your session is 15 minutes configured in web.xml, getMaxInactiveInterval() will return 900.

JSP – Handling Date

We will explore how to deal with data in JSP in this section. One of the most significant benefits of using JSP is that all the methods available in core Java can be used. We can take you through the Date class found in the java.util package; the latest date and time are encapsulated in this class.

Date( )

One statement that matches the amount of msec that have passed after midnight, January 1, 1970, is acknowledged by the following constructor.

Date(long millisec)

Getting Current Date and Time

For the JSP software, the latest date and time can be very conveniently accessed. With the toString() method process, you may use a simple Date object to print the current date and time as below –

<%@ page import = "java.io.*,java.util.*, javax.servlet.*" %>
 
<html>
   <head>
      <title>Display Current Date & Time</title>
   </head>
   
   <body>
      <center>
         <h1>Display Current Date & Time</h1>
      </center>
      <%
         Date date = new Date();
         out.print( "<h2 align = \"center\">" +date.toString()+"</h2>");
      %>
   </body>
</html>

Keep refreshing the page with the URL http://localhost:8080/CurrentDate.jsp. It will show the difference in seconds every time you refresh.

Date Formatting using SimpleDateFormat

SimpleDateFormat is a specific class for locale-sensitive encoding and parsing of dates. SimpleDateFormat lets you begin by choosing some user-defined date-time configuration styles.

Let us change the example above as follows:

<%@ page import = "java.io.*,java.util.*" %>
<%@ page import = "javax.servlet.*,java.text.*" %>
 
<html>
   <head>
      <title>Display Current Date & Time</title>
   </head>
   
   <body>
      <center>
         <h1>Display Current Date & Time</h1>
      </center>
      <%
         Date dNow = new Date( );
         SimpleDateFormat ft = 
         new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
         out.print( "<h2 align=\"center\">" + ft.format(dNow) + "</h2>");
      %>
   </body>
</html>

Once again, compile the above servlet and then use the URL http://localhost:8080/CurrentDate to call this servlet.

Take up free Java programming courses from a great learning academy and upskill yourself.

Engaging in the study of Java programming suggests a keen interest in the realm of software development. For those embarking upon this journey with aspirations towards a career in this field, it is recommended to explore the following pages in order to acquire a comprehensive understanding of the development career path:

Software engineering courses certificates
Software engineering courses placements
Software engineering courses syllabus
Software engineering courses fees
Software engineering courses eligibility
Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top