Scriptlets inserts arbitrary code into servlet'

2019-09-11 04:58发布

问题:

Scriptlets let you insert arbitrary code into servlet's _jspService method.

Can anyone explain this statement with an example containing a block of code?

I am aware about syntactical stuff of JSP and Servlets, what I need to know is

  • In what context arbitrary code is used?

_jspService() is a method of JSP life cycle then,

  • What does it mean by servlet's method?

回答1:

A JSP is in fact transformed by the container into a Java class extending HttpServlet, that class is then compiled and executed exactly as a hand-coded servlet would be.

The code you have into the JSP is transformed into Java code that constitutes the _jspService method of the generated servlet. So, for example

<html>
<% String foo = "hello"; out.println(foo); %>

is transformed by the container, into something like

void _jspService(JspWriter out) {
    out.println("<html>");
    String foo = "hello"; out.println(foo);
}

So, whatever code you write into your scriptlets (arbitrary code) ends up in the _jspService method of the servlet created by the container from the JSP.