JavaRush /Java Blog /Random EN /What is JSP? Exploring opportunities in practice
Анзор Кармов
Level 31
Санкт-Петербург

What is JSP? Exploring opportunities in practice

Published in the Random EN group
JSP or Java Server Pages is a Java technology that allows you to create dynamic web pages for Java applications. In this article, we will talk in more detail about what JSP is, discuss some of the capabilities of this technology, consider the structure of JSP pages, and also try to take a practical look at what these Java Server Pages are. What is JSP?  Dealing with the possibilities in practice - 1But first, let's talk about the benefits and importance of JSPs. JSP allows the developer to:
  • get data from a web page into Java code;
  • send data from Java code to a web page;
  • write Java code directly inside the html (however, you should not abuse this).
The need for knowledge of JSP can be rated quite highly for several reasons:
  • JSP is one of the core Java web technologies;
  • JSP is widely used in most companies and projects;
  • JSP seamlessly integrates with Java servlets inside a servlet container.

JSP - Definition

Here is a definition from Wikipedia: JSP (JavaServer Pages)A technology that allows web developers to create content that has both static and dynamic components. A JSP page contains two types of text: static source data, which can be in one of the HTML, SVG, WML, or XML text formats, and JSP elements, which construct dynamic content. In addition, JSP tag libraries can be used, as well as Expression Language (EL) to inject Java code into the static content of JSP pages. The JSP page code is translated into Java servlet code using the Jasper JSP Page Compiler, and then compiled into Java Virtual Machine (JVM) bytecode. Servlet containers capable of executing JSP pages are written in the platform-independent Java language. JSP technology is platform independent,

JSP page structure

In general, JSP refers to dynamic web pages, in which the dynamic part is generated using Java, and the static part is formed by markup languages, most often HTML. Such a page is a text document with the .jsp extension, written in one of the markup languages ​​(such as HTML, SVG, WML, and XML), interspersed with JSP elements (or jsp tags). Inside these tags are calls to the server code (data), and some calculations are also performed. These files are processed on the server, as a result of which all JSP tags are converted into html tags, and the output is a regular html page. The diagram below is a diagram of the structure of a JSP page and its interaction with the server. What is JSP?  Dealing with the possibilities in practice - 2An example of a simple JSP page:
<html>
  <body>
    <p> ${2 + 2} равно 4 </p>
  </body>
</html>
In this example, a JSP expression written in a special language Expression Language (EL) is “embedded” inside the html code . It provides an important mechanism for the interaction of the presentation layer (web pages) with the application's business logic layer (Java code). As you can see from the example, the JSP expression is enclosed in curly braces, with a leading dollar sign - ${...}. Everything inside the curly braces is evaluated on the server and the result of that expression is cast in html, to the place where the JSP expression was originally defined. After processing all the tags, the page will look like this:
<html>
  <body>
    <p> 4 равно 4 </p>
  </body>
</html>

Installing and running the servlet container

Since the JSP code is translated into Java servlet code, we need to get some kind of servlet container somewhere so that we can talk about how the JSP works. Otherwise, without a container, the JSP will not work. But first, let's define a servlet container. A servlet container is a program that is a server that provides system support for servlets and ensures their life cycle in accordance with the rules defined in the specifications. It can work as a full standalone web server, be a page provider for another web server, or integrate into a Java EE application server. One of the most popular servlet containers is Apache Tomcat. What is JSP?  Understanding the possibilities in practice - 3It is worth mentioning that Tomcat is not a full-fledged Java EE application server. However, for the vital needs of servlets and JSP pages, the Tomcat server is more than enough. Let's proceed with the installation. You can download Tomcat from the official page . For Windows OS, you can install Tomcat as follows:
  1. Download 32-bit/64-bit Windows Service Installer.

  2. We start the file.

  3. The following is the normal installation procedure:

    1. do not forget to check the Examples checkbox on the corresponding installer window:

      What is JSP?  Dealing with the possibilities in practice - 4
    2. and specify the path to the pre-installed JRE:

      What is JSP?  Dealing with the possibilities in practice - 5
  4. After installation, launch Tomcat and open a browser. Go to http://localhost:8080/ .

If you see the Tomcat start page, then the installation was successful and the server is running. To start and stop Tomcat manually, you can run one of the two executable files in the bin directory. It is located inside the directory where Tomcat is installed: What is JSP?  Dealing with the possibilities in practice - 6

Demo applications. Hidden objects

Let's take a look at some JSP features in action. One of them is access to the so-called hidden objects ( Implicit Objects ). These are objects that can be accessed using the EL (Expression Language) expression language. Examples of such objects are HTTP headers or URL parameters. Let's break down (or brush up on) what URL parameters are. The example below shows a URL with parameters. Parameters are in bold: http://example.net/foo/bar ?param1=value1¶m2=value2&a=1&name=Tom Parameters always begin with a question mark (?). This is followed by the name of the parameter, after - through the equal sign - the value of the parameter is determined. There can be several parameters or one. If there is more than one, each name-value pair is separated by an ampersand (&). In the example above, several parameters and their values ​​were defined:
Parameter name Parameter value
param1 value1
param2 value2
a 1
name Tom
Let's take a look at how you can access hidden objects in a JSP, including URL parameters. To do this, start Tomcat and open the browser on the page http://localhost:8080/ Then go to the page Examples: Then go to the What is JSP?  Dealing with the possibilities in practice - 7link JSP Examples: What is JSP?  Dealing with opportunities in practice - 8On the examples page go to the link Implicit Objects -> Execute: What is JSP?  Dealing with the possibilities in practice - 9On this page you can see an example of using hidden objects. Below is a screenshot of the page with detailed explanations: What is JSP?  Dealing with the possibilities in practice - 10Try changing the parameter valuefoo, using the appropriate field on the page for this, after which note that the value of this parameter has also changed in the address bar. The presented page does not have much functionality, but it is a good reference that you can refer to in the future when you need to access a particular hidden object. This page contains a list of hidden objects that you can access. And below, in the table, it is shown how you can access this or that object.

JSP Functions

Now let's go back to the previous page and take a look at the source code for the "hidden objects" page: What is JSP?  Dealing with opportunities in practice - 11Here it is:
<%@page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<html>
  <head>
    <title>JSP 2.0 Expression Language - Implicit Objects</title>
  </head>
  <body>
    <h1>JSP 2.0 Expression Language - Implicit Objects</h1>
    <hr>
    This example illustrates some of the implicit objects available
    in the Expression Language.  The following implicit objects are
    available (not all illustrated here):
    <ul>
      <li>pageContext - the PageContext object</li>
      <li>pageScope - a Map that maps page-scoped attribute names to
          their values</li>
      <li>requestScope - a Map that maps request-scoped attribute names
          to their values</li>
      <li>sessionScope - a Map that maps session-scoped attribute names
          to their values</li>
      <li>applicationScope - a Map that maps application-scoped attribute
          names to their values</li>
      <li>param - a Map that maps parameter names to a single String
          parameter value</li>
      <li>paramValues - a Map that maps parameter names to a String[] of
          all values for that parameter</li>
      <li>header - a Map that maps header names to a single String
          header value</li>
      <li>headerValues - a Map that maps header names to a String[] of
          all values for that header</li>
      <li>initParam - a Map that maps context initialization parameter
          names to their String parameter value</li>
      <li>cookie - a Map that maps cookie names to a single Cookie object.</li>
    </ul>

    <blockquote>
      <u><b>Change Parameter</b></u>
      <form action="implicit-objects.jsp" method="GET">
          foo = <input type="text" name="foo" value="${fn:escapeXml(param["foo"])}">
          <input type="submit">
      </form>
      <br>
      <code>
        <table border="1">
          <thead>
            <td><b>EL Expression</b></td>
            <td><b>Result</b></td>
          </thead>
          <tr>
            <td>\${param.foo}</td>
            <td>${fn:escapeXml(param["foo"])} </td>
          </tr>
          <tr>
            <td>\${param["foo"]}</td>
            <td>${fn:escapeXml(param["foo"])} </td>
          </tr>
          <tr>
            <td>\${header["host"]}</td>
            <td>${fn:escapeXml(header["host"])} </td>
          </tr>
          <tr>
            <td>\${header["accept"]}</td>
            <td>${fn:escapeXml(header["accept"])} </td>
          </tr>
          <tr>
            <td>\${header["user-agent"]}</td>
            <td>${fn:escapeXml(header["user-agent"])} </td>
          </tr>
        </table>
      </code>
    </blockquote>
  </body>
</html>
If you're familiar with HTML, the page's source code should be pretty clear to you. Pay attention to these lines:
<tr>
  <td>${param.foo}</td>
  <td>${fn:escapeXml(param["foo"])} </td>
</tr>
Here we see html tags <tr>and <td>. The tags <td>are followed by JSP tags wrapped in curly braces ${ }. However, notice how the value of the URL parameter is displayed foo:
${fn:escapeXml(param["foo"])}
The value is inferred using the JSP function fn:escapeXml(). JSP functions encapsulate some functionality that can be reused. In this case, it's XML escaping. JSP technology provides a wide range of functions to choose from, as well as the ability to create your own functions. To use a function in a JSP, you must import into the JSP file the appropriate library that defines the function.

Tag Libraries

Let's take a look at another line of source code (the second line) above:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
This is how tag libraries are imported. The syntax is intuitive. We define several things:
  • taglib(tag library - tag library);
  • urlon which the given library is located;
  • prefix (in this case fn) through which it will be possible to call the functions defined in this library.
In the example above, we considered importing functions. Specifically, in our example, we imported the JSTL (JSP Standard Tag Library) library. JSTL is a standard tag library that contains a set of different libraries that come with every servlet and JSP implementation, including Tomcat. Another popular tag library is core, which can be imported like this:
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
As with fn, the notation cis optional and generally accepted. This designation can be found almost everywhere where these libraries are used. Here is an example of a function from the core library:
<c:out value = "${'<div>'}"/>
This function will simply output the tag <div>. This function already does XML escaping. This function is important from a security point of view, because by displaying the value of variables directly, through ${variable}, we open the door for script injection.

JSP Editing

Now, armed with new knowledge, let's try to make changes to the demo application inside Tomcat. To do this, let's find the source code of this page inside the folder where this servlet container was installed. This file can be found at the following address: ...\Apache Software Foundation\Tomcat 9.0\webapps\examples\jsp\jsp2\el Then open the implicit-objects.jsp file in any text editor Add the import of the core library, and then use it to Let's display some text: What is JSP?  Dealing with opportunities in practice - 12Now let's refresh the Hidden Objects page and take a look at the changes made: What is JSP?  Dealing with opportunities in practice - 13

Results

So, we have superficially considered such technology as JSP. We discussed:
  • what is JSP;
  • the structure of the JSP page;
  • how to install and start the Tomcat servlet container;
  • a demo application for accessing hidden objects, which is included in the distribution package of the Tomcat server;
  • JSP functions and tag libraries.
What is JSP?  Dealing with opportunities in practice - 14

What's next?

To fix the material, you can:
  1. Repeat everything described in this article.
  2. Explore other demo applications included with the Tomcat server.
  3. Write your own application and deploy it in a servlet container. You can use the article Creating a Basic Web Project in IntelliJ Idea Enterprise as a guide . Step by step with pictures.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION