Monday, June 20, 2016

Translating JSP scriptlet code to servlet service life cycle method

Scriptlets are nothing but java code enclosed within <% and %> tags. JSP container moves the statements enclosed in it to _jspService()method while generating servlet from JSP. The reason of copying this code to service method is: For each client’s request the _jspService() method gets invoked, hence the code inside it executes for every request made by client.
Syntax of Scriptlet:
[code language=”java”]<% Executable java code%>[/code]

JSP to Servlet transition for Scriptlet –

As I stated in my previous tutorials that JSP doesn’t get executed directly, it first gets converted into a Servlet and then Servlet execution happens as normal. Also, I explained in first para that while translation from JSP to servlet, the java code is copied from scriptlet to _jspService() method. Lets see how that happens.
Sample JSP code:
[code language=”html”]

Sample JSP


<% myMethod();%>
[/code]
Note: Semicolon at the end of scriptlet.
Corresponding translated Servlet code for above JSP code:
[code language=”java”]
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession();
JspWriter out = response.getWriter();
out.println("

Sample JSP

");
myMethod();
}[/code]

No comments:

Post a Comment