JSP/Servlet | JSP(Java Server Pages) | Running Multiple Lines of Code
Now we know that Java code in JSP is executed on the server side. However, what <%= ~ %> can do is only output the result of a single expression. If that were all we could do, it would be a little inconvenient. In many cases, you will need to execute longer blocks of code.
In such cases, use the <% ~ %> tag. If you write Java code between <% and %>, the written content is executed. It does not output the result; it only executes the code. If you need to output a result, you must write the output processing yourself.
Another thing to know is “import”. In Java, it is common to add import statements at the beginning so frequently used classes can be used by class name alone without specifying the package name. In JSP, this is specified with a page directive.
<%@ page import="class specification"%>
If you write it this way, the specified class can be used without the package name. Of course, you can also use a wildcard (*).
Now let’s modify the previous example a little.
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ page import="java.util.Calendar" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy MM dd");
String result = format.format(calendar.getTime());
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample jsp</title>
<style>
h1 {font-size:16pt; background:#AAFFAA; padding:5px; }
</style>
</head>
<body>
<h1>Sample jsp page</h1>
<p>This page is a sample.</p>
<p><% out.println(result); %></p>
</body>
</html>
After modifying it as shown above and running it again, you can confirm that today’s date is displayed. This time, SimpleDateFormat is used to display the Date in the specified format.
About the implicit object “out”
In this example, the formatted text is output not with <%= ~ %>, but with out.println(result);. What exactly is this “out”?
This is something specific to JSP and is called an “implicit object”. An implicit object is an object that can be used freely in JSP code without declaring anything.
This “out” is an instance of the JspWriter class. Simply put, you can think of it as a companion to the out in System.out. If you call output methods included in it, such as print and println, the content is output directly to the web page. This is used often, so remember it.