Panduan untuk Halaman JavaServer (JSP)

Daftar Isi

  • 1. Ikhtisar
  • 2. Halaman JavaServer
  • 2.1. Sintaks JSP
  • 2.2. Isi Statis dan Dinamis
  • 2.3. Objek Implisit
  • 2.4. Objek Implisit Lainnya
  • 2.5. Arahan
  • 2.6. Petunjuk Halaman
  • 3.0. Tiga Contoh
  • 3.1. HTML Dirender di Servlet
  • 3.2. Java dalam Konten Statis JSP
  • 3.3. JSP Dengan Penerusan
  • 3.4. Cobalah!
  • 4. Kesimpulan

1. Ikhtisar

Halaman JavaServer (JSP) memungkinkan injeksi konten dinamis ke dalam konten statis menggunakan Java dan Java Servlets . Kita dapat membuat permintaan ke Java Servlet, melakukan logika yang relevan, dan membuat tampilan sisi server tertentu untuk digunakan di sisi klien . Artikel ini akan memberikan gambaran menyeluruh tentang Halaman JavaServer yang menggunakan Java 8 dan Jave 7 EE.

Kita akan mulai dengan menjelajahi beberapa konsep utama yang relevan dengan JSP: yaitu, perbedaan antara konten dinamis dan statis , siklus hidup JSP, dan sintaks JSP serta arahan dan objek implisit yang dibuat saat kompilasi!

2. Halaman JavaServer

Halaman JavaServer (JSP) memungkinkan data khusus Java diteruskan ke atau ditempatkan dalam tampilan .jsp dan digunakan di sisi klien.

File JSP pada dasarnya adalah file .html dengan beberapa sintaks tambahan, dan beberapa perbedaan awal kecil:

  1. yang .html akhiran diganti dengan jsp (itu dianggap sebagai .jsp filetype) dan
  2. tag berikut ditambahkan ke bagian atas elemen markup .html:

Mari kita bahas beberapa konsep utama di JSP.

2.1. Sintaks JSP

Ada dua cara untuk menambahkan kode Java ke .jsp. Pertama, kita dapat menggunakan sintaks Java Scriptlet dasar yang melibatkan penempatan blok kode Java dalam dua tag Scriptlet:

<% Java code here %>

Metode kedua khusus untuk XML:

 Java code here 

Yang terpenting, seseorang dapat menggunakan logika bersyarat di sisi klien dengan JSP dengan menggunakan klausa if , then , dan else lalu membungkus blok markup yang relevan dengan tanda kurung tersebut.

 Doodad! 

Hello!

Misalnya, jika doodad benar, kami akan menampilkan elemen div pertama, jika tidak kami akan menampilkan elemen p kedua !

2.2. Isi Statis dan Dinamis

Konten web statis adalah aset tetap yang digunakan secara independen dari permintaan RESTful, SOAP, HTTP, HTTPS, atau informasi lain yang dikirimkan pengguna.

Konten statis , bagaimanapun, tetap dan tidak diubah oleh input pengguna. Konten web dinamis adalah aset yang merespons, dimodifikasi oleh, atau berubah sehubungan dengan tindakan atau informasi pengguna!

Teknologi JSP memungkinkan pemisahan tanggung jawab yang bersih antara konten dinamis dan statis .

Server (servlet) mengelola konten dinamis dan klien (halaman .jsp aktual) adalah konteks statis di mana konten dinamis dimasukkan.

Mari kita lihat objek implisit yang dibuat oleh JSP dan yang memungkinkan Anda mengakses sisi server data yang relevan dengan JSP!

2.3. Objek Implisit

Objek implisit dibuat oleh mesin JSP secara otomatis selama kompilasi .

Objek implisit termasuk objek HttpRequest dan HttpResponse dan mengekspos berbagai fungsi sisi server untuk digunakan dalam servlet Anda dan untuk berinteraksi dengan .jsp! Berikut daftar objek implisit yang dibuat:

permintaan

permintaan milik kelas javax.servlet.http.HttpServletRequest . The permintaan objek mengekspos semua masukan data pengguna dan membuatnya serverside tersedia.

tanggapan

respon milik kelas javax.servlet.http.HttpServletResponse dan menentukan apa yang dikirimkan kembali ke sisi klien setelah permintaan dibuat.

Mari kita lihat lebih dekat objek implisit permintaan dan respons karena mereka yang paling penting dan paling sering digunakan.

Contoh di bawah ini menunjukkan metode servlet yang sangat sederhana, tidak lengkap, untuk menangani permintaan GET. Saya telah menghilangkan sebagian besar detail sehingga kami dapat fokus pada cara menggunakan objek permintaan dan respons :

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

Pertama, kita melihat bahwa objek request dan respon diteruskan sebagai parameter ke dalam metode yang membuatnya tersedia dalam cakupannya.

Kita bisa mengakses parameter permintaan menggunakan fungsi .getParameter () . Di atas, kami mengambil parameter pesan dan menginisialisasi variabel string sehingga kami dapat menggunakannya dalam logika sisi server kami. Kita juga bisa mengakses objek respon yang menentukan apa dan bagaimana data akan diteruskan ke tampilan.

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!