Handbuch zu JavaServer Pages (JSP)

Inhaltsverzeichnis

  • 1. Übersicht
  • 2. JavaServer-Seiten
  • 2.1. JSP-Syntax
  • 2.2. Statischer und dynamischer Inhalt
  • 2.3. Implizite Objekte
  • 2.4. Andere implizite Objekte
  • 2.5. Richtlinien
  • 2.6. Seitenanweisungen
  • 3.0. Drei Beispiele
  • 3.1. In Servlet gerendertes HTML
  • 3.2. Java in einem statischen JSP-Inhalt
  • 3.3. JSP mit Weiterleitung
  • 3.4. Versuch es!
  • 4. Fazit

1. Übersicht

JavaServer Pages (JSP) ermöglicht die dynamische Injektion von Inhalten in statische Inhalte mithilfe von Java- und Java-Servlets . Wir können Anforderungen an ein Java-Servlet stellen, relevante Logik ausführen und eine bestimmte Ansicht serverseitig rendern, um sie clientseitig zu verwenden . Dieser Artikel bietet einen umfassenden Überblick über JavaServer Pages mit Java 8 und Jave 7 EE.

Wir werden zunächst einige für JSP relevante Schlüsselkonzepte untersuchen: den Unterschied zwischen dynamischen und statischen Inhalten, den JSP-Lebenszyklus und die JSP-Syntax sowie Anweisungen und die impliziten Objekte, die beim Kompilieren erstellt wurden!

2. JavaServer-Seiten

Mit JavaServer Pages (JSP) konnten Java-spezifische Daten in eine JSP-Ansicht übergeben oder dort platziert und clientseitig verwendet werden.

JSP-Dateien sind im Wesentlichen HTML-Dateien mit einer zusätzlichen Syntax und einigen geringfügigen anfänglichen Unterschieden:

  1. Das .html- Suffix wird durch .jsp (es wird als .jsp-Dateityp betrachtet) und ersetzt
  2. Das folgende Tag wird oben in die HTML-Markup-Elemente eingefügt:

Lassen Sie uns einige der Schlüsselkonzepte in JSP durchgehen.

2.1. JSP-Syntax

Es gibt zwei Möglichkeiten, einem .jsp Java-Code hinzuzufügen. Erstens können wir die grundlegende Java Scriptlet-Syntax verwenden, bei der Java-Codeblöcke in zwei Scriptlet-Tags eingefügt werden:

<% Java code here %>

Die zweite Methode ist spezifisch für XML:

 Java code here 

Wichtig ist , dass eine bedingte Logik client mit JSP verwenden , indem Sie wenn , dann , und anderen Klauseln und dann mit diesen Klammern der entsprechenden Blöcke von Markup - Verpackung.

 Doodad! 

Hello!

Wenn zum Beispiel Doodad wahr ist, würden wir das erste div- Element anzeigen, andernfalls würden wir das zweite p- Element anzeigen !

2.2. Statischer und dynamischer Inhalt

Statische Webinhalte sind Sachanlagen, die unabhängig von RESTful-, SOAP-, HTTP-, HTTPS-Anforderungen oder anderen vom Benutzer übermittelten Informationen verwendet werden.

Der statische Inhalt ist jedoch festgelegt und wird nicht durch Benutzereingaben geändert. Dynamische Webinhalte sind solche Assets, die auf Benutzeraktionen oder -informationen reagieren, von diesen geändert werden oder diese ändern.

Die JSP-Technologie ermöglicht die saubere Trennung von Verantwortlichkeiten zwischen dynamischen und statischen Inhalten.

Der Server (Servlet) verwaltet die dynamischen Inhalte und der Client (die eigentliche JSP-Seite) ist der statische Kontext, in den dynamische Inhalte eingefügt werden.

Werfen wir einen Blick auf die impliziten Objekte , die von JSP erstellt werden und die Ihnen den Zugriff auf JSP-relevante Datenserver ermöglichen!

2.3. Implizite Objekte

Implizite Objekte werden von der JSP-Engine beim Kompilieren automatisch generiert .

Implizite Objekte umfassen die Objekte HttpRequest und HttpResponse und stellen verschiedene serverseitige Funktionen zur Verwendung in Ihrem Servlet und zur Interaktion mit Ihrer .jsp! Hier ist die Liste der impliziten Objekte , die erstellt werden:

Anfrage

Anfrage gehört zur Klasse javax.servlet.http.HttpServletRequest . Das Anforderungsobjekt macht alle Benutzereingabedaten verfügbar und stellt sie serverseitig zur Verfügung.

Antwort

Die Antwort gehört zur Klasse javax.servlet.http.HttpServletResponse und bestimmt, was nach einer Anforderung clientseitig zurückgegeben wird.

Schauen wir uns die impliziten Objekte für Anforderungen und Antworten genauer an, da sie die wichtigsten und am häufigsten verwendeten sind.

Das folgende Beispiel zeigt eine sehr einfache, unvollständige Servlet-Methode zur Verarbeitung von GET-Anforderungen. Ich habe die meisten Details weggelassen, damit wir uns auf die Verwendung der Anforderungs- und Antwortobjekte konzentrieren können:

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

Zunächst sehen wir, dass die Anforderungs- und Antwortobjekte als Parameter an die Methode übergeben werden, um sie innerhalb ihres Bereichs verfügbar zu machen.

Wir können mit der Funktion .getParameter () auf Anforderungsparameter zugreifen . Oben fangen wir den Nachrichtenparameter und initialisieren eine Zeichenfolgenvariable, damit wir sie in unserer serverseitigen Logik verwenden können. Wir können auch auf das Antwortobjekt zugreifen, das bestimmt, wie und wie die in die Ansicht übergebenen Daten aussehen.

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!