2.1 JSP directives

Since we found out that the JSP file is converted into a regular servlet, then you can write normal Java code in it. And in this Java code, you can use various classes (Math from the example). This is even better! But we can see that all the code has been moved to a doGet()servlet method. And this immediately raises several questions:

  • How to make it so that the code is moved to the method doPost()?
  • How to add your own code to the method init()?
  • How in the end to register class imports?

Great questions, and, of course, they have an answer - JSP directives. All non-HTML code within a JSP must be enclosed in special brackets <%and %>. All JSP directives are given by a template:

<%@ directive %>

Here is a list of the most popular page directive attributes:

Example Description
1 import <%@ page import="java.util.Date" %> Imports a class
2 contentType <%@ page contentType=text/html %> Sets contentType
3 extends <%@ page extends="Object" %> You can set the base class
4 info <%@ page info="Author: Peter Ivanovich; version:1.0" %> Sets data for getServletInfo()
5 buffer <%@ page buffer="16kb" %> Sets the size of the response buffer
6 language <%@ page language="java" %> Specifies the language, default is Java
7 isELIgnored <%@ page isELIgnored="true" %> Allows you to disable EL scripts
8 isThreadSafe <%@ page isThreadSafe="false" %> Points to threadsafe
9 autoFlush <%@ page autoFlush="false" %> Manages buffer writes
10 session <%@ page session="false" %> You can disable the session for the page
eleven pageEncoding <%@ page pageEncoding="UTF-8"%> You can set the page encoding
12 errorPage <%@ page errorPage="errorpage.jsp" %> You can set an error page

2.2 Imports

Let's add a few imports to our JSP file for fun and define a base class.

JSP file example:


    <%@ page import="java.util.Date" %> 
    <%@ page import="java.lang.Math" %> 
    <%@ page extends="com.codegym.MyHttpServlet" %> 
 
    <html> 
    <body> 
    <%
        double num = Math.random();
        if (num > 0.95) {
     %>
         <h2>You are lucky, user!</h2><p>(<%= num %>)</p>
    <%
    }
    %> 
  </body> 
   </html> 

And this is what will come of it:

import java.util.Date;
import java.lang.Math;

public class HelloServlet extends com.codegym.MyHttpServlet {
    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> ");
    }
}

Works. Great!