Guida a JavaServer Pages (JSP)

Sommario

  • 1. Panoramica
  • 2. JavaServer Pages
  • 2.1. Sintassi JSP
  • 2.2. Contenuti statici e dinamici
  • 2.3. Oggetti impliciti
  • 2.4. Altri oggetti impliciti
  • 2.5. Direttive
  • 2.6. Direttive di pagina
  • 3.0. Tre esempi
  • 3.1. HTML reso in Servlet
  • 3.2. Java in un contenuto statico JSP
  • 3.3. JSP con inoltro
  • 3.4. Provalo!
  • 4. Conclusione

1. Panoramica

JavaServer Pages (JSP) consente l' iniezione di contenuto dinamico in contenuti statici utilizzando Java e Java Servlet . Possiamo effettuare richieste a un servlet Java, eseguire la logica pertinente e rendere una vista specifica lato server da utilizzare lato client . Questo articolo fornirà una panoramica completa delle JavaServer Pages utilizzando Java 8 e Jave 7 EE.

Inizieremo esplorando alcuni concetti chiave rilevanti per JSP: vale a dire, la differenza tra contenuti dinamici e statici , il ciclo di vita JSP e la sintassi JSP, nonché le direttive e gli oggetti impliciti creati durante la compilazione!

2. JavaServer Pages

JavaServer Pages (JSP) abilitava il passaggio o l'inserimento di dati specifici di Java in una vista .jsp e l'utilizzo lato client.

I file JSP sono essenzialmente file .html con una sintassi extra e un paio di piccole differenze iniziali:

  1. il suffisso .html viene sostituito con .jsp (è considerato un tipo di file .jsp) e
  2. il tag seguente viene aggiunto all'inizio degli elementi di markup .html:

Esaminiamo alcuni dei concetti chiave di JSP.

2.1. Sintassi JSP

Esistono due modi per aggiungere codice Java a un file .jsp. Innanzitutto, possiamo utilizzare la sintassi Java Scriptlet di base che implica l'inserimento di blocchi di codice Java all'interno di due tag Scriptlet:

<% Java code here %>

Il secondo metodo è specifico per XML:

 Java code here 

È importante sottolineare che è possibile utilizzare la logica condizionale lato client con JSP utilizzando le clausole if , then e else e quindi avvolgendo i blocchi di markup pertinenti con quelle parentesi.

 Doodad! 

Hello!

Ad esempio, se doodad è vero, visualizzeremo il primo elemento div altrimenti visualizzeremo il secondo elemento p !

2.2. Contenuti statici e dinamici

I contenuti Web statici sono risorse fisse che vengono consumate indipendentemente da RESTful, SOAP, HTTP, richieste HTTPS o altre informazioni inviate dall'utente.

Il contenuto statico , tuttavia, è fisso e non viene modificato dagli input dell'utente. I contenuti web dinamici sono quelle risorse che rispondono, vengono modificate o cambiano alla luce delle azioni o delle informazioni dell'utente!

La tecnologia JSP consente la netta separazione delle responsabilità tra contenuti dinamici e statici .

Il server (servlet) gestisce i contenuti dinamici e il client (l'attuale pagina .jsp) è il contesto statico in cui vengono iniettati i contenuti dinamici.

Diamo un'occhiata agli oggetti impliciti che vengono creati da JSP e che ti consentono di accedere ai dati rilevanti per JSP lato server!

2.3. Oggetti impliciti

Gli oggetti impliciti vengono generati automaticamente dal motore JSP durante la compilazione .

Gli oggetti impliciti includono gli oggetti HttpRequest e HttpResponse ed espongono varie funzionalità lato server da utilizzare nel tuo servlet e per interagire con il tuo .jsp! Ecco l'elenco degli oggetti impliciti che vengono creati:

richiesta

la richiesta appartiene alla classe javax.servlet.http.HttpServletRequest . L' oggetto richiesta espone tutti i dati di input dell'utente e li rende disponibili lato server.

risposta

response appartiene alla classe javax.servlet.http.HttpServletResponse e determina cosa viene passato sul lato client dopo che è stata effettuata una richiesta .

Diamo un'occhiata più da vicino agli oggetti impliciti di richiesta e risposta poiché sono i più importanti e maggiormente utilizzati.

L'esempio seguente mostra un metodo servlet molto semplice, incompleto per gestire le richieste GET. Ho omesso la maggior parte dei dettagli in modo che possiamo concentrarci su come utilizzare gli oggetti richiesta e risposta :

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String message = request.getParameter("message"); response.setContentType("text/html"); . . . }

Innanzitutto, vediamo che gli oggetti richiesta e risposta vengono passati come parametri nel metodo rendendoli disponibili nel suo ambito.

Possiamo accedere ai parametri della richiesta utilizzando la funzione .getParameter () . Sopra, catturiamo il parametro del messaggio e inizializziamo una variabile di stringa in modo da poterla utilizzare nella nostra logica lato server. Possiamo anche accedere all'oggetto risposta che determina quali e come saranno i dati passati nella vista.

Above we set the content type on it. We don't need to return the response object to have it's payload display on the JSP page at render!

out

out belongs to the class javax.servlet.jsp.JspWriter and is used to write content to the client.

There are at least two ways to print to your JSP page and its worth discussing both here. out is created automatically and allows you to write to memory and then to the response object:

out.print(“hello”); out.println(“world”);

That's it!

The second approach can be more performant since it allows you to write directly to the response object! Here, we use PrintWriter:

PrintWriter out = response.getWriter(); out.println("Hello World");

2.4. Other Implicit Objects

Here are some other Implicit objects that are also good to know!

session

session belongs to the class javax.servlet.http.HttpSession maintains user data for the duration of the session.

application

application belongs to the class javax.servlet.ServletContext stores application-wide parameters set at initialization or that need to be accessed application-wide.

exception

exception belongs to the class javax.servlet.jsp.JspException is used to display error messages on JSP pages which have the tag .

page

page belongs to the class java.lang.Object allows one to access or reference current servlet information.

pageContext

pageContext belongs to the class javax.servlet.jsp.PageContext defaults to page scope but can be used for accessing request, application, and session attributes.

config

config belongs to the class javax.servlet.ServletConfig is the servlet configuration object allowing one to get the servlet context, name, and configuration parameters.

Now that we've covered the implicit objects provided by JSP, let's turn to directives which allow .jsp pages to (indirectly) access some of these objects.

2.5. Directives

JSP supplies out of the box directives that can be used to specify core functionalities for our JSP files. There are two parts to JSP directives: (1) the directive itself and (2) the attribute of that directive which is assigned a value.

The three kinds of directives that can be referenced using directive tags are which defines dependencies and attributes of the JSP including content type and language, which specifies an import or file to be used, and which specifies a tag library defining custom actions to be used by a page.

So, as an example, a page directive would be specified using JSP tags in the following way:

And, we can do that using XML as follows:

2.6. Page Directive Attributes

There are a lot of attributes that can be declared within a page directive:

autoFlush

autoFlush controls the buffer output, clearing it out when the buffer size is reached. The default value is true.

buffer

buffer sets the size of the buffer used by our JSP page. The default value is 8kb.

errorPage

errorPage specifies a JSP page as an error page.

extends

extends specifies the super class of the corresponding servlet code.

info

info is used to set a text-based description for the JSP.

isELIgnored

isELIgnored states whether or not the page will ignore Expression Language (EL) in JSP. EL enables the presentation layer to communicate with Java managed beans and does so using ${…} syntax and while we won't get into the nitty-gritties of EL here, there are several examples found below that are sufficient to build our example JSP app! The default value for isELIgnored is false.

isErrorPage

isErrorPage says whether or not a page is an error page. We must specify an error page if we create an error handler for our page within the application.

isThreadSafe

isThreadSafe has a default value of true. isThreadSafe determines whether or not the JSP can use Servlet multi-threading. In general, you would never want

to turn off that functionality.

language

language determines what scripting language to use in the JSP. The default value is Java.

session

session determines whether or not to maintain the HTTP session. It defaults to true and accepts values of true or false.

trimDirectiveWhitespaces

trimDirectiveWhitespaces stripes out white-spaces in the JSP page condensing the code into a more compact block at compile-time. Setting this value to true may help to reduce the size of the JSP code. The default value is false.

3. Three Examples

Now that we've reviewed the concepts central to JSP, let's apply those concepts to some basic examples that will help you to get your first JSP-serving servlet up and running!

There are three main ways to inject Java into a .jsp and we'll explore each of those ways below using native functionalities in Java 8 and Jakarta EE.

First, we'll render our markup server-side to be displayed client-side. Second, we'll look at how to add Java code directly into our .jsp file independent of javax.servlet.http‘s request and response objects.

Third, we'll demonstrate how to both forward an HttpServletRequest to a specific .jsp and bind server-side processed Java to it.

Let's set up our project in Eclipse using the File/New/Project/Web/Dynamic web project/ type to be hosted in Tomcat! You should see after creating the project:

|-project |- WebContent |- META-INF |- MANIFEST.MF |- WEB-INF |- lib |- src

We're going to add a few files to the application structure so that we end up with:

|-project |- WebContent |- META-INF |- MANIFEST.MF |- WEB-INF |-lib *-web.xml |- ExampleTree.jsp |- ExampleTwo.jsp *- index.jsp |- src |- com |- baeldung *- ExampleOne.java *- ExampleThree.java

Let's set up index.jsp which will be displayed when we access the URL context in Tomcat 8:

 JSP Examples 

Invoke HTML rendered by Servlet: here

Java in static page: here

Java injected by Servlet: here

There are three a, each linking to one of the examples we'll go through below in sections 4.1 through 4.4.

We also need to make sure that we've got our web.xml set up:

 index.html index.htm index.jsp ExampleOne com.baeldung.ExampleOne ExampleOne /ExampleOne 

A main note here is – how to correctly map each of our servlets to a particular servlet-mapping.Doing so associates each servlet with a specific endpoint where it can consumed! Now, we'll go through each of the other files below!

3.1. HTML Rendered in Servlet

In this example, we'll actually skip building a .jsp file!

Instead, we'll create a string representation of our markup and then write it to the GET response with PrintWriter after ExampleOne Servlet receives a GET request:

public class ExampleOne extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println( "" + "" + "" + "HTML Rendered by Servlet" + "" + "" + "
" + "

This page was rendered by the ExampleOne Servlet!

" + "" + "" ); } }

What we're doing here is injecting our markup through our servlet request handling directly. Instead of a JSP tag, we generate our HTML, along with any and all Java-specific data to be inserted, purely server-side without a static JSP!

Earlier, we reviewed the out object which is a feature of JspWriter.

Above, I used the PrintWriter object instead which writes directly to the response object.

JspWriter actually buffers the string to be written into memory which is then written to the response objects after the in-memory buffer is flushed.

PrintWriter is already attached to the response object. I've preferred to write directly to the response object in the examples above and below for those reasons.

3.2. Java in a JSP Static Content

Here we create a JSP file named ExampleTwo.jsp with a JSP tag. As seen above, this allows Java to be added directly into our markup. Here, we randomly print an element of a String[]:

 Java in Static Page Example 

Above, you'll see that variable declaration within JSP tags objects: typevariableName and an initialization just like regular Java.

I've included the above example to demonstrate how to add Java to a static page without making recourse to a specific servlet. Here, Java is simply added to a page and the JSP lifecycle takes care of the rest.

3.3. JSP With Forwarding

Now, for our final and most involved example! Here, we're going to use the @WebServlet annotation on ExampleThree which eliminates the need for servlet mappings in server.xml.

@WebServlet( name = "ExampleThree", description = "JSP Servlet With Annotations", urlPatterns = {"/ExampleThree"} ) public class ExampleThree extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String message = request.getParameter("message"); request.setAttribute("text", message); request.getRequestDispatcher("/ExampleThree.jsp").forward(request, response); } }

ExampleThree takes a URL parameter passed in as message, binds that parameter to the request object, and then redirects that request object to ExampleThree.jsp.

Thus, we've not only accomplished a truly dynamic web experience but we've also done so within an application containing multiple .jsp files.

getRequestDispatcher().forward() is a simple way to ensure that the correct .jsp page is rendered.

All the data bound to the request object sent its (the .jsp file's) way will then be displayed! Here's how we handle that last part:

 Java Binding Example 

You said: ${text}

Note the JSP tag added to the top of ExampleThree.jsp. You'll notice that I switched the JSP tags here. I'm using Expression Language (which I mentioned before) to render our set parameter (which is bound as ${text})!

3.4. Try It Out!

Now, we'll export our application into a .war to be launched and hosted in Tomcat 8! Find your server.xml and we'll update our Context to:

Which will allow us to access our servlets and JSP's on localhost:8080/spring-mvc-xml/jsp/index.jsp! Pick up a working copy over at: GitHub. Congrats!

4. Conclusion

We've covered quite a bit of ground! We've learned about what JavaServer Pages are, what they were introduced to accomplish, their lifecycle, how to create them, and finally a few different ways to implement them!

This concludes the introduction to JSP! Be well and code on!