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
55
votes
9 answers

Pass variables from servlet to jsp

How can I pass variable from servlet to jsp? setAttribute and getAttribute didn't work for me :-(
Developer
  • 6,375
  • 12
  • 58
  • 92
55
votes
2 answers

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

The following code causes an error: <% String resp = "abc"; resp = resp + test; pageContext.setAttribute("resp", resp); %> The error says "error a line 4: unknown symbol…
Cornish
  • 899
  • 2
  • 9
  • 8
55
votes
6 answers

JSP debugging in IntelliJ IDEA

Does anyone know how to debug JSP in IntelliJ IDEA? When I set breakpoint in my JSP files, those breakpoints never seem to take effect. The debugger never hits them. IDEA seems to think that the breakpoints are valid. I do see a red dot placed to…
yuantan
55
votes
4 answers

JSTL if-statement inside HTML-attribute

is it possible to do something like this in JSTL:

some other stuff...

Is there any way to get this to work, or is there a better way to add a class by looking at a…
Mickel
  • 6,658
  • 5
  • 42
  • 59
54
votes
4 answers

Variables in jsp pages with "included" pages

What are the scoping rules for variables in a jsp page with pages added to them using tags? My understanding is that an included page is essentially copied verbatim into the page, which would lead me to assume that if I've declared a variable in a…
Omar Kooheji
  • 54,530
  • 68
  • 182
  • 238
54
votes
11 answers

Eclipse webtools project (WTP) and its performance / quality

Our company is using eclipse since several years now (we are using WTP since release 0.7) I am currently evaluating eclipse 3.6.2 with WTP 3.2.3 which should replace eclipse 3.4.2 with WTP 3.0.4 as being our main IDE. And I have to say that once…
MRalwasser
  • 15,605
  • 15
  • 101
  • 147
54
votes
5 answers

What is the meaning of ? (question mark) in a URL string?

What is the difference between using href="../usermanagement/search_user.jsp?" and href="../usermanagement/search_user.jsp?pagename=navigation" in file navigation.jsp?
Sanjay Yadav
  • 569
  • 1
  • 4
  • 11
54
votes
2 answers

Default value on JSP custom-tag attribute

When defining an attribute for a custom JSP tag, is it possible to specify a default value? The attribute directive doesn't have a default value attribute. Currently I'm making do with: <%@ attribute name="myAttr" required="false"…
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
54
votes
5 answers

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

I have got a problem with my page jump when I use JAVA, if I use: response.sendRedirect("login.jsp") then I get this url: http://localhost:8080/login.jsp But if I use request.getRequestDispathcer("login.jsp").forward(request, response) then I get…
roger
  • 9,063
  • 20
  • 72
  • 119
52
votes
8 answers

Should I be doing JSPX instead of JSP?

Using JDeveloper, I started developing a set of web pages for a project at work. Since I didn't know much about JDev at the time, I ran over to Oracle to follow some tutorials. The JDev tutorials recommended doing JSPX instead of JSP, but didn't…
user290
52
votes
3 answers

Get value from hashmap based on key to JSTL

I want to get the value of HashMap based on key. HashMap> map = new HashMap>(); ArrayList arrayList = new ArrayList(); map.put("key", arrayList); request.setAttribute("key",…
newbie
  • 1,884
  • 7
  • 34
  • 55
52
votes
4 answers

debug JSP from eclipse

Does anyone know of a good tool for debugging JSPs from within Eclipse? I'd like to be able to set and watch breakpoints, step through the Java code/tags, etc within Eclipse while the app is running (under JBoss in my case). Presumably, it's…
Dónal
  • 185,044
  • 174
  • 569
  • 824
51
votes
2 answers

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

org.apache.catalina.core.ContainerBase addChildInternal SEVERE: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]] …
Abhi
  • 533
  • 1
  • 4
  • 8
50
votes
7 answers

How to use session in JSP pages to get information?

I have a JSP page used for editing some user's info. When a user logins to the website, I keep the information in the session, then in my edit page I try the following: <%! String username=session.getAttribute("username"); %>
yrazlik
  • 10,411
  • 33
  • 99
  • 165
49
votes
2 answers

What are and used for?

I was working on custom tag libraries and I was confused how the and tags are used in the TLD file to define a custom tag attribute. What are these tags? What should we write in-between them? What behavior do we get after…
bali208
  • 2,257
  • 7
  • 40
  • 43