JSP – Quick Guide For Beginners

What is JavaServer Pages?

The JavaServer Pages (JSP), a server-side technology, helps developers to develop web pages, which use HTML, XML, SOAP, etc. It is also referred to as Jakarta Server Pages. In JSP, developers can embed the java code in the HTML language. There are unique tags in the JSP, which allows the use of Java code in HTML. These tags begin and end with ‘<%’ and ‘%>’ symbols, respectively. For running JSPs, you need a web server containing the servlet container. For example, you can use Apache Tomcat or Jetty

JSP is modeled from the Java servlets. Java servlet is also called Jakarta Servlet. During the runtime, JSPs are transformed into servlets; therefore, they are called servlets. Generally, JSPs are written in text files and embed HTML or XHTML code, JSP actions, XML elements, and JSP commands. JSPs plays the role of user interfaces in Java web applications. All JSP implicit objects, like request, session, config, out, response, application, page, and pageContext, are created by the web container

You might have come across web page forms. The purpose of these forms is to collect data from different users. In these webpage forms, JSP is used for taking data from users as input, arranges these data in the form of a database, and generates web pages. The primary objective of JSP is to present XML and HTML document types. But, it can also present documents in other formats, as it uses OutputStream. The file extension for JSP is .jsp, .jspx, .jspf, and the internet media type is application/jsp. 

You can convert any HTML file into the JSP file by changing the file extension .html to .jsp. After changing the extension, use JSP tags to add java code inside HTML pages. Using JPS, developers can generate dynamic web pages and platform-independent web pages. Let us see some significant features of JSP. 

Check out our Human Computer Interface guide which will be good for beginners.

JSP Features

JSP is one of the convenient ways of creating dynamic web content. There are several reasons why developers choose JSP for creating several applications. Here are some handpicked features of Jakarta Server Pages. 

  • There are action and custom tags in JSP. Therefore, the code length of JSP is small in size. 
  • It is straightforward to write code in JSP, as it embeds java programming language in HTML or XML pages. 
  • JSP allows developers to collect the data and put it into the database or read or write the data into the database. 
  • This server-side technology is highly flexible, portable, and robust because it does not depend on any browser or server. 
  • There is no requirement for JSP code to compile again and again. It is platform-independent and can be run on any console without recompiling. 
  • JSP incorporates implicit objects, servlets, and custom tags. Therefore, developers generate interactive and real-time web pages. 
  • We can also embed other scripting languages in JSP programs, like JavaScript, Perl, VBScript, etc. By default, Java is the scripting language of JSP. 

Why use Java Server Pages?

There are several advantages of using JSPs. They act similarly to that of the Common Gateway Interface (CGI). Web servers execute all programs that generate dynamic web pages on the common gateway interface. When we compare JSP with CGI, JSP is more robust and offers more benefits to developers. Here are some reasons that will help to understand how JSP is more advantageous than CGI. 

  • Developers can add Dynamic Elements in HTML using JSP. If they use CGI, they need to create a separate CGI file for Dynamic Elements. 
  • JSPs are compiled and later run on any platform. On the other hand, CGI loads the interpreter and interprets the code whenever you request the web page. 
  • You can use JSP and servlets together for monitoring the business logic. The Java servlet template engines support this combined model of JSP and servlet. 
  • JSP is a high-level abstraction of Java servlets. These pages are created at the top level of the Java servlet interface. Hence, they can access all the primary Java interfaces, like JAXP, JDBC, JNDI, etc. 
  • In the MVC architecture, JSP is used as its view layer. 
  • All enterprise-level applications are executed on the platform, called Java EE. The Java EE platform incorporates JSP. 

Advantages of JSP 

JSP is more efficient and sturdy than other technologies, like JavaScript, Static HTML, Pure Servlets, etc. Here we shall see how JSP is advantageous over other technologies. 

  • One of the most desirable advantages of JSP is it uses the Java programming language for writing its dynamic part. It does not use Visual Basic for writing the code. Secondly, it is compatible with other operating systems. 
  • Using JSPs, we embed the Java code into HTML pages. Hence, it is effortless to modify HTML. 
  • It retrieves data from web forms and connects them to the database. 
  • In the web application, JSP separates the business logic layer from the presentation layer. 
  • JSP uses the Java programming language. Hence, it also supports the multithreading concept of Java. 

Before we proceed to the JSP tutorial, we will guide you in setting up the JSP environment. Additionally, you require detailed knowledge about Java programming. Let us now know how to set-up the JSP environment on your desktop. 

How to set-up a JSP environment?

Why do you need to set-up the JSP environment? Is it necessary to fix the JSP environment on the desktop? If you desire to create dynamic web content or web applications using JSP, you must set-up the JSP environment. This environment enables developers to write the JSP programs, compile them, execute them on any platform. We will explain the JSP environment set-up in the steps below:

Java Development Kit Set-up

The first step is to fix the Java Development Kit (JDK) on your desktop. The Java Development Kit is necessary because we embed the java code in HTML code using JSP. Therefore, the JSP environment requires fixing the JDK environment first. 

Firstly, you have to download the Java Software Development Kit (SDK) from Oracle’s official website

After downloading, open the .exe file and install and configure it using the given guidelines. Later, you need to set two environment variables, PATH and JAVA_HOME. You have to set the PATH variable to the desktop’s location of java, i.e., java_install_dir/bin, and the JAVA_HOME variable to the location where there is javac, i.e., java_install_dir

If you have the Windows system and installed the SDK file at the C:\jdk1.5.0_20 location, add this path to the C:\autoexec.bat file. 

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

If you have installed the SDK file on the Windows NT, 2000, or XP system, there is a different way of setting PATH and JAVA_HOME environment variables. You have to right-click on My Computer, select Properties, ick on Advanced, and go to Environment Variables. Here, you have to set the PATH to the location of the java, i.e., C\jdk1.5.0_20\bin. After changing the PATH, click on the OK button. 

Now we shall know how to set PATH and JAVA_HOEM environment variables for UNIX systems, like Solaris, Linux, etc. Suppose we have installed the SDK file in /usr/local/jdk1.5.0_20. You have to add the below two commands in the .cshrc file. Consider that we utilize the C shell.

setnev PATH /usr/local/jdk1.5.0_20/bin:$PATH
setnev JAVA_HOME /usr/jdk1.5.0_20

If you use Integrated Development Environment (IDE) tools, like Eclipse, Sun ONE Studio, JBuilder, etc., take a sample java program, compile, and run it to check that your IDE tool knows where Java is installed on your system. 

After installing the Java Development Kit and setting PATH and JAVA_HOME environment variables, the next step is to set-up the web server. 

Setting the Tomcat Web Server

There are several web servers available today that support developing dynamic web applications through JSP or Servlets. We will use the Tomcat web server, which is open-source and free to use. Tomcat is a short name for Apache Tomcat. It is free to utilize by anyone and is compatible with several server technologies, like JavaServer Pages, Servlets, WebSocket, and Java Expression Language. The Java code in the Tomcat is run on the “pure Java” HTTP web server. 

There are several components in Apache Tomcat. Let us know each component and its use. 

  • The servlet container for Tomcat is Catalina, which utilizes Sun Microsystem’s specifications for JSP and servlets. The username, password, and roles of users are present in the Realm element. 
  • The connector component for Tomcat is Coyote, which is compatible with the HTTP 1.1 protocol. 
  • The JSP engine in Tomcat is Jasper. This engine parses the JSP text file and compiles it into the Java code. 
  • Another component of Tomcat is Cluster, which manages large web applications. 

Here are the steps to download the Apache Tomcat web server. 

  • Firstly, you have to download the Apache Tomcat from its official website

You must download the latest version of Apache Tomcat. 

  • After downloading the software, place the downloaded at a specific location. For example, if you installed Tomcat on the Windows system, locate the downloaded file in C:\apache-tomcat-5.5.29. For Linux or Unix systems, place the file in /usr/local/apache-tomcat-5.5.29
  • After locating the file, create the CATALINA_HOME environment variable. Set this variable to the location of the tomcat file, as mentioned above, i.e., for Windows systems, set the variable to C:\apache-tomcat-5.5.29, and for Linux systems, set the variable to /usr/local/apache-tomcat-5.5.29.

The Apache Tomcat set-up is done successfully. If you have installed Tomcat on the Windows system, follow any of the two commands for starting the Tomcat application. 

%CATALINA_HOME%\bin\startup.bat

or

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

If your Tomcat application is installed on the Linux system, you can type any of the below commands to start the Tomcat application. 

$CATALINA_HOME/bin/startup.sh

Or

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

Once you successfully open the Tomcat application, visit http://localhost:8080/. You will notice all the default applications present in Tomcat. You can carry out configuration and running the Tomcat application using the documentation available on Tomcat’s official website. 

Now, we shall see commands for shutting the Tomcat application on Windows and Linux systems. There are two commands for shutting down the Tomcat application on the Windows systems. They are as follows:

%CATALINA_HOME%\bin\shutdown

Or 

C:\apache-tomcat-5.5.29\bin\shutdown

For the Linus systems, you can follow any of the two commands for closing the Tomcat application. 

$CATALINA_HOME/bin/shutdown.sh

Or

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

CLASSPATH Set-up

We will discuss how to set-up the CLASSPATH for Windows and Linux systems. If you installed Tomcat on the Windows system, follow the below code lines for setting up the CLASSPATH.

set CLASSPATH = C:\apache-tomcat-5.5.29
set CLASSPATH = %CATALINA%\common\lib\jsp-api.jar;%CLASSPATH%

If your Windows system has NT, 2000, or XP versions, you need to right-click on My Computer, select Properties, click on Advanced, and go to Environment Variables. Here, you have to change the CLASSPATH value and click on the OK button. 

If you have installed Tomcat on the Linux system, add the following two lines in the .cshrc file. Consider that we use the C shell. 

setnev CATALINA = /usr/local/apache-tomcat-5.5.29
setnev CLASSPATH = $CATALINA/common/lib/jsp-api.jar:$CLASSPATH

How is the JSP’s Architecture?

We have set-up the environment for JSP. We have used Apache Tomcat for running JSP pages. For processing JSP pages, there is a JSP engine called a container.  In the Apache Tomcat, there is a built-in JSP engine called Jasper. Therefore, using Jasper, developers can create JSP pages. The container and the web server work together to provide the runtime environment or JSP and all other services required by JSP.

JSP

The above diagram illustrates the JSP container and JSP files’ position and in any web application. Now, we will explain the process of generating a dynamic webpage by the web server using JSP. 

  • Firstly, the client or the browser from Windows, Linux, or macOS system sends the HTTP request to the web server via the internet, as shown in the diagram above. 
  • The web server has the JSP engine in it, where all JSP files are stored. On receiving the HTTP request from the client, the web server identifies that the request is for the JSP page. After that, it transmits this request to the JSP engine. The web server transmits the HTTP request to the JSP page using a file having .jsp or .html extension or through an URL. 
  • Now, the JSP receives the HTTP request that was sent by the client to the web server. We know that the HTTP request was for a JSP page. Therefore, the engine loads that particular page from the disk and transforms it into a servlet content. In other words, all the template text is changed into println() statements. On the other hand, this transformation also converts all JSP pages into Java code. 
  • The requested JSP page is transformed into the servlet. Therefore, the servlet is compiled by the JSP engine into an executable class. Later, the HTTP request from the client is sent to the servlet engine by the JSP engine. 
  •  Both servlet and JSP engines are parts of the web server. The servlet engine executes the executable class compiled by the JSP engine and generates the HTML format output. There is another component on the web server, HTTP response. The servlet engine sends the HTML output to the HTTP response. 
  • Lastly, the web server sends the HTTP response to the browser via the internet in the form of static HTML content. 

Therefore, you can write the servlet using the JSP page with very few Java programming skills. From the above processing of JSP, we can conclude that it works the same as that of the servlet, except for the translation phase. It follows the 3-tier architecture, having the web server supporting the JSP page. Now, we shall move towards the JSP lifecycle. Here we will discuss how the JSP file passes through the different phases and how it is present in the web container. 

Life Cycle of JSP

The lifecycle of any component starts when it is created and ends when it gets destroyed. The life cycle of JSP is similar to the servlet’s life cycle. An additional phase in the JSP lifecycle is used for converting and compiling the JSP page into a servlet. The JSP lifecycle can be defined as creating the JSP page, transforming it into a servlet, lifecycle of the servlet, and destroying the JSP page. Let us now watch JSP’s life cycle in detail below. 

The JSP’s life cycle involves four primary paths as follows:

  1. Compilation
  2. Initialization
  3. Execution
  4. Cleanup

All these four JSP lifecycle paths are similar to servlet’s life cycle paths. The below diagram illustrates the above phases. 

JSP

Let us now discuss each phase of the JSP lifecycle and its description in detail. 

  1. JSP Compilation

When the client or browser sends the HTTP request for the JSP page, the JSP engine present in the web server verifies whether the request page has to be compiled or not. The JSP engine compiles the requested page if it was not previously compiled or it was not compiled after modifying the page. The page compilation involves three steps as follows:

  • The requested page is parsed by the JSP engine. 
  • It then transforms the JSP page into a servlet.
  • Lastly, the servlet gets compiled.

When the JSP page is transformed into a servlet, the .jsp file is converted into a .java file. At the time of compilation, the .java file is then converted into a .class file. 

  1. JSP Initialization

After the compilation is done, the classloading process takes place. The JSP source loads the servlet class, and this servlet class is then loaded into the container. The instance of the servlet class is created in the container. After the instance of the servlet class gets created, the jspInit() method gets invoked. This method is invoked only once in the JSP’s life cycle. For the JSP-specific initialization, you have to override the jspInit() method as follows:

public void jspInit()
{
//Initialization Code
}

When the jspInit() method is instantiated, you have to create the database connection and generate the lookup tables in the file. 

  1. JSP Execution

After the jspInit() method is instantiated, the _jspService() method is used. This method serves all the requests sent by the client to the web server until the JSP gets destroyed. 

The _jspService() method involves two different parameters, HttpServletRequest and HttpServletResponse. This method is defined as follows:

void  _jspService( HttpServletRequest request, HttpServletResponse response)
{
//service handling code
}

The _jspService() method responds to all the requests from the client. Whenever the client issues the request, the _jspService() method is invoked. It also responds to all seven HTTP requests, like GET, DELETE, POST, PUT, etc. You can override the _jspService() method. 

  1. JSP Cleanup:

The last stage of the JSP life cycle is Cleanup, where the JSP gets destroyed. The container removes JSP and does not use it. This method is the same as that of a servlet’s destroy method. When you require to close any files in the database or close the database connection, you can override the jspDestroy() method. The syntax of the jspDestroy() method is as follows:

public void jspDestroy()
{
//Cleanup code
}

Syntaxes in JSP

In this segment, we will learn several JSP elements’ syntax, like actions, directives, implicit objects, comments, expressions, etc. This section of the tutorial is very significant for the novice in the JSP domain. Following is a quick guide about JSP syntax. 

  1. Scriptlet:

The Scriptlet is one of the robust JSP elements. We can store Java statements, methods, variables, and expressions in the scriptlet. Additionally, it can also store elements of any scripting language. Below is the Scriptlet element’s Syntax:

Syntax:

<% code fragment%>

The above Scriptlet syntax can be written as an XML equivalent in the following format:

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

All HTML tags, JSP elements, and any other text is always written outside the Scriptlet tags. We will see a straightforward example of JSP inside the HTML page. 

Example:

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

The Tomcat server should be installed on your desktop, and its environment should be set-up for running this program. Follow the above Environment Set-up steps for setting up the Tomcat server environment. We will save the above file as firstjsp.jsp in the C:\apache-tomcat7.0.2\webapps\ROOT folder. After saving the file, go to the browser and type the URL, http://localhost:8080/firstjsp.jsp. The above code will display “JSP Quick Guide” and your system’s IP address. 

  1. Declarations

When you need variables or methods to use in the Java code, the JSP declarations declare them. Before you use any variable or method in the Java code, you must declare it using the JSP Declaration. The syntax of the JSP Declarations is as given below:

Syntax:

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

The above syntax is written in XML as follows:

<jsp: declaration>
Code fragment
</jsp:declaration>

Now, let us see an example of the JSP declarations. 

Example:

<%! int j=0; %>
<%! int x, y, z; %>
<%! Circle x = new Circle(2.0); %>
  1. Expression

An expression in JSP contains expressions of scripting language. These expressions can be evaluated, transformed into a String, and added to the JSP file, where the expression appears. You can use JSP expressions with the text, as it can be transformed into the String. It is not mandatory to tag JSP expressions inside HTML tags. One important thing to remember while writing the JSP expression is that they do not use the semicolon to end the expression. 

Syntax:

<%= expression %>

The above syntax can be written into its XML equivalent as follows:

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

The following example will help you to acknowledge how to use the JSP expression in HTML. 

<html>
<head><title>Software Test and Tricks</title></head>
<body>
<p>Today's Date : <%= (new java.util.Date()).toLocaleString() %></p>
</body>
</html>

You will get the output as the current date and time as follows:

Today's Date : 24-Nov-2020 03:25:34
  1. Comments

Comments are statements that are not for the execution. They are meant only for programmers and readers. In JSP, comments are ignored by the container. If you wish to hide some part of the JSP program, you can comment that part using JSP comments. The following is the syntax for JSP comments. 

Syntax:

<%-- Software Tips and Tricks --%>

We will execute the below example that contains the JSP comment in it. 

Example:

<html>
<head><title>Software Tricks and Tips></title></head>
<body>
<h2>JSP Tutorial></h2>
<%-- JSP comment --%>
</body>
</html>

The result of this code is given below.

JSP Tutorial

There are many other ways in JSP for specifying comments. Below are six different comment syntaxes and their uses:

  • <!– comment >

The above is referred to as an HTML comment and the browser ignores the characters or words written inside the comment. 

  • %\>

<%\> implies a static literal. 

  • <\%

The above comment also refers to as a static literal. 

  • \” 

It specifies a double quote used in an attribute. 

  • \’

It specifies a single quote used in an attribute.

  1. Directives

There are three directives in JSP, <%@page… %>, <%@include… %>, and <%@taglib… %>. The <%@page… %> directive is used for defining page attributes, like error page, scripting language, and buffering requirements. The other directive, <%@include… %>, includes a specific file used during the translation phase of the JSP life cycle. Lastly, the <%@taglib… %> directive is used for declaring tab library and custom actions required in the JSP page. When JSP directives are used, they affect the servlet class’s structure. Here is the syntax for the JSP directive. 

<%@ directive attribute="value" %>
  1. Actions

Actions are functions that are defined already. JSP actions are used for controlling the servlet engine’s behavior. These actions add the construct in the XML code. Using JSP actions, you can insert any file dynamically, create the HTML for the Java plugin, or reuse the JavaBeans components. Below is the syntax of JSP actions. 

Syntax:

<jsp:action_name attribute = "value" />

We are listing some significant JSP actions and their description below:

  • jsp:useBean: This action instantiates or identifies a JavaBean. 
  • jsp:getProperty: You can use the jsp:getProperty action for adding the JavaBean property into the output. 
  • jsp:setProperty: This action fixes the JavaBean property. 
  • jsp:include: When the user requests the page, this action adds the file. 
  • jsp:plugin: It creates an OBJECT or EMBED tag and browser-specific code for the Java Plugin. 
  • jsp:attribute: This action is used for defining the XML element’s attribute that is dynamically-defined. 
  • jsp:forward: This action takes the user to the new page. 
  • jsp:element: When you need to define XML elements dynamically, use this action. 
  • jsp:text: This action enables users to add the template text to the JSP page. 
  • jsp:body: It is used for defining the XML element’s body, which is defined dynamically. 
  1. Implicit Objects

There are nine implicit objects in JSP, request, response, session, out, pageContext, config, application, page, and exception. Let us know about each implicit object in detail here. 

  • request: The request object is HttpServletRequest, associated with the client’s request. 
  • response: The response object is HttpServletResponse, associated with the server’s response to the client. 
  • session: This object involves HttpSession and is associated with the client’s request object. 
  • out: Another implicit object is out. It is used for sending the output to the client using the PrintWriter object. 
  • pageContext: This implicit object specifies the application of server-specific features. One example of the server-specific feature is JspWriters. 
  • config: This object involves the ServletConfig object, which is used with the JSP page. 
  • application: The ServletContext object of JSP is used with the application context. 
  • page: The page implicit object calls all methods, which are defined by the servlet class. 
  • Exception: The designated JSP can access the exception data using the Exception object. 
  1. Control-Flow Statements

JSP also uses control-flow statements, decision-making statements, and loops. Here we shall see how the decision-making statement and loops are used in JSP programming. 

Decision-Making Statements

Decision-making statements are used for deciding on the available choices. There are two ways of implementing a decision-making statement. One is using the if_else statement, and another is using the switch-case statement. Each if and else condition is enclosed in separate scriptlets. Let us observe an example of an if_else statement in JSP. 

Example:

<%! int month = 3; %>
<html>
  <head><title>IF...ELSE Example</title></head>
 
  <body>
      <% if (month == 1 || month == 7) { %>
        <p>Enjoy Holidays.</p>
      <% } else { %>
        <p> This is not the time to enjoy.</p>
      <% } %>
  </body>
</html> 

Here, we have declared ‘month=3’ and specified the conditions in the if_else statements. Therefore the output will be:

This is not the time to enjoy.

Now, we will implement the switch…case statements. The below code is quite different from the above code, as the conditions in the below code are specified in one Scriptlet. 

Example:

<%! int month = 5; %>
<html>
  <head><title>SWITCH...CASE Example</title></head>
 
  <body>
      <%
        switch(month) {
            case 0:
              out.println("It's January.");
              break;
            case 1:
              out.println("It's February.");
              break;
            case 2:
              out.println("It's March.");
              break;
            case 3:
              out.println("It's April.");
              break;
            case 4:
              out.println("It's May.");
              break;
            case 5:
              out.println("It's June.");
              break;
            default:
              out.println("It's July.");
        }
      %>
  </body>
</html> 

Output:

June

Loop Statements

We use the loop in the program for repeating a particular instruction a specific number of times. There are three different types of loops supported by JSP, for, while, and do…while. Let us see examples of each loop type below.

For Loop: 

<%! int fontSize; %>
<html>
  <head><title>FOR LOOP Example</title></head>
 
  <body>
      <%for ( fontSize = 3; fontSize <= 4; fontSize++){ %>
        <font color = "Red" size = "<%= fontSize %>">
            Software Tips and Tricks
      </font><br />
      <%}%>
  </body>
</html> 

Output:

Software Tips and Tricks

Software Tips and Tricks

Software Tips and Tricks


While Loop:

<%! int fontSize; %>
<html>
  <head><title>WHILE LOOP Example</title></head>
 
  <body>
      <%while ( fontSize <= 4){ %>
        <font color = "Red" size = "<%= fontSize %>">
            Software Tips and Tricks
        </font><br />
        <%fontSize++;%>
      <%}%>
  </body>
</html> 

Output:

Software Tips and Tricks

Software Tips and Tricks

Software Tips and Tricks

Software Tips and Tricks

  1. Operators in JSP

All logical and arithmetic operators supported by Java are used in JSP. Operators are used in JSP expressions for evaluating them. The operator having the highest precedence is evaluated first, and with the lowest precedence is evaluated at last. We have listed all JSP operators with the highest precedence first, second highest precedence the next, and so on. 

  • Postfix: There are three postfix operators ‘()’. ‘[]’, and ‘.’. All these operators have left to right associativity. 
  • Unary: Unary operators are ‘++’, ‘–’, ‘!’, and ‘~’ having the right to left associativity. 
  • Multiplicative: There are three multiplicative operators, ‘*’, ‘/’, and ‘%’. They have left to right associativity. 
  • Additive: Additive operators are ‘+’ and ‘-’. They also have left to right associativity. 
  • Shift: Shift operators, ‘>>’, ‘>>>’, and ‘<<’ have left to right associativity. 
  • Relational: There are four relational operators, ‘>’, ‘<’, ‘>=’, and ‘<=’. All of them have left to right associativity. 
  • Equality: Equality operators are ‘==’ and ‘!=’ having left to right associativity. 
  • Bitwise AND: The bitwise AND operator (&) has left to right associativity. 
  • Bitwise XOR: The bitwise XOR operator (^) has left to right associativity.
  • Bitwise OR: The bitwise OR operator (|) has left to right associativity.
  • Logical AND: The logical AND operator (&&) has left to right associativity.
  • Logical OR: The logical OR operator (||) has left to right associativity. 
  • Conditional: The conditional operator (?:) has the right to left associativity. 
  • Assignment: There are several assignment operators, like =, +=, -+, *=, %=, /=, >>=, <<=, &=, ^=, and |=. All these operators have the right to left associativity. 
  • Comma: The comma operator (‘) has left to right associativity. 

JSP supports five different literals or data types, Boolean, integer, floating-point, String, and NULL. The Boolean literal returns either true or false as a result. An integer is used for specifying the number, and the Floating-point is used for declaring the decimal numbers in the JSP program. The String data type in JSP is different from that of the Java language. The NULL data type specifies the null value. 

JSP Actions

We have seen what the JSP actions are. We have also seen all JSP actions in the brief above. Actions are nothing but functions that regulate the JSP engine’s behavior. Let us recall the syntax of the JSP action. 

Syntax:

<jsp:action_name attribute = "value" />

The JSP actions are jsp:include, jsp:useBean, jsp:setProperty, jsp:getProperty, jsp:forward, jsp:element, jsp:plugin, jsp:attribute, jsp:body, and jsp:text. All these JSP actions have two common components, ID and Scope. 

The ID component is used for uniquely identifying any JSP action. This component of the JSP action is used in the JSP program, defining the action to be performed. Another element is Scope, which is used for identifying the JSP action’s life cycle. Using the action’s ID, its lifespan is determined. Therefore, the ID element and the Scope element are directly proportional. The Scope component may take the possible values: page, session, request, or applications. 

The <jsp:useBean> Action

The useBean action in JSP first finds an object possessing the ID and Scope attributes. If the object is not found, this action creates the object for that specific ID and Scope attributes. The following is the way to load the useBean class.

<jsp:useBean is = "name" class = "package.class" />

After loading the Bean class, you can use the other two JSP actions, jsp:setProperty and jsp:getProperty. These actions are used for modifying and fetching the bean properties. The useBean action uses three different attributes, class, type, and beanName. The class attribute assigns the bean’s package name. You can use the type element for specifying the variable type for the object that we refer to. Lastly, the beanName provides the name of the bean. The instantiate() method specifies the bean name. 

The <jsp:setproperty> Action

The <jsp:setproperty> action is used for setting the Bean’s property. The only requirement for setting the bean’s property is the bean must be first defined. There are two ways for using the <jsp:setProperty> action as follows:

The first way is using the <jsp:setProperty> outside and after the <jsp:useBean> component. 

<jsp:useBean is = "myName" ...>
...
<jsp:setProperty name = "myName" property = "someProperty" .../>

In the above syntax, even if the new <jsp:useBean> element is not instantiated or an existing <jsp:useBean> is not found, the <jsp:setProperty> action is executed. 

Another way of defining the <jsp:setProperty> action is inside the jsp:useBean component. 

<jsp:useBean is = "myName" .../>
...
<jsp:setProperty name = "myName" property = "somePropoerty" .../>
</jsp:useBean>

Unlike the first way of using the <jsp:setProperty>, the second way executes <jsp:setProperty> only if an existing <jsp:useBean> is found or the new one is instantiated.

The jsp:setProperty involves four different attributes, name, property, value, and param. The name attribute assigns the name to the bean of which the property is to be set. Another attribute, property, defines the property. The value is the value assigned to the property, and the param attribute defines the name of the parameter received by the property. 

The <jsp:getProperty> Action

We have seen that the jsp:setProperty action sets the property’s value. Here, the <jsp:getProperty> action fetches the property’s value. After fetching the value, it transforms it into the String and adds it to the result. 

The <jsp:getProperty> action has only two attributes, name and property. The name attribute defines the bean name holding a particular property, and the property attribute defines the name of the Bean’s property. The below is the syntax of the <jsp:getProperty> action: 

<jsp:useBean is = "myName" .../>
...
<jsp:getProperty name = "myName"  property = "someProperty" .../>

Let us observe one example that contains the example bean. Save the below file as ExampleBean.java.

package action;

public class ExampleBean {
  private String msg = "There is no message here!";

  public String getMsg() {
      return(msg);
  }
  public void setMsg(String msg) {
      this.msg = msg;
  }
}

After writing this code in the ExampleBean.java file, compile it to generate the ExampleBean.class file. Now, copy the ExampleBean.class file to the C:\apache-tomcat-7.0.2\webapps\WEB-INF\classes\action folder. Make sure you have also set the CLASSPATH variable. 

You have to now create the main.jsp file and write the below code into it. 

<html>
 
  <head>
      <title>setProperty and getProperty Actions in JSP</title>
  </head>
 
  <body>
      <center>
        <h2>setProperty and getProperty Actions in JSP</h2>
        <jsp:useBean id = "example" class = "action.ExampleBean" />
        <jsp:setProperty name = "example"  property = "msg"
            value = "Welcome to Software Tips and Tricks..." />
           
        <p>The Message is....</p>
        <jsp:getProperty name = "example" property = "msg" />
      </center>
  </body>
</html>

Output:

setProperty and getProperty Actions in JSP


The Message is....
Welcome to Software Tips and Tricks...

The <jsp:plugin> Action

When you want to insert Java elements into the JSP program, the <jsp:plugin> action is used. This action also identifies the browser type and adds <object> or <embed> tags into the JSP program. Suppose you require the Java component, whose plugin is not available. The <jsp:plugin> action downloads the plugin required to execute the Java component, like Applet or Bean. There are multiple attributes in the plugin action, which corresponds to the HTML tags. 

Below is one straightforward example of the <jsp:plugin> action. 

<jsp:plugin type = "applet" codebase = "dirname" code = "MyApplet.class"
  width = "50" height = "70">
  <jsp:param name = "fontcolor" value = "green" />
  <jsp:param name = "background" value = "red" />

  <jsp:fallback>
      Unable to initialize Java Plugin
  </jsp:fallback>

</jsp:plugin>

In the above code, we can observe the new element, <fallback>. When the component fails, this element sends the error string to the user. 

The actions, like <jsp:element>, <jsp:attribute>, and <jsp:body> defines XML elements. All the XML elements are generated at the run time and not at the compile time, i.e., they are generated dynamically. 

The <jsp:forward> Action

When you want to terminate the action of the current page and forward it to the other resource, you can use the <jsp:forward> action. The syntax of this action is given as follows:

<jsp:forward page ="Relative URL" />

Only one attribute is associated with the <jsp:forward> action, the page. This page must include the relative URL of the resource, where the action is transferred. The resource can be the JSP page, Java Servlet, and the static page. 

Now, we shall see one simple example of the <jsp:forward> action. We will create two files, date.jsp and main.jsp. The date.jsp file will display the current date and the main.jsp file contains the <jsp:forward> action. 

date.jsp file

<p>Today's Date: <%= (new java.util.Date()).toLocaleString() %></p>

main.jsp file

<html>
  <head>
      <title>The Forward Action Example</title>
  </head>
 
  <body>
      <center>
        <h2>The Forward action Example</h2>
        <jsp:forward page = "date.jsp" />
      </center>
  </body>
</html>

You must save both the files in the ROOT directory. We will now access the main.jsp file for the result. It will not display the content from the main.jsp file; instead, it will display the content from the date.jsp file, as it is a forwarded file. 

Output:

Today's Date: 25-Nov-2020 12:51:34

The <jsp:text> Action

Using the <jsp:text> action, we can write text templates or documents in JSP pages. Below is the syntax of the <jsp:text> action:

<jsp:text>Template data</jsp:text>

Here, the template only contains text and EL expressions. No other elements can be present in the template. In the XML files, do not use the expression as ${whatever > 0}, as this sign is not allowed or illegal. Instead, you can use ${whatever gt 0}

JSP Directives

In the syntax section, we have seen what directories in JSP are. Here, we will learn JSP directories in detail. Directives are essential in JSP, as they command and direct the JSP container for handling and regulating specific JSP processing elements. The entire structure of the servlet class gets affected because of JSP directives.

Syntax:

<%@ directive attribute = "value" %>

The attributes in the directives are of the key-value form. There can be several attributes in directives, and each is separated by a comma. In the above syntax, we can observe a space between ‘<%@’ and the directive name, and the value and ‘%>.’ These spaces are optional. There is no worry if you do not add spaces between them. We have seen above that there are three directive tags, <%@ page… %>, <%@ include… %>, and <%@ taglib… %>. Let us discuss each of these directive tags in detail. 

The Page Directive

The Page directive provides instructions to the current page of the container. You can include the page directive anywhere in your JSP program. Generally, the page directive is used at the top of the JSP page. The syntax of the page directive is:

<%@ page attribute = "value" %>

The above syntax is written in XML as given below:

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

There are 13 attributes associated with the page directive, as explained below.

  • autoFlush: This attribute regulates the servlet output buffer’s behavior. 
  • errorPage: errorPage displays the URL of the other JSP, which throws Java unchecked runtime exceptions. 
  • extends: The generated servlet should extend the specified superclass. 
  • buffer: The buffer attribute defines the output stream’s buffering model.
  • contentType: This attribute defines the scheme for character encoding. 
  • isErrorPage: It suggests whether the current JSP page is the URL defined by the errorPage attribute of the other JSP page. 
  • info:  It specifies a String, which can be accessed by the getServletInfo() method. 
  • language: This attribute indicates the programming language used in JSP pages. 
  • isELIgnored: It specifies if the EL expression in the JSP page will be ignored. 
  • import: This statement indicates all packages and classes required to add in the JSP. In Java, the Java import statement specifies all classes and packages required to include in the Java program. 
  • isThreadSafe: This attribute specifies the servlet’s threading model. 
  • session: The session attribute verifies whether the JSP page takes part in the HTTP session or not. 
  • isScriptingEnabled: This element specifies whether to use the scripting elements in the JSP page. 

The Include Directive

During the translation phase, the include directive is used to include the file in the JSP page. This directive is also to direct the container about combining all external files with the JSP page. As the page directive is included only at the top of the JSP page, the include directive can be used anywhere on the page. 

Syntax:

<%@ include file = 'relative url" />

The above syntax is written in XML as follows:

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

Here, the filename is the relative url. If you do not define the file’s path, the compiler assumes that your file is present at the JSP’s location. 

The taglib Directory

The last directory type is taglib. This directory provides a lot of information about the JSP page, like the set of custom tags used, the library’s location, and finding the custom tags from the JSP page. Below is the syntax of the taglib directory. 

<%@ taglib uri = "uri" prefix = "prefixOfTag" >

The above syntax can be written in XML as follows:

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

The attribute, uri, specifies the location that the container can understand, and the prefix attribute tells the container about the composition of the custom actions. 

JSP Implicit Objects

JSP implicit objects are Java objects. The JSP container allows developers to use these implicit objects in every JSP page without being declared explicitly. These objects are also referred to as predefined variables. There are nine different implicit objects: request, response, out, session, application, page, pageContext, config, and exception. 

The request Object

The javax.servlet.http.HttpServletRequest object creates an instance called the request object. When a client or user requests a particular page, the JSP engine generates a new object representing the client’s request. The request object offers several methods for extracting the HTTP header’s information, like HTTP methods, cookies, etc. 

The response Object

The javax.servlet.http.HttpServletResponse object creates an instance called the response object. As the JSP engine creates the new object whenever the user requests a particular page, it also creates an object representing its response. Using the response object, you can include new cookies to the JSP program, like HTTP status codes, stamps, etc. 

The out Object

The javax.servlet.jsp.JspWriter object creates an instance called the out object. The JSP engine can add content to the response requested by the client. The JspWriter object has almost the same methods present in the java.io.PrintWriter class. There are some additional methods in the JspWriter object used for buffering and throws IOException. 

The application Object

The javax.servlet.ServletContext creates an instance called an application object, which acts as a wrapper for the ServletContext object. This object represents the JSP page. When the JSP page is initialized, an application object is created. This object gets removed, as the JSP page is destroyed using the jspDestroy() method. 

The session Object

The javax.servlet.http.HttpSession creates an instance called the session object. This object works similarly as it works in Java Servlets. The primary objective of the session object is to track the session between client requests. 

The exception Object

A wrapper containing the exception from the previous JSP page is called an exception object. When an error condition occurs, an exception object is used for handling it. 

The page Object

The page object provides the reference to the instance of the page. It represents the entire JSP page. The ‘this’ object and the page object are synonyms for each other.

The pageContext Object

The javax.servlet.jsp.PageContext creates an instance called pageContext object. Like the page object, the pageContext object also represents the complete JSP page. Using the pageContext object’s attributes, we can derive other implicit objects, like application, config, session, and out. This object also stores information, like page scope, errorPageURL, and buffering information. There are 40 methods supported by the pageContext object. 

The config Object

The javax.servlet.ServletConfig creates an instance called the config object. This object acts as the wrapper for the ServletConfig object. Users can use this object for accessing the initialization parameters of the servlet or JSP engine. The below method is the one that is used in the JSP page using the config object. 

config.getServletName();

JSP Client Request

The web server gets a lot of information when the browser or the client requests a particular web page. This information cannot be used directly, as it travels through the HTTP request’s header. The HTTP header contains several elements that store the information when the browser requests the web page. These elements are accept, accept-charset, accept-encoding, accept-language, connection, authorization, cookie, content-length, if-modified-since, host, referrer, if-unmodified-since, and user-agent. 

The HTTPServletRequest Object

The javax.servlet.http.HttpServletRequest object creates an instance called the request object. Whenever any user requests a particular page, the JSP engine generates the new object. The request object’s primary objective is to retrieve the HTTP information, like data, HTTP methods, cookies, etc. Below are some methods that read the HTTP header information from the JSP program. 

  • Enumeration getAttributeNames(): This method results in the Enumeration, which contains attribute names available for this request. 
  • Cookie[] getCookies(): When the client sends the request, it contains cookie objects. Therefore, this method produces an array, which holds all these cookie objects. 
  • Enumeration getParameterNames(): This method results in the enumeration of String objects. This enumeration holds the parameter names present in the request.
  • Enumeration getHeaderNames(): It produces an enumeration holding the header names present in this request. 
  • HttpSession getSession(boolean create): The HttpSession getSession(boolean create) method results in the current HttpSession related with this request. If there is no session present at that moment and the boolean for create is true, this method results in a new session. 
  • HttpSession getSession(): This method returns the current session related to the request. If the session is not available, this method creates a new one and returns it. 
  • Object getAttribute(String name): It produces the value of the attribute that has the name as an object. If there is no name for the attribute, it returns NULL. 
  • Locale getLocale(): It gives back the Locale, where the client will accept the content. 
  • String getAuthType(): This method specifies the authentication scheme name used to conserve the servlet. If the JSP is not conserved, it returns NULL. 
  • ServletInputStream getInputStream(): The ServletInputStream fetches the request’s body in the binary form. 
  • String getContent Type(): This method gives back the MIME type of the request’s body. If the type is not known, it returns NULL. 
  • String getCharacterEncoding(): The character encoding name present in the request’s body is produced by this method. 
  • String getHeader(String name): It returns the request header’s value in the String format. 
  • String getContextPath(): It produces the URI’s portion of the request. 
  • String getParameter(String name): This method results in the request parameter’s value in the String form. If the parameter of the request does not exist, it returns NULL.
  • String getMethod(): The String getMethod() method produces the HTTP request’s name, which was used with the current request. 
  • String getProtocol(): Requests in JSP use certain protocols. This method returns the protocol’s name and version. 
  • String getPathInfo(): When the client makes the request, it sends the URL. The String getPathInfo() method returns extra information about the path related to the URL. 
  • String getRemoteAddr(): This method results in the Internet Protocol (IP) address of the client’s system. 
  • String getRemoteUser(): It produces the login of the authenticated client making the request. If the user is not authenticated, it returns NULL.
  • String getRemoteHost(): If the client’s name making the request is to be retrieved, the String getRemoteHost() method can be used. 
  • String getRequestedSessionId(): This method gives back the session ID, which is defined by the client. 
  • String getRequestURI(): It returns the request’s URL from the protocol name. 
  • String[] getParameterValues(String name): This method gives back an array containing String objects. These objects hold values of all parameters present in the request. 
  • String getServletPath(): It also returns the request’s URL. 
  • int getContentLength(): It returns the length of the request’s body in bytes. 
  • boolean isSecure(): It gives back the boolean value specifying whether the request is made through a secure channel or not. 
  • int getServletPort(): This method gives the port number of the request. 
  • int getIntHeader(String name): This method results in the value of the request header in the integer format. 

The HTTP Header Request Example

Here, we will see one straightforward example of the HTTP Header Request. In the HTTP header request’s example, we will apply the getHeaderName() method for reading the HTTP header information. It produces an enumeration containing the HTTP header information of the request. The hasmoreElements() method determines when the nextElement() method should stop.

Example:

<%@ page import = "java.io.*,java.util.*" %>

<html>
  <head>
      <title>Example of the HTTP Header Request</title>
  </head>

  <body>
      <center>
        <h2>Example of the HTTP Header Request</h2>
       
        <table width = "100%" border = "1" align = "center">
            <tr bgcolor = "#949494">
              <th>Header Name</th>
              <th>Header Value(s)</th>
            </tr>
            <%
              Enumeration headerNames = request.getHeaderNames();
              while(headerNames.hasMoreElements()) {
                  String paramName = (String)headerNames.nextElement();
                  out.print("<tr><td>" + paramName + "</td>\n");
                  String paramValue = request.getHeader(paramName);
                  out.println("<td> " + paramValue + "</td></tr>\n");
              }
            %>
        </table>
      </center>
 
  </body>
</html>

Write the above code in the main.jsp file and access it for reading the HTTP request header’s information. It will give you all information about the HTTP request header, like host, connection, cache-control, user-agent, accept, accept-language, and accept-encoding. 

JSP Server Response

When the client or browser requests the web page, the web server responds to the HTTP request called a response. This response includes a blank line, document, the status line, and some response header. The HTTP response looks as follows:

HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
  (Blank Line)
<!doctype ...>

<html>
  <head>...</head>
  <body>
      ...
  </body>
</html>

In the above code, the HTTP version is HTTP/1.1, 200 is the status code, and OK is the message to the status code. There are multiple response headers, having the HTTP/1.1 version sent by the web server to the browser. These response headers are cache-control, allow, content-disposition, connection, content-length, content-encoding, content-language, expires, content-type, location, last-modified, set-cookie, refresh, and retry-after.  

The HttpServletResponse Object

The javax.servlet.http.HttpServletResponse creates an instance called the response object. This object is created by the web server, which represents the response sent to the client. The response object is also associated with the interfaces required for HTTP headers creation. Programmers can add new cookies, HTTP status codes, and date stamps in the JSP program. The following are some methods or functions used for adding the HTTP response header in the servlet program. 

  • String encodeURL(String url): This method is used for encoding a particular URL that includes the session ID. If the encoding is required, this method sends the URL without changing. 
  • String encodeRedirectURL(String url): The URL included in the sendRedirect function is encoded. If the encoding is not required, the URL remains unchanged.
  • boolean isCommitted(): This function results in the boolean value, specifying whether the response has been committed. 
  • boolean containsHeader(String name): It also results in the boolean value specifying whether the response header having the name has been set. 
  • void addHeader(String name, String value): This function includes a response header with its name and value. 
  • void addDateHeader(String name, long date): It also includes a new response header with its name and date. 
  • void flushBuffer(): This function forcefully writes the content present in the buffer to the client. 
  • void addIntHeader(String name, int value): This function includes a new response header with its name and an integer value. 
  • void resetBuffer(): It removes or clears all the content from the underlying buffer but does not clear headers and status codes. 
  • void reset(): This function removes or deletes all the data present in the buffer, along with the status code and headers. 
  • void sendError(int sc, String msg): It results in the error message having a particular status and is sent to the client. 
  • void sendError(int sc): This function also transmits the error message to the client with the specific status code by deleting the data from the buffer. 
  • void setBufferSize(int size): This function fixes the buffer size for the response body. 
  • void setIntHeader(String name, int value): This function sets the response header with its name and the specific integer value. 

The HTTP Header Response Example

Here is an example of the HTTP header response, which uses the setIntHeader() function for setting the Refresh header. 

Example:

<%@ page import = "java.io.*,java.util.*" %>

<html>
 
  <head>
      <title>HTTP Header Response Example</title>
  </head>
 
  <body>
      <center>
        <h2>HTTP Header Response Example</h2>
        <%
            // Set refresh, autoload time as 4 seconds
            response.setIntHeader("Refresh", 4);
           
            // Get current time
            Calendar calendar = new GregorianCalendar();
           
            String am_pm;
            int hour = calendar.get(Calendar.HOUR);
            int minute = calendar.get(Calendar.MINUTE);
            int second = calendar.get(Calendar.SECOND);
           
            if(calendar.get(Calendar.AM_PM) == 0)
              am_pm = "AM";
            else
              am_pm = "PM";
              String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
              out.println("The Current Time is: " + CT + "\n");
        %>
      </center>
 
  </body>
</html>

Save the above code with the filename, main.jsp. After every 4 seconds, the current time of the system gets displayed, as shown below. 

Output:

HTTP Header Response Example
The Current Time is: 08:28:30 PM

HTTP Status Code in JSP

The HTTP Request and HTTP Response have the same structure as follows:

  • Firstly, it includes the status line, Carriage Return (CRLF), and Line Feed. Line Feed implies a new line. 
  • The next is zero or more header lines and Carriage Return (CRLF). 
  • Then comes a blank line, CRLF.
  • Lastly, the message body is optional. The message body may contain the query output, query data, or file. 

In the above section, we have seen how the response header looks like. 

The web server returns some HTTP codes and their respective messages to the client. These HTTP status codes and their messages are described in the following section. 

CodeMessage
100Continue
101Switching Protocols
200OK
201Created
202Accepted
203Non-Authoritative Information
204No Content
205Reset Content
206Partial Content
300Multiple Choices
301Moves Permanently
302Found
303See Other
304Not Modified
305Use Proxy
306Unused
307Temporary Redirect
400Bad Request
401Unauthorized
402Payment Required
403Forbidden
404Not Found
405Method Not Allowed
406Not Acceptable
407Proxy Authentication Required
408Request Timeout
409Conflict
410Gone
411Length Required
412Precondition Failed
413Request Entity Too Large
414Request-url Too Long
415Unsupported Media Type
417Expectation Failed
500Internal Server Error
501Not Implemented
502Bad Gateway
503Service Unavailable
504Gateway Timeout
505HTTP Version Not Supported

The three different methods are used to set the HTTP status code as given below:

  1. public void setStatus(int statusCode): It sets the status code, which uses the integer value for the status code as an argument. 
  2. public void sendRedirect(String url): This function creates a response having the 302 code. It also generates a Location header, which specifies the URL of the new document. 
  3. public void sendError(int code, String message): This function transmits the 404 HTTP status code to the browser with a short message. 

We shall see one straightforward example, which will display the 407 error status code to the client. 

Example:

<html>
  <head>
      <title>"Need Authentication" HTTP Status Code</title>
  </head>
 
  <body>
      <%
        // Set error code and reason.
        response.sendError(407, "Need authentication!!!" );
      %>
  </body>
</html>

The above code will display the 407 HTTP Status Code with the Need Authentication message. 

Form Processing in JSP

Many times, we need to transmit the data from the browser to the web server and finally to the program. There are two methods, GET and POST used by the browser to transmit this data to the web server. The four methods are used for reading the data using JSP, getParameter(), getParameterValues(), getParameterNames(), and getInputStream()

The GET Method

The GET method is used for transmitting the encoded user information and appending it to the page request. The encoded user information and the page request is separated by the ‘?’ symbol. This method is the default for transmitting the user information to the web server from the browser. It returns the String that will be present in the Location:box of the Browser. If you have confidential data, like passwords, do not use the GET method. 

Example of the GET method using URL

Let us create the URL that will pass two different values to the GetURLForm program using the GET method. 

http://localhost:8080/main.jsp?first_name=JOHN&last_name=Williams

We will write the below code in the main.jsp file. We have used the getParameter() methods for reading the data using JSP.

Example:

<html>
  <head>
      <title>GET Method using URL</title>
  </head>
 
  <body>
      <h1>GET Method using URL</h1>
      <ul>
        <li><p><b>First Name:</b>
            <%= request.getParameter("first_name")%>
        </p></li>
        <li><p><b>Last  Name:</b>
            <%= request.getParameter("last_name")%>
        </p></li>
      </ul>
 
  </body>
</html>

After writing this code in the main.jsp, got to the browser’s Location:box and type the below URL:

http://localhost:8080/main.jsp?first_name=JOHN&last_name=Williams

Output:

GET Method using URL
First Name: John
Last Name: Williams

Example of the GET method using Form

In the following example, we will pass the two values, first_name and last_name using the HTML form. We will write the below code in the main.jsp file.

Example:

<html>
  <body>
     
      <form action = "main.jsp" method = "GET">
        First Name: <input type = "text" name = "first_name">
        <br />
        Last Name: <input type = "text" name = "last_name" />
        <input type = "submit" value = "Submit" />
      </form>
     
  </body>
</html>

This is the HTML file. Save it in a GetForm.htm file and place it in the <Tomcat-installation-directory>/webapps/ROOTS directory. When you want to display the output of the above code, type the below URL in your browser.

http://localhost:8080/GetForm.htm

Output:

wRlmGvIrbQFh9mMPxPOpDCQgR2LlYWpBTpnD5VWCyOxU8kW1lS3QJnFS nywH IPw9i56 Iqm3pzyTv1QagmUhraDW3kgBWqySHgsIINlvCZEDzjTp5AgnJtEeRhNxfW zcasCE1

The POST Method

Another method for transmitting the information to the program is the POST method. This method is more reliable than the GET method. It holds the information the same way as that of the GET method. The only difference is the GET method passes the information in the String after the ‘?’ symbol in the URL, and the POST method passes it as an individual message. 

Example of the POST method using Form

The below code contains both GET and POST methods. We will write the below code in the main.jsp file. 

main.jsp

<html>
  <head>
      <title>GET and POST Methods</title>
  </head>
 
  <body>
      <center>
      <h1>POST Method for reading the Form Data</h1>
     
      <ul>
        <li><p><b>First Name:</b>
            <%= request.getParameter("first_name")%>
        </p></li>
        <li><p><b>Last  Name:</b>
            <%= request.getParameter("last_name")%>
        </p></li>
      </ul>
 
  </body>
</html>

Now, write the below program in the PostForm.htm file. 

PostForm.htm

<html>
  <body>
     
      <form action = "main.jsp" method = "POST">
        First Name: <input type = "text" name = "first_name">
        <br />
        Last Name: <input type = "text" name = "last_name" />
        <input type = "submit" value = "Submit" />
      </form>
     
  </body>
</html>

Place both the files, main.jsp and PostForm.htm in the <Tomcat-installation-directory>/webapps/ROOTS directory. When you require to observe the output, type the below URL in the browser:

http://localhost:8080/PostFrom.htm

Output:

JSP

When you enter the first_name and the last_name and click on the Submit button, you will see the result. 

Using Checkbox in the JSP Program

Many times, we need to select multiple options from the available ones. When multiple options are to be selected, you have to use checkboxes. Let us see one straightforward example of using checkboxes in the JSP program. Below is the HTML code and write it in the file, CheckExample.htm. 

CheckExample.htm

<html>
  <body>
     
      <form action = "main.jsp" method = "POST" target = "_blank">
        <input type = "checkbox" name = "C++" checked = "checked" /> C++
        <input type = "checkbox" name = "C"  /> C
        <input type = "checkbox" name = "Java" checked = "checked" /> Java
        <input type = "submit" value = "Select Subject" />
      </form>
     
  </body>
</html>

The above code will generate three checkboxes, with two checkboxes active. Now, we will write the main.jsp file and access it for reading the checkbox data.

main.jsp

<html>
  <head>
      <title>Checkbox Using JSP</title>
  </head>
 
  <body>
      <h1>Checkbox Using JSP</h1>
     
      <ul>
        <li><p><b>C++ Flag:</b>
            <%= request.getParameter("C++")%>
        </p></li>
        <li><p><b>C Flag:</b>
            <%= request.getParameter("C")%>
        </p></li>
        <li><p><b>Java Flag:</b>
            <%= request.getParameter("Java")%>
        </p></li>
      </ul>
 
  </body>
</html>

Output:

Checkbox Using JSP
C++ Flag : on
C Flag : null
Java Flag : on

Cookies Handling

What are cookies? Cookies are the text files present in the client’s desktop and are used for tracking purposes. The HTTP cookies are supported by the JSP. Here, we shall see the anatomy of the HTTP cookie, how to set or reset the cookie, and methods in cookies. 

Anatomy of a Cookie

The cookie is always present at the HTTP header. When the JSP sets the cookie in the HTTP header, it has the following structure.

HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT;
  path = /; domain = tutorialspoint.com
Connection: close
Content-Type: text/html

In the Set-Cookie header above, you can observe the name-value pair, date in GMT, a path, and the domain. This name-value pair is present in the URL format. Another element in the above cookie is expires, which tells the browser to forget this cookie after the specified date and time. 

Cookies Methods

The following are some significant methods related to the Cookies, along with their descriptions.

  • public String getDomain(): This function retrieves the domain of the cookie. 
  • public void setDomain(String pattern): You can set the domain for your cookie using this function. 
  • public int getMaxAge(): It fetches the maximum age of a cookie. The age is represented in seconds. 
  • public void setMaxAge(int expiry): This function will set the time duration for elapse before the cookie expires. 
  • public String getValue(): It retrieves the cookie’s value. 
  • public String getName(): It fetches the cookie’s name. You cannot change the cookie name after its creation.
  • public void setValue(String newValue): This function fixes the cookie value. 
  • public String getPath(): It results in the path associated with the cookie.
  • public void setPath(String uri): This function sets the path for the cookie. 
  • public String getComment(): It results in the comment, which specifies the cookie’s purpose or use. If the cookie has no comment, it returns NULL. 
  • public void setSecure(boolean flag): It specifies the boolean value defining whether to send the cookie over an encrypted connection. 
  • public void setComment(String purpose): This function sets the comment for a cookie specifying its purpose.

How to set the Cookie?

There are three straightforward methods for setting the cookie. These methods are explained below:

  1. Firstly, create the cookie object. Call the cookie constructor with the cookie’s name and corresponding value. Both name and value are represented in String. 
Cookie cookie = new Cookie("key","value");

While creating the cookie, you must remember that there should not be any blank spaces or special symbols in the name and value. 

  1. After creating the cookie, we will now set the maximum age for it using the setMaxAge function. 
cookie.setMaxAge(60*60*24);

The above function sets the maximum cookie age of 24 hours. 

  1. Lastly, use the response.addCookie to add the cookie into the HTTP response header. 
response.addCookie(cookie);

Conclusion

JavaServer Pages or Jakarta Server Pages (JSP) is the technology enabling developers to create dynamic content or webpages. There are multiple advanced advantages of JSP, as it is easy to maintain, requires less code than servlets, and offers fast development. This article is a quick guide to learn JSP for novice users. 

We have covered all aspects of the JSP that are required for novice developers to learn. Before starting any JSP program, first set up the Java environment and the Tomcat classpath. Here is a complete tutorial about all the essential JSP elements. 

We do have a Graph Theory quick guide which talks about all the details related to Graph Theory in detail. 

Recommended Articles