Show List

JSP architecture and lifecycle

JSP (JavaServer Pages) follows the Model-View-Controller (MVC) architecture pattern, which separates the application logic (Model), presentation layer (View), and user interaction (Controller). Here is a high-level overview of the JSP architecture and lifecycle:

  1. The client sends a request to the server for a JSP page.
  2. The JSP page is first translated into a servlet by the JSP container.
  3. The translated servlet is then compiled into bytecode.
  4. The compiled servlet is loaded and executed by the JSP container to generate the HTML response.
  5. The generated HTML response is sent back to the client.

Now, let's take a look at a simple JSP example to understand the lifecycle in more detail:

First, create a new JSP file named "example.jsp". Here's the content of the file:

jsp
Copy code
<html> <body> <% String message = "Hello, JSP!"; out.println(message); %> </body> </html>

When the client sends a request to the server for the "example.jsp" page, the following steps are performed:

  • The JSP container translates the JSP page into a servlet class. The translated code might look like this:
java
Copy code
public class example_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { // Generated servlet code public void _jspService(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { JspWriter out = null; // Set response content type response.setContentType("text/html"); // Get JSP writer out = _jspx_page_context.pushBody(); // Business logic try { String message = "Hello, JSP!"; out.println(message); } catch(Exception ex) { out.println("Exception: " + ex); } // Finalize JSP writer out = _jspx_page_context.popBody(); } }
  • The servlet class is compiled into bytecode.
  • The compiled servlet is loaded and executed by the JSP container to generate the HTML response. The output might look like this:
html
Copy code
<html> <body> Hello, JSP! </body> </html>
  • The generated HTML response is sent back to the client.

    Leave a Comment


  • captcha text