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
7
votes
2 answers

Where is JSESSIONID stored? (JavaEE)

I have two applications - A Java EE web application and a Java SE applet. I want to authenticate a user in the applet by means of a JSESSIONID (which is created by the web application). So there is a problem - how to associate this JSESSIONID with…
marxin
  • 3,692
  • 3
  • 31
  • 44
7
votes
3 answers

Retaining the submitted JSP form data

I am having a web form(JSP) which submits the data to different application, hosted on different server. After submitting the form data, that application redirect back to same JSP page. Now, I want to save the entered the data. What are the…
Sourabh
  • 1,515
  • 1
  • 14
  • 21
7
votes
4 answers

When does a body onLoad gets called?

I need to understand when does a body's onload gets called I read in w3school that onload=Script to be run when a document load what does this mean? Does it mean that the html/jsp page gets loaded before rendering any elements in the body like any…
user801116
7
votes
2 answers

Specify JRE/JDK when starting Apache Tomcat 7

Is there a way to tell Tomcat 7 the path to the JVM that must be used? For example: startup --jvm /path/to/my/jvm
MauroPorras
  • 5,079
  • 5
  • 30
  • 41
7
votes
4 answers

How to call a servlet on jsp page load?

I have below servlet. I would like to call the servlet on jsp page load. How can I do that? servlet: SomeServlet.java Hello SomeServlet
user1016403
  • 12,151
  • 35
  • 108
  • 137
7
votes
3 answers

Where to put my taglib declaration?

I've got a JSP and I'm going to start using the JSTL taglib. So I need to declare it and I do it by the row <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> But where do I put this code? At the top of the file, before everything, or…
Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424
7
votes
2 answers

How to host a JSP website on a webserver?

I have a website developed mostly in HTML and JSP, and accessing a MySQL database. Having never put such a website online before, I wanted to know what are the steps needed to get it up and running online. I know there needs to be a web server. How…
absessive
  • 1,121
  • 5
  • 14
  • 36
7
votes
1 answer

Designer friendly JSP/Servlet web development in both Windows and Linux (Ubuntu, et. al.)

I'm a front-end developer for my college JSP project and so far I was using Sublime Text 2 for writing markup and my CSS/Less and ran the project directly from Apache Tomcat configured manually where I placed my project directory in webapps folder,…
Kushal
  • 3,112
  • 10
  • 50
  • 79
6
votes
1 answer

JSTL variables are not shown in EL

JSTL variable values are not shown in EL. For example this code: <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="s" uri="http://www.springframework.org/tags" %>
adrift
  • 637
  • 2
  • 10
  • 34
6
votes
2 answers

Cannot redirect with the response.sendRedirect

I googled and googled for hours on how to make a redirect in jsp or servlets. However when i try to apply it, it doesn't work. Code that i have inside jsp page: <% String articleId = request.getParameter("article_id").toString(); …
Dmitris
  • 3,408
  • 5
  • 35
  • 41
6
votes
2 answers

Using JSP with Buttons

I have a button in a JSP page: I want to perform the following jsp code: <% session.setAtrribute("status","guest"); %> when I press the button. Is it possible to use JSP code on a…
Kristal
  • 235
  • 2
  • 3
  • 9
6
votes
1 answer

Apache Tomcat:The requested resource () is not available (while acessing the resource that should be avaliable)

This is my first question here (so be gentle :)). I've looked everywhere and cant find the answer to my problem (also went a little crazy in the process). I'm using Tomcat 7 and latest Eclipse IDE for Java EE developers (Eclipse platform 3.7.2 and…
MoD
  • 264
  • 2
  • 9
6
votes
2 answers

How to display checkboxes within HTML dropdown?

I need to populate a drop down list (HTML ) with check boxes. I have tried to display such a list using a
tag and applying some styles in JSP page but it displays a list like a list box. Below is the code in JSP page…
Bhavesh
  • 4,607
  • 13
  • 43
  • 70
6
votes
6 answers

How can I view .JSP files

I am new with web application and I have some files (web files) with the extension of .jsp. I would like to know how I can view them in suitble way in my machine? Do I need apache server? Note: I am talking about the end-user view NOT the…
Aan
  • 12,247
  • 36
  • 89
  • 150
6
votes
2 answers

How do I add .jsp headers and footers to my Spring MVC web app?

How do I add .jsp headers and footers to my Spring MVC web app? I know there's many different answers, but I would like to know (them all really but more importantly) what is the proper way to do this? I'm just learning Spring and I have a hint the…
Xonatron
  • 15,622
  • 30
  • 70
  • 84