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
85
votes
12 answers

How to show email addresses on the website to avoid spams?

I show email on my website as following Email But I read the following while analysing my website using woorank.com, what should I do to avoid this? Malicious bots scrape the web in search of email addresses…
Jack
  • 6,430
  • 27
  • 80
  • 151
84
votes
26 answers

Java error: Only a type can be imported. XYZ resolves to a package

I get the error: "Only a type can be imported. XYZ resolves to a package." Someone has explained the cause here but I am not sure what I supposed to do to fix this. FYI: I am using Eclipse. I have added the code that does the importing below. The…
Ankur
  • 50,282
  • 110
  • 242
  • 312
83
votes
3 answers

How to internationalize/localize a JSP/Servlet web application?

I learnt from Google that Internationalization is the process by which I can make my web application to use all languages. I want to understand Unicode for the process of internationalization, so I learnt about Unicode from here and there. I am…
IamIronMAN
  • 1,871
  • 6
  • 22
  • 28
83
votes
10 answers

XSS prevention in JSP/Servlet web application

How can I prevent XSS attacks in a JSP/Servlet web application?
newbie
  • 24,286
  • 80
  • 201
  • 301
82
votes
4 answers

JSP EL String concatenation

How do I concatenate strings in EL? I want to do something like this but it doesn't work: ${var1 == 0 ? 'hi' : 'hello ' + var2} It throws an exception trying to cast 'hello' to a Double
Kyle
  • 21,377
  • 37
  • 113
  • 200
80
votes
6 answers

How to use relative paths without including the context root name?

To working my static file (CSS, JS) I have to write absolute path like /AppName/templates/style/main.css. Is there any solution, that I could write relative path like style/main.css?
kspacja
  • 4,648
  • 11
  • 38
  • 41
79
votes
3 answers

What's the difference between # , % and $ signs in Struts tags?

I'm working with Struts 2 and when I'm accessing ValueStack variables I don't know whether to use % or # or $. I try all of them until I find the correct one. Can anybody explain what is the difference between them?
Khashayar
  • 2,014
  • 3
  • 22
  • 31
79
votes
16 answers

Alternatives to JSP for Spring MVC view layer

I'm looking to create a new app from scratch and will probably use Spring MVC and possibly Spring Web Flow. The projects created by Spring Roo use Spring MVC and optionally Web Flow. What are some good alternatives for view technology, or is JSP…
digitaljoel
  • 26,265
  • 15
  • 89
  • 115
78
votes
1 answer

Hidden features of JSP/Servlet

I am interested in your tricks etc used when writing JSP/Servlet. I will start: I somewhat recently found out how you can include the output of one JSP tag in an attribute of another tag:
mkoryak
  • 57,086
  • 61
  • 201
  • 257
76
votes
1 answer

How do I compare if a string is not equal to?

I'm trying to only show something based on if a string is not equal to:
  • Publish History
  • It keeps throwing the error…
    Ben
    • 60,438
    • 111
    • 314
    • 488
    75
    votes
    7 answers

    Difference between JSP forward and redirect

    Please explain the difference between jsp:forward and redirect. What is happening in each case?
    Ammu
    • 5,067
    • 9
    • 34
    • 34
    73
    votes
    1 answer

    Declaring functions in JSP?

    I come from PHP world, where declaring a function in the middle of a php page is pretty simple. I tried to do the same in JSP: public String getQuarter(int i){ String quarter; switch(i){ case 1: quarter = "Winter"; break; case 2:…
    Nathan H
    • 48,033
    • 60
    • 165
    • 247
    72
    votes
    11 answers

    How do I set Tomcat Manager Application User Name and Password for NetBeans?

    I'm trying to follow a tutorial to make an extremely basic Java web application in NetBeans. When I try to run it, a dialogue box appears title "Authentication Required". Inside the dialogue box there the heading "Tomcat Manager Application" and…
    Eric Wilson
    • 57,719
    • 77
    • 200
    • 270
    70
    votes
    6 answers

    Convert and format a Date in JSP

    From my JSP Page, I am getting Date in this format. Fri May 13 2011 19:59:09 GMT 0530 (India Standard Time) How can I convert this to the pattern yyyy-MM-dd HH:mm:ss?
    user663724
    70
    votes
    11 answers

    Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

    I can't get tomcat7 to compile jsps. It till run the example servlets just fine and the service is up and running. I am running oracle java 8. Can anyone point me in the right direction? Here is the stacktrace: type Exception report message Unable…
    user2130951
    • 2,601
    • 4
    • 31
    • 58