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!
GO TO FULL VERSION