Questions tagged [jsp]

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

JSP (JavaServer Pages)

JSP is a Java view 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 webapp starts up, the servlet container will compile the JSP file into a class extending HttpServlet and use it during the webapp'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/JS) 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 Editor).

How to install JDK or JRE is outlined here: https://docs.oracle.com/javase/9/install/overview-jdk-9-and-jre-9-installation.htm

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 to 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 API in my Eclipse project?

Hello World

This example uses JSTL and EL to display the user IP 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 use 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 webserver. 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 JS 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 info pages

51773 questions
123
votes
2 answers

Difference between JSP EL, JSF EL and Unified EL

I would like to know the detailed difference between the Expression Languages (EL). There is JSP EL, JSF EL and Unified EL. I would like to know the history behind the EL and what the latest EL is that is used in Java EE applications. Is it the EL…
Krishna
  • 6,706
  • 15
  • 64
  • 79
122
votes
2 answers

Evaluate if list is empty JSTL

I've been trying to evaluate if this array list is empty or not but none of these have even compiled:
OscarRyz
  • 184,433
  • 106
  • 369
  • 548
118
votes
7 answers

How do you get the length of a list in the JSF expression language?

How would I get the length of an ArrayList using a JSF EL expression? #{MyBean.somelist.length} does not work.
GBa
  • 14,931
  • 15
  • 47
  • 67
116
votes
9 answers

Strip whitespace from jsp output

How can I strip out extra whitespace from jsp pages' output? Is there a switch I can flip on my web.xml? Is there a Tomcat specific setting?
Seth Weiner
  • 2,929
  • 5
  • 24
  • 14
112
votes
5 answers

JSP : JSTL's tag

Writing a JSP page, what exactly does the do? I've noticed that the following both has the same result:

The person's name is

The person's name is ${person.name}

Steve Kuo
  • 58,491
  • 75
  • 189
  • 247
112
votes
5 answers

How to get a index value from foreach loop in jstl

I have a value set in the request object like the following, String[] categoriesList=null; categoriesList = engine.getCategoryNamesArray(); request.setAttribute("categoriesList", categoriesList ); and this is how I iterate in jsp page <%…
Java Questions
  • 7,372
  • 37
  • 109
  • 169
109
votes
6 answers

What is the difference between and <%@ include file = ... >?

Both tags include the content from one page in another. So what is the exact difference between these two tags?
Prasoon
  • 1,407
  • 4
  • 13
  • 10
108
votes
4 answers

JSF vs Facelets vs JSP

I can't seem to get a clear answer as to the concrete difference between Java Server Faces vs. so-called facelets. Can anyone give me a clear-as-day answer?!? Also, I understand that either JSF or JSP can be used to create dynamic web pages, but two…
Pam
  • 1,083
  • 2
  • 8
  • 4
106
votes
12 answers

How to reference constants in EL?

How do you reference an constants with EL on a JSP page? I have an interface Addresses with a constant named URL. I know I can reference it with a scriplet by going: <%=Addresses.URL%>, but how do I do this using EL?
tau-neutrino
  • 3,150
  • 6
  • 22
  • 20
106
votes
19 answers

How do I get whole and fractional parts from double in JSP/Java?

How do I get whole and fractional parts from double in JSP/Java ? If the value is 3.25 then I want to get fractional =.25, whole = 3 How can we do this in Java?
Vinayak Bevinakatti
  • 38,839
  • 25
  • 103
  • 135
106
votes
13 answers

Access Enum value using EL with JSTL

I have an Enum called Status defined as such: public enum Status { VALID("valid"), OLD("old"); private final String val; Status(String val) { this.val = val; } public String getStatus() { return val; …
IaCoder
  • 10,849
  • 10
  • 33
  • 45
104
votes
4 answers

Use JSTL forEach loop's varStatus as an ID

I want to use the count from the JSTL forEach loop, but my code doesnt seem to work.
produces
Mark W
  • 5,416
  • 13
  • 52
  • 90
103
votes
17 answers

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

I have an HTML form in a JSP file in my WebContent/jsps folder. I have a servlet class servlet.java in my default package in src folder. In my web.xml it is mapped as /servlet. I have tried several URLs in action attribute of the HTML form:
pongahead
  • 1,814
  • 3
  • 18
  • 21
100
votes
5 answers

Prevent user from seeing previously visited secured page after logout

I have the requirement that the end user should not be able to go back to the restricted page after logout/sign out. But currently the end user is able to do that by the browser back button, visiting browser history or even by re-entering the URL in…
raaz
  • 11,942
  • 21
  • 59
  • 81
99
votes
6 answers

How to get domain URL and application name?

Here's the scenario. My Java web application has following path https://www.mywebsite.com:9443/MyWebApp Let's say there is a JSP file https://www.mywebsite.com:9443/MyWebApp/protected/index.jsp and I need to retrieve…
ericbae
  • 9,378
  • 22
  • 73
  • 103