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
69
votes
4 answers

Increment counter with loop

This question is related to my previous question : Jsp iterate trough object list I want to insert counter that starts from 0 in my for loop, I've tried several combinations so far : 1.
London
  • 14,986
  • 35
  • 106
  • 147
69
votes
3 answers

Using JSF as view technology of Spring MVC

I am currently implementing a small Spring MVC PoC, and I would like to use JSF as the view technology since most people in my company are used to a J2EE with Primefaces environment. Does Spring MVC 3 support JSF, or simply JSP? I have read multiple…
Astronaut
  • 6,691
  • 18
  • 61
  • 99
68
votes
3 answers

jstl foreach omit an element in last record

trying to use this jstl to formulate a json string, how can i make the segment not to put a comma in the end of the last record? note the comma in the end { id:1001,data:["
nokheat
  • 1,167
  • 4
  • 14
  • 23
68
votes
5 answers

Thymeleaf construct URL with variable

I have the following code setting a variable in my controller: model.set("type", type); In the thymeleaf view I want to construct a form with action url: /mycontroller/{type} Any ideas how to achieve this? I've read thymeleaf documentation with no…
Chris
  • 923
  • 1
  • 8
  • 11
67
votes
6 answers

How do you get the contextPath from JavaScript, the right way?

Using a Java-based back-end (i.e., servlets and JSP), if I need the contextPath from JavaScript, what is the recommended pattern for doing that, any why? I can think of a few possibilities. Am I missing any? 1. Burn a SCRIPT tag into the page that…
Mike M. Lin
  • 9,992
  • 12
  • 53
  • 62
67
votes
5 answers

Why set a JSP page session = "false" directive?

I was wondering when you would want to set the following page directive in a JSP: <%@ page session="false" %> I know that it prevents the creation of the session object, but when would you need to do that? Is it considered a best practice when a JSP…
Mike G
  • 4,713
  • 2
  • 28
  • 31
67
votes
8 answers

Sun JSTL taglib declaration fails with "Can not find the tag library descriptor"

I am using a JSP page to print an array of values. I'm trying to use JSTL for this. ${object.name} The problem is my JSTL taglib declaration: <%@ taglib prefix="c"…
Atma
  • 29,141
  • 56
  • 198
  • 299
66
votes
16 answers

getOutputStream() has already been called for this response

I google the error message getOutputStream() has already been called for this response and many people said it is because of the space or newline after <% or %>, but in my code , there is no a space or a newline. I am using tomcat6 on linux. <%@ …
Southsouth
  • 2,659
  • 6
  • 32
  • 39
65
votes
5 answers

Using request.getRemoteAddr() returns 0:0:0:0:0:0:0:1

I am trying to print the IP adress of the logged user in my webApplication. If a user connects from another PC (which is under the same network, as the web application is running in my pc) using the IP address 192.168.10.120:8080/WebApplication the…
yaylitzis
  • 5,354
  • 17
  • 62
  • 107
64
votes
5 answers

Can I serve JSPs from inside a JAR in lib, or is there a workaround?

I have a web application deployed as a WAR file in Tomcat 7. The application is build as a multi-module project: core - packaged as JAR, contains most of the backend code core-api - packaged as JAR, contains interfaces toward core webapp - packaged…
waxwing
  • 18,547
  • 8
  • 66
  • 82
64
votes
6 answers

No results returned by the Query error in PostgreSQL

I am trying to insert a data into a table. After executing the query i am getting an exception stating org.postgresql.util.PSQLException: No results were returned by the…
Ragesh Kr
  • 1,573
  • 8
  • 29
  • 46
63
votes
6 answers

Reading a JSP variable from JavaScript

How can I read/access a JSP variable from JavaScript?
Siddiqui
  • 7,662
  • 17
  • 81
  • 129
63
votes
8 answers

How to change Java version used by TOMCAT?

I have Java 1.6 and Tomcat 5.5 installed on my system. But Tomcat 5.5 accesses Java 1.5 and hence as the outcome I get the error Bad version number in .class file while executing java code with JSP. How can I change the Tomcat version to Java…
LGAP
  • 2,365
  • 17
  • 50
  • 71
63
votes
8 answers

How do I prevent people from doing XSS in Spring MVC?

What should I do to prevent XSS in Spring MVC? Right now I am just putting all places where I output user text into JSTL tags or fn:escapeXml() functions, but this seems error prone as I might miss a place. Is there an easy systematic way to…
Doug
  • 813
  • 1
  • 7
  • 7
62
votes
3 answers

How to access at request attributes in JSP?

Currently I use: <% final String message = (String) request.getAttribute ("Error_Message"); %> and then <%= message %> However I wonder if the same can be done with EL or JSTL instead of using a scriptlet.
Martin
  • 11,577
  • 16
  • 80
  • 110