CodeGym/Java Course/Module 3. Java Professional/JSP: declarative way to define a servlet

JSP: declarative way to define a servlet

Available

1.1 Introduction to JSP

There are two popular ways to write a servlet: imperative and declarative . We have already dealt with the first one - this is, in fact, a Servlet. The second is called JSP (Java Server Pages), and we will get acquainted with it now.

Servlet JSP example:

<html>
    <body>
        <% out.print(2*5); %>
    </body>
 </html>

Not very similar to the classic Servlet we are used to, is it? This is true. JSP is an HTML page with Java code inserts (highlighted in green) .

You see, if you have a lot of Java code in a servlet and little HTML code, then you are more comfortable using a classic servlet . But what if you need a large HTML page in which only a couple of lines are changed by the server?

In this case, the simplest thing would be to create this HTML page and somehow execute the Java code on the server right in it.

1.2 Compiling JSPs

Let's look at another example:

<html>
  <body>
    <%
        double num = Math.random();
        if (num > 0.95) {
     %>
         <h2>You are lucky, user!</h2><p>(<%= num %>)</p>
    <%
        }
    %>
  </body>
</html>

We get a random number, and if it's greater than 0.95, we print the text "You're lucky, user!"

Java code is highlighted here in blue . Normal (not highlighted) - HTML code, and red - service tags , which help to understand where the Java code is and where the HTML is.

Do you notice something odd? The closing curly brace "}"is in another "code block". What is the right way to write such code? How does it even work?

The answer will be super simple :)

The web server, after it finds a JSP file, compiles it into a classic servlet. Based on the above JSP page, this Servlet will be generated:

public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)  throws Exception {
    PrintWriter out = response.getWriter();
    out.print("<html> ");
    out.print("<body>");
        double num = Math.random();
        if (num > 0.95) {
            out.print("<h2>You're lucky user! </h2><p>(" + num + ")</p>");
        }
    out.print("</body>");
    out.print("</html>");
    }
}

The web container just generated the servlet code, where the HTML turned into text and the Java code inserts became regular Java code!

Comments (1)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
Thomas
Level 41 , Bayreuth, Germany
16 March, 09:01
In reality the generated code doesn't look like the given example. It is more complex and defines some variables that are worth mentioning.
public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent {

    private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();

    private static java.util.List <String> _jspx_dependants;

    private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;

    public java.util.List<String> getDependants() {
        return _jspx_dependants;
    }

    public void _jspService(HttpServletRequest request, HttpServletResponse response)
    throws java.io.IOException, ServletException {

        PageContext pageContext = null;
        HttpSession session = null;
        ServletContext application = null;
        ServletConfig config = null;
        JspWriter out = null;
        Object page = this;
        JspWriter _jspx_out = null;
        PageContext _jspx_page_context = null;

        try {
            response.setContentType("text/html; charset=UTF-8");
            response.setHeader("X-Powered-By", "JSP/2.3");
            pageContext = _jspxFactory.getPageContext(this, request, response,
            null, true, 8192, true);
            _jspx_page_context = pageContext;
            application = pageContext.getServletContext();
            config = pageContext.getServletConfig();
            session = pageContext.getSession();
            out = pageContext.getOut();
            _jspx_out = out;

           out.write("\n");
           // ... here generated code
That's the first lines that the jsp engine Jasper is creating when compiling such code. You can see that some variables got generated: pageContext, session, application, config, out, page, exception, request, response These can be used inside your code without you needing to declare them on your own.