Questions tagged [jsp]

JSP (Jakarta Server Pages, formerly JavaServer Pages) is a Java-based view technology running on the server machine which allows you to write template text in client side languages (like HTML, CSS, JavaScript and so on) and interact with backend Java code.

JSP (Jakarta Server Pages, formerly JavaServer Pages)

JSP is a Java templating technology running on a server which allows you to write template text in client-side languages like HTML, CSS, JavaScript and so on. JSP supports the so-called taglibs which are backed by pieces of Java code with which you can control the page flow and/or output dynamically (programmatically). A well-known taglib is JSTL. JSP also supports Expression Language (EL), with syntax like ${} which can be used to access backend data (actually, the attributes which are available in the page, request, session and application scopes), mostly in combination with taglibs.

Lifecycle

When a JSP is requested for the first time or when the web application starts up, the servlet container will compile the JSP file into a class extending HttpServlet and use it during the web application's lifetime. You can find the generated source code in the server's work directory. In, for example, Tomcat, it's the /work directory. On a JSP request, the servlet container will execute the compiled JSP class and send the generated output (usually just HTML, CSS, and JavaScript) through the web server over the network to the client side, which in turn displays it in the browser.

Installing JSP

In order to run JSP, you need:

  • JDK (JRE is only sufficient if the server has its own compiler).
  • A servlet container.
  • Optionally, a Java EE aware IDE (integrated development environment).

How to install JDK or JRE is outlined in Overview of JDK 9 and JRE 9 Installation.

There are several servlet containers.

There are also Java EE application servers which in turn also contain a servlet container beside other Java EE APIs such as JSF, JPA, EJB, etc. See also What exactly is Java EE?

Installing a servlet container is generally just a matter of downloading the zip/gz file and extracting it at the location of your choice.

Generally, you'd also like to use an IDE such as Eclipse, IntelliJ or NetBeans so you don't need to manually compile and build the source files with javac over and over. Decent IDEs have plugins to seamlessly integrate the servlet container and import the necessary Java EE APIs into the build path of the project. See also How do I import the javax.servlet / jakarta.servlet API in my Eclipse project?.

Hello, World!

This example uses JSTL and EL to display the user's IP address and today's date.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<jsp:useBean id="date" class="java.util.Date" />

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>JSP Hello, World!</title>
    </head>
    <body>
        <h1>Hello</h1>
        <p>Welcome, user from <c:out value="${pageContext.request.remoteAddr}" />
        <p>It's now <fmt:formatDate value="${date}" pattern="MM/dd/yyyy HH:mm" />
    </body>
</html>

Save it as /hello.jsp and open it by http://localhost:8080/contextname/hello.jsp.

If JSTL doesn't work (the JSTL tags are not parsed/executed and still there in generated HTML output when you right-click and View Source in the browser), then probably your servlet container doesn't support it out of the box (like Tomcat). You can install it by just dropping jstl-1.2.jar in /WEB-INF/lib. If it still doesn't work, then refer JSTL info page for more detail.

Scriptlets

You can also inline raw Java code in a JSP file using scriptlets (those <% %> things).

<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Date" %>

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>JSP Hello, World!</title>
    </head>
    <body>
        <h1>Hello</h1>
        <p>Welcome, user from <%= request.getRemoteAddr() %>
        <p>It's now <%= new SimpleDateFormat("MM/dd/yyyy HH:mm").format(new Date()) %>
    </body>
</html>

Its use is however as per the JSP coding conventions discouraged for other purposes than quick prototyping.

Best Practices

It is easy to write unmaintainable code with JSP, so some best practices have been developed. A fundamental practice is to use JSP as the view in the model view controller design pattern. This is sometimes referred to as the Model 2 design where Servlets are used as the Controller. The model can be JavaBeans, POJOs, or even JPA entities. Other best practices include avoiding scriplets, creating reusable template tags, and using JSTL to avoid re-inventing the wheel.

Data pre-loading and form post-processing

To pre-load data for display in a JSP and to post-process a form submit, you'd like to use a Servlet. For more detail, see Servlets tag info page.

JavaScript

It's important to realize that JSP runs in the web server, producing HTML output and that JavaScript is part of the HTML output that runs in the browser only. So JSP and JavaScript don't run in sync as you might expect from the coding. To let JavaScript "access" JSP variables, all you need to do is to let JSP/JSTL/EL print it as if it is a JavaScript variable. This way any JavaScript function, once executed in the browser, can access it. The below example prints the server side session ID as a JavaScript variable using EL:

<script>var jsessionid = '${pageContext.session.id}';</script>

If you open this page in a browser and do a View Source, then you'll see something like:

<script>var jsessionid = '4C147636FF923CA7EA642F2E10DB95F1';</script>

(note that those single quotes were thus mandatory to represent a JavaScript string value!)

Then, to let JSP "access" JavaScript variables, you need to send the JavaScript variable back to the server using an HTTP request, since that's the only way to send data from the browser to a web server. You could:

  • use the HTML DOM to manipulate a hidden input field and fill it with the data, and if necessary submit the form using form.submit() so that it's available by request.getParameter().
  • use window.location to do a "redirect" to a new URL with the JavaScript variable as a request parameter.
  • use XMLHttpRequest to send an asynchronous (Ajax) request with the JavaScript variable as a request parameter.
  • let JavaScript set it as a cookie so that it's available by request.getCookies() in subsequent requests.

See also Access Java / Servlet / JSP / JSTL / EL variables in JavaScript.

Facelets

Since Java EE 6, JSP has been succeeded by Facelets as the default view technology for the Java EE MVC framework JSF (JavaServer Faces). Since the Java EE 6 tutorial, JSP is not treated in detail any longer. You need to head back to the Java EE 5 tutorial if you want to learn JSP. See also https://stackoverflow.com/questions/4845032/wheres-the-official-jsp-tutorial.

Online resources

Frequently Asked Questions

Related tag information pages

52210 questions
62
votes
7 answers

Where can I download JSTL jar

Does anyone know because all the places I've tried seem to timeout!
Deano
  • 1,740
  • 4
  • 20
  • 24
61
votes
6 answers

Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern

I'm implementing MVC using JSP and JDBC. I have imported a database class file to my JSP file and I would like to show the data of a DB table. I don't know how I should return the ResultSet from the Java class to the JSP page and embed it in…
Ashwani Sharma
  • 629
  • 1
  • 6
  • 3
61
votes
1 answer

struts2 optiontransferselect retrieve and display value from database

In the jsp page, I have a for swap values between left side and right side and a submit button to save.
Learner
  • 727
  • 4
  • 13
61
votes
7 answers

String Concatenation in EL

I would like to concatenate a string within a ternary operator in EL(Expression Language). Suppose there is a variable named value. If it's empty, I want to use some default text. Otherwise, I need to append it with some static text. ${(empty…
Tom Tucker
  • 11,676
  • 22
  • 89
  • 130
61
votes
16 answers

Spring Boot JSP 404

I'm trying to add a jsp page in my Spring Boot service. My problem is that every time I try to go to that page I have this: Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Tue Apr…
dephinera
  • 3,703
  • 11
  • 41
  • 75
61
votes
2 answers

Iterate over elements of List and Map using JSTL tag

If I have a JSF backing bean return an object of type ArrayList, I should be able to use to iterate over the elements in the list. Each element contains a map and although the question of how to access the map content through JSTL has…
volvox
  • 3,014
  • 16
  • 51
  • 80
61
votes
22 answers

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

I have a Java EE project which build fine with Ant, deploys perfectly to JBoss, and runs without any trouble. This project includes a few custom tag libraries (which is not JSTL!), which are also working without any difficulties. The problem is with…
ryandenki
  • 1,859
  • 3
  • 19
  • 30
60
votes
2 answers

What is the difference between creating JSF pages with .jsp or .xhtml or .jsf extension

I saw some examples creating the JSF pages with .jsp extension, other examples creating them with .xhtml extension, and other examples choose .jsf. I just would like to know what the difference is between above extensions when working with JSF…
fresh_dev
  • 6,694
  • 23
  • 67
  • 95
60
votes
3 answers

setting up a value for a variable name in thymeleaf

I am new to Thymeleaf and converting my Web page from JSP to Thymeleaf. I have a strut tag like this: That variable can be used anywhere in JSP. Is there any such alternatives for this in Thymeleaf?
59
votes
13 answers

HTTP Status 404 - The requested resource (/) is not available

I integrated Tomcat 7 in Eclipse. When I start it using Eclipse, it shows that Tomcat is up and running, but when I go to http://localhost:8080 in my browser, it gives me following error: HTTP Status 404 - / type Status report message / description…
Vandan Patel
  • 1,012
  • 1
  • 12
  • 23
59
votes
1 answer

How to loop over something a specified number of times in JSTL?

I need a while loop within JSTL. I cannot seem to find how to loop over something a specified number of times. Any ideas how I can accomplish this? I am thinking I could use a forEach but I do not really care to loop over a collection.
Jonathan Hult
  • 1,351
  • 2
  • 13
  • 19
56
votes
1 answer

JSP include with parameters usage

How should I access the param1 value from the included jsp (navMenu.jsp)?
DanC
  • 8,595
  • 9
  • 42
  • 64
56
votes
2 answers

Use with HashMap

I have a java class that sets an servlet attribute to a HashMap object: request.setAttribute("types", da.getSecurityTypes()); where request is an HttpServletRequest Object, and da.getSecurityTypes() returns a HashMap Object. Is there a way to go…
jonasespelita
  • 1,660
  • 5
  • 25
  • 31
56
votes
4 answers

Passing parameters to another JSP file using tag

I have a JSP file and in that file I am including another JSP file: ...
SIGSTP
  • 1,125
  • 2
  • 9
  • 21
55
votes
6 answers

Redirect pages in JSP?

I have to design several pages in jsp. After clicking on the submit button on the first page, the page should be automatically redirected to the second page. Can you help with a quick example or a link to a tutorial that demonstrates how to…
PROXY
  • 619
  • 1
  • 5
  • 4