13 - Introduction to JSP

13.1 JSP Overview

JSP (Java Server Pages)  is a Java view technology that runs on the server machine and capable of rendering dynamic views as compared to HTML which can render static content only.

JSP is easier to write for the people who are not very confident in writing Java programs

Internally all JSP are translated in to Java (Servlets) and compiled to get class files out of it.

JSP allow us to write complete Java logic inside a jsp using a special tags known as expressions, scriplets and declaratives as well as we can include all CSS , JS or any other client side technologies.

JSP should always be used to display the data to end user and not a good place to write a complete business logic in it.

Good Design approach is to divide the web application in a view and business logic processing parts and used servlets for business logic and JSP for view part.

In MVC design pattern,JSP is used  as VIEW part of it.

In all of our earlier chapters we were displaying content to the end user using PrintWriter object and passing on complete HTML content in it.

Any change in even small content or tag requires Servlets to compile to see the changes.

Alternatively, Servlet can forward the request to  JSP where we can have all the display logic which data to display in which style etc

13.2 Scriplets / Declarations / Expressions

As I mentioned in overview section, we can write complete java in a JSP inside special tags.

  1. Declaration – Declaration tag is used to define any methods or a member variables in a JSP. Syntax of Declaration is <!% %>
  1. Scriplets – We can write a Java code inside the scriplets and all the code written in a scriplets  goes to service() method . (JSP gets translated to Servlets internally). Syntax of scriplet is <% %>
  1. Expression- Expression tag is used to print the value of any variable defined either at a class level or in methods. Syntax of expression tag is <%= %>

 

We all know in Java programs , we need to import the libraries we need to use so in JSP also we need to import the libraries we need to use using below syntax

      <%@ page import=”java.util.*” %>

Note- In JSP we can use <!--   Comments-- > syntax for comments outside scriplets and declarations and java comments syntax //  in scriplets and declarations

Lets write introduction.jsp in WebContent directory  using above tags to display current time

<!DOCTYPE html>
<html>
<head>
<title>Introduction</title>
</head>
<%@page import="java.util.Date"%>
<body>
    <!--  Declaration Section  -->
    <%!String instanceVariable;
    public Date getCurrentTime() {
        return new Date();
    }%>
    <!--  Scriplet Section  -->
    <%
        String currentDate = getCurrentTime().toString();
    %>
    <!--  Expression to display the current date  -->
    <%=currentDate%>
</body>
</html>

Testing

Hit http://localhost:8080/HelloWorld/introduction.jsp

In above JSP,

  1.  we have used java.util.Date so imported it using <%@ page import=”java.util.Date” %> directive
  2. Created a instance variable and a instance method using declaration
  3. Created a local variable inside scriplet whose value is the value returned by the instance method
  4. Used expression tag to display the value
  5. Used comments

13.3 – Internal Details

As I mentioned that JSP is translated to Servlet and compiled by container so internally container will generate code something like below [This is for your understanding and not the exact code)

import java.util.Date;
public int instanceVariable;
public Date getCurrentTime() {
        return new Date();
    }
public void service()
{
    String currentDate = getCurrentTime().toString();
    PrintWriter writer = response.getWriter();
    Writer.println(currentDate);
}

Note –All code written inside scriplets goes inside service() method. 

13.4 Implicit Objects

You must be wondering if everything that can be done with Servlets, are possible with JSP as well then how can we get objects like request, response etc.

Answer is implicit objects. JSP provides a total 9 implicit objects (listed below)  which can be used inside scriplet.

13.4.1 request – this is HttpServletRequest object

13.4.2 response - This is the HttpServletResponse object

13.4.3 out- This is the PrintWriter object to send the response

13.4.4 session – This is the HttpSession object

13.4.5 applicaiton – This is ServletContext Object

13.4.6 config – This is ServletConfig object associated with JSP

13.4.7  pageContext- A PageContext instance provides access to all the namespaces associated with a JSP page, provides access to several page attributes, as well as a layer above the implementation details. Implicit objects are added to the pageContext automatically.

13.4.8 page – equivalent to “this” in Java means instance

13.4.9 exception –exception object

           

13.5 JSP and Servlet together

Web application is developed using both JSP and servlets. Servlets should be used to write business logic code and JSP for view purpose. This means there should be a way by which JSP and servlet can connect together.

JSP can invoke Servlet similar as we are doing with HTML in our sample examples using action attribute of form tag. There is no change in that.

Servlet can invoke JSP , the way servlet is invoking another servlet using RequestDispatcher Object. with only change of passing JSP name instead Servlet’s name.

Lets take an example to show how JSP and servlets can connect together along with the usage of implicit object.

Example will contains –

  1.  two JSP (login.jsp and home.jsp)
  2.  one servlet LoginServlet.
  3.  Login.jsp will take username and password and will pass these information to User Servlet
  4. User Servlet will find user’s details and send back to home.jsp where the user’s information will be displayed. Ideally user’s information should be pulled from Database but in this example we will add some dummy information and send back.
  1. Create login.jsp in WebContent directory.
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<form name="logonform" action="UserServlet" method="POST">
Username: <input type="text" name="username"/>
<br/>
Password:<input type="password" name="password"/>
<br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

  1. Add Servlet entry in web.xml
<servlet>
        <servlet-name>UserServlet</servlet-name>
        <servlet-class>com.servlet.tutorial.UserServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/UserServlet</url-pattern>
    </servlet-mapping>
  1. Write UserServlet Code- Servlet will add the dummy data if username is admin and password is password. Also how Servlet will invoke home.jsp is highlighted in below code.
package com.servlet.tutorial;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
    String username=request.getParameter("username");
    String password=request.getParameter("password");
// if user name is admin and password is password, we will send dummy data else no data
    if(username.equals("admin") && password.equals("password") )
    {
            String name="Admin Name";
            String address="Admin Address";
            // Add these information in request
            request.setAttribute("name", name);
            request.setAttribute("address", address);
            request.setAttribute("message", "Your personal details are -");
        }
        else
        {
            request.setAttribute("message", "No data found for given username and password ");
        }
            // Forward to home.jsp
        RequestDispatcher rd = request.getRequestDispatcher("home.jsp");
        rd.forward(request, response);
    }                    
}

  1. Write home.jsp in WebContent directory. Usage of request and out implicit variables are highlighted
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
    <%
        String message= request.getAttribute("message").toString();
        Object obj= request.getAttribute("name");
        String name = "";
        if(obj!=null)
        {
            name= obj.toString();
        }
        obj= request.getAttribute("address");
        String address = "";
        if(obj!=null)
        {
            address= obj.toString();
        }
            out.println(message);
            out.println("<br/>");
            out.println("Name :: " + name);
            out.println("<br/>");
            out.println("Password :: "+address);
%>
</body>
</html>

Testing –

Hit http://localhost:8080/HelloWorld/login.jsp and enter username as admin and password as password and Submit

Hit http://localhost:8080/HelloWorld/login.jsp and enter username password other than admin and  password and Submit

 

Like us on Facebook