How a JSP is converted into a Servlet - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

How a JSP is converted into a Servlet

Share This

We have discussed earlier that a JSP file is converted to Servlet. Here with the following example, we will try to understand the conversion technique. During the conversion, JSP expressions are sent to the PrintWriter, so that the value of the expression is printed on the Web page. The lines of code written in JSP Scriptlet are added to the service() method. The variable declarations, which are written in JSP Declarations, are added to the generated Servlet as instance variables.


Hence, the variables, which are declared in JSP Scriptlet, are local variables to the service method. But the variables, declared in JSP Declarations, are added to the Servlet as instance variables.


We can't write any logical expressions in JSP Declarations as logical expressions can not be written in a Class (logical expressions can be written in methods only). 


Similarly, if you want to define a method, it should be written in JSP Declarations because, during interpretation, the code block will be added in Servlet as a method. We can't define any method within JSP Scriptlet because that code will be added in service() method but a method does not contain any other method definition.


The following code is self-explanatory, so read the comments carefully.

Source Code of index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <!-- The following line is added in generated Servlet class directly --> <%!int x = 10;%> <!-- The following block shows how to add a method in generated Servlet class --> <%!void print(int z) { System.out.print(z); // prints the value of z to server console }%> <!-- The following variable is added to the service method --> <% int y = 20; %> <!-- The following block of code is added to the service method --> <% int factorial = 1; for (int i = 1; i < 5; i++) { factorial *= i; } %> <!-- The following line prints the value of factorial on page. It's added to the service method using PrintWriter object. --> <%=factorial%> </body> </html>

Let's compare JSP and Servlet side by side.



Happy Exploring!

No comments:

Post a Comment