How to write java code in jsp page

In this tutorial you will learn how you can write the java code in jsp file, as discussed in pervious tutorials that you can write the html as well java code also in jsp page.

To write the java code in jsp file you have to follow some rules in jsp, we will discuss these rules in details. JSP comes up with four type of block where you can write the java code. See the below example of code of jsp file, the jsp file name is displayDate.jsp.

Example of displayDate.jsp

<%@page import="java.util.Date"%>

<h3>Hello everybody!</h3>

<%!int counter;%>
<%
	counter++;
%>
Today date is : <%=new Date()%><br />

This page access by : <%=counter%> times.

This jsp has all four types of block where you can write the java code. The detail of each block and its use in jsp is explained below.

As you know that web server will generate the servlet of each jsp page at run time, and the each java code which is written in jsp also will go in generated servlet.

JSP directives

The JSP directive is the block of code where you can import the packages, include other pages in current jsp and define tag library. We will learn about the JSP directive in detail in different tutorial.

In the above example we have use the page directive for import the java.util.Date file.

<%@ page import="java.util.Date"%>

The generated code of JSP directive will go to on top of generated servlet.

JSP declaration

The JSP declaration is the block of code where you can write java code which has to go as global variable for generated servlet.

The code in JSP declaration will in parallel of service method, so you can write any method, or define the class variables in JSP declaration.

In this example we have declare the below code.

<%! int counter;%>

So it will declare the instance int variable named counter.

JSP Scriptlets

The JSP scriptlets is the block of code where you can write any logic using other variable or any stuff, the code written in JSP scriptlets will go as part of service method.

In this example we have written the below code which increment the counter for each time it has been requested.

<%
	counter++;
%>

JSP Expression

The JSP expression is the block of code which has to as part of output in jsp. i.e. the code written in JSP expression will go as parameter of the out.write() method, and it will show as output is jsp.

In this example the below code will go as the out.write() method.


Today date is : <%=new Date()%>

<br />

This page access by : <%=counter%> times.

The generated servlet of displayDate.jsp is looks like below code.

The below example show you the generated Servlet code, you can see how the code written in JSP converted in java.

package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.Date;

public final class displayDate_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

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

  private static java.util.List _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.AnnotationProcessor _jsp_annotationprocessor;

  public Object getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig()
    .getServletContext()).getExpressionFactory();
    _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext()
    .getAttribute(org.apache.AnnotationProcessor.class.getName());
  }

  public void _jspDestroy() {
  }

  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");
      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("

Hello everybody!

\r\n"); out.write("\r\n"); out.write('\r'); out.write('\n'); counter++; out.write("\r\n"); out.write("\r\n"); out.write("Today date is : "); out.print(new Date()); out.write("\r\n"); out.write("
\r\n"); out.write("This page access by : "); out.print(counter); out.write(" times.\r\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }