Guide till JavaServer Pages (JSP)

Innehållsförteckning

  • 1. Översikt
  • 2. JavaServer-sidor
  • 2.1. JSP-syntax
  • 2.2. Statiska och dynamiska innehåll
  • 2.3. Implicita objekt
  • 2.4. Andra implicita objekt
  • 2.5. Direktiv
  • 2.6. Siddirektiv
  • 3.0. Tre exempel
  • 3.1. HTML återges i Servlet
  • 3.2. Java i ett JSP-statiskt innehåll
  • 3.3. JSP med vidarebefordran
  • 3.4. Testa!
  • 4. Slutsats

1. Översikt

JavaServer Pages (JSP) tillåter dynamisk innehållsinjicering i statiskt innehåll med Java och Java Servlets . Vi kan göra förfrågningar till en Java Servlet, utföra relevant logik och göra en specifik vy på serversidan som ska konsumeras på klientsidan . Den här artikeln ger en grundlig översikt över JavaServer-sidor med Java 8 och Jave 7 EE.

Vi börjar med att utforska några viktiga begrepp som är relevanta för JSP: nämligen skillnaden mellan dynamiskt och statiskt innehåll, JSP-livscykeln och JSP-syntaxen samt direktiv och de implicita objekten som skapas vid sammanställning!

2. JavaServer-sidor

JavaServer Pages (JSP) gjorde det möjligt för Java-specifika data att skickas till eller placeras i en .jsp-vy och konsumeras på klientsidan.

JSP-filer är i huvudsak Html-filer med lite extra syntax och ett par mindre initiala skillnader:

  1. den .html suffix ersätts med .jsp (det anses en .jsp filtyp) och
  2. följande tagg läggs till överst i HTML-markeringselementen:

Låt oss gå igenom några av de viktigaste begreppen i JSP.

2.1. JSP-syntax

Det finns två sätt att lägga till Java-kod till en .jsp. Först kan vi använda grundläggande Java Scriptlet-syntax som innebär att Java-kodblock placeras i två Scriptlet-taggar:

<% Java code here %>

Den andra metoden är specifik för XML:

 Java code here 

Viktigt kan man använda villkorslogik client med JSP med om , , och annars klausuler och sedan linda de relevanta block av uppmärkning med dessa konsoler.

 Doodad! 

Hello!

Till exempel, om doodad är sant, skulle vi visa det första, div- elementet annars skulle vi visa det andra, p- elementet!

2.2. Statiska och dynamiska innehåll

Statiskt webbinnehåll är anläggningstillgångar som konsumeras oberoende av RESTful, SOAP, HTTP, HTTPS-förfrågningar eller annan användarinlämnad information.

Statiskt innehåll är dock fixat och modifieras inte av användarens ingångar. Dynamiskt webbinnehåll är de tillgångar som svarar på, modifieras av eller ändras mot bakgrund av användaråtgärder eller information!

JSP-teknik möjliggör en ren separering av ansvarsområden mellan dynamiskt och statiskt innehåll.

Servern (servlet) hanterar det dynamiska innehållet och klienten (den faktiska .jsp-sidan) är det statiska sammanhang som dynamiskt innehåll injiceras i.

Låt oss ta en titt på de implicita objekten som skapas av JSP och som låter dig komma åt JSP-relevant dataserversida!

2.3. Implicita objekt

Implicita objekt genereras automatiskt av JSP-motorn under kompileringen .

Implicita objekt inkluderar HttpRequest och HttpResponse- objekten och exponerar olika funktioner på serversidan för användning i din servlet och för interaktion med din .jsp! Här är listan över implicita objekt som skapas:

begäran

begäran tillhör klassen javax.servlet.http.HttpServletRequest . Den begäran objektet exponerar alla användardata ingångar uppgifter och gör den tillgänglig server.

svar

svaret tillhör klassen javax.servlet.http.HttpServletResponse och avgör vad som skickas tillbaka klientsidan efter att en begäran har gjorts.

Låt oss titta närmare på förfrågan och svara på implicita objekt eftersom de är de viktigaste och mest använda.

Exemplet nedan visar en mycket enkel, ofullständig servletmetod för att hantera GET-förfrågningar. Jag har utelämnat de flesta detaljerna så att vi kan fokusera på hur vi använder förfrågan och svarsobjekten :

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

Först ser vi att förfrågnings- och svarsobjekten skickas in som parametrar till metoden som gör dem tillgängliga inom dess räckvidd.

Vi kan få åtkomstparametrar med funktionen .getParameter () . Ovan fäster vi meddelandeparametern och initierar en strängvariabel så att vi kan använda den i vår logik på serversidan. Vi kan även få tillgång till svars föremål som bestämmer vad och hur data skickas i vyn kommer att bli.

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!