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

Issue in getting context path inside jsp?

My jsp lies at below location http://myApp.com/myWebApp/customer/images/customer.jsp My image(accessed thru customer.jsp) lies at http://myApp.com/myWebApp/images/customer.gif In image tag i am making the absoulte path as…
M Sach
  • 33,416
  • 76
  • 221
  • 314
7
votes
1 answer

JSF 1.2 - iterate over a Map that contains Collections

Using JSF 1.2 and JSP.... Is it possible to iterate over a Map whose values contain Collections? I have a Map that looks like this: Map> myMap; I would like to iterate over myMap and draw a separate table for each key. Each table…
jahroy
  • 22,322
  • 9
  • 59
  • 108
7
votes
2 answers

host 'X' Blocked because of many connection errors

Hi I am Using Java with MySql . I have taken some x hosting service,in that i have deployed my java .war file it is worked some days ,since 2 days i am getting some error that is java.sql.SQLException: null, message from server: "Host 'X host' is…
user1548560
  • 91
  • 1
  • 2
  • 5
7
votes
2 answers

Unable to compile class for JSP: cannot be resolved to a type

I am developing a Dynamic web project. Project is running well on local server but not on live. On live server it throws exception at the line I have used any java object: org.apache.jasper.JasperException: Unable to compile class for JSP: An…
Sukhpal Singh
  • 672
  • 1
  • 12
  • 31
7
votes
2 answers

Request Attributes not available in jsp page when using sendRedirect from a servlet

I am new to jsp and servlet. My scenario is as follows I have a jsp page which have a form in it. with two fields. The code snipet of the jsp page is as follows. MyFirstJSP.jsp file

This is my first jsp and servlet…

Param-Ganak
  • 5,787
  • 17
  • 50
  • 62
7
votes
1 answer

Binding a map of lists in Spring MVC

I am not sure if this is a complex problem but as a starting person this seems a bit complex to me. I have an object based on which i need to show some values on the UI and let user select some of them, i need to send data back to another controller…
Umesh Awasthi
  • 23,407
  • 37
  • 132
  • 204
7
votes
2 answers

Give access to JSP file/folder only for particular IP address

I made a CMS application using JSP and servlet. I am not using any kind of framework. The CMS has 2 parts: Front end Admin (Back end) If I hosted it on www.example.com, for example, then all my frond end site will show for all users. But…
KuKu
  • 646
  • 2
  • 15
  • 38
7
votes
4 answers

Get IP address of client in JSP

I need to get the IP address of the client in the JSP page. I have tried the following…
Satish Sharma
  • 3,284
  • 9
  • 38
  • 51
7
votes
2 answers

Facelets without JSF

I'm finishing on learning the Java language and looking to write very small web applications, since Facelets seems to be the replacement for JSP, and JSF seems overkill for small web apps, can I just learn Facelets and use it without the whole JSF…
Der
  • 283
  • 2
  • 7
7
votes
3 answers

JSP - what's the difference between “<% … %>” VS “<%= … %>”

While working with JSP files and servlets , I came across <% … %> and <%= … %> . What's the difference between both cases ? Thanks
JAN
  • 21,236
  • 66
  • 181
  • 318
7
votes
6 answers

How to load a .properties file into a jsp

I've gotten as far as this: private Properties logoUrls = new Properties(); logoUrls.load(new FileInputStream("channelLogos.properties")); where channelLogos.properties is in the same directory as my JSP. I get a FileNotFound exception. Where does…
morgancodes
  • 25,055
  • 38
  • 135
  • 187
7
votes
2 answers

How to call JS function within .js file into .jsp file?

I am trying to call a javaScript function that's in .../js/index.js file to .../index.jsp file. Any suggestion would be helpful. Here is code within both file: index.js function testing() { if ("c" + "a" + "t" === "cat") { …
Simple-Solution
  • 4,209
  • 12
  • 47
  • 66
7
votes
2 answers

What is the simplest way to display httpServletResponse.sendError(403, "My Message") status from JSTL

I have a servlet which does some error checking and if something is wrong I will typically do this: response.sendError(403, "My message") return; I don't want to throw an exception from the servlet - because I would like to conform with HTTP…
tronda
  • 3,902
  • 4
  • 33
  • 55
7
votes
3 answers

Get current URL in Webapplication

I am in process to capture Current URL as its being displayed in the browser's address bar in my JSP page and have few options to get it done. Using javax.servlet.include.request_uri and other defined in Servlet 2.4 specification.I refer this…
Umesh Awasthi
  • 23,407
  • 37
  • 132
  • 204
7
votes
2 answers

tomcat - their classes from previous runs are still loaded in memory

when stop my project , tomcat say : The following web applications were stopped (reloaded, undeployed), but their classes from previous runs are still loaded in memory, thus causing a memory leak (use a profiler to confirm) . Where we find that…
Ali Farozi
  • 193
  • 2
  • 2
  • 6