JAVA Servlets and JSp

To see a good tutorial on JSP go to this Site: Java Server Pages Tutorial

Before reading this tutorial you must be familiar with Java, Html and web applications.

DIFFERENCES BETWEEN SERVLETS AND JSP (Java Server Pages)

A web Application can be divided basically in 2 big parts or sections, the Application layer which encapsulates the business logic and backed processing, and the Presentation Layer which function is to present the user with a Graphic User Interface (GUI) to see the results of the backend processing. One goal in Web Applications Development is to "separate" the application layer from the presentation layer as much as possible to achieve modular and robust systems.

- Java Servlets are mostly used for backend processing tasks, such as connections with databases and other servers, hard programming and business logic implementation. Those activities defines the Application Layer of a System. Java Servlets are Java Classes (compiled into .class files) that are accessible through the web (using a web server like tomcat or resin). Servlets must extend the HttpServlet abstract class.

- Java Server Pages (JSP) basic purpose was to address the presentation layer of web applications and NOT the application business logic or Backend Logic. JSP syntax consists of tags intermixed with html tags to generate the appropriate user interface dynamically. In the end, JSP are compiled into servlets.

In theory you must use JSP pages to show the results of what servlets do in the backend. In practice, many people forget about this separation and end up putting a lot of unnecessary code in JSP pages, making web applications hard to maintain and update.

There are many methodologies to try achieve this separation from view (presentation layer) and model (application layer). One of those is the Model-View-Controller (MVC) Architecture, as described in the java blueprints for MVC

One basic way to implement the MVC architecture is to have a servlet called "controller" (any name will do though) to listen for client requests. On each request, the controller decides which module to call based on the parameters received. After that module (servlet) is finished the application control is passed to another module (usually a JSP) to display the results to be shown to the client in the form of HTML.

This is very convenient since it allows back-end programmers to focus on the development of modules that implement the business logic (without being concerned about such issues as front-end design). On the other hand front-end and design-oriented programmers can design the user interface functionality, worrying only on how to display the results and NOT in how to generate the results.


COMMON STRUCTURE OF A SERVLET

A Servlet extends the HttpServlet abstract class. By doing that, the "servlet container" makes this "servlet" accessible to the web. By "Servlet Container" are web servers such as Tomcat and Resin that are able to understand servlets and JSP syntax. Basically, a java servlet has the following structure:

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
  
public class hello extends HttpServlet{

    public void doGet(HttpServletRequest request, HttpServletResponse response) 
                                        throws IOException { 
		 
       response.setContentType("text/html");
       PrintWriter out = response.getWriter(); 
       out.print("Hello World from GET method ");

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) 
                                        throws IOException { 
		 
       response.setContentType("text/html");
       PrintWriter out = response.getWriter(); 
       out.print("Hello World from POST method ");

    }
}
  

A servlet has the methods doGet and doPost (inherited from HttpServlet) to manage user requests. Basically you put the code that will control the behaviour of the servlets in those 2 methods. Alternatively you can custom initialize and end a servlet by overriding the methods init() and destroy()

There's no much more to say about servlets in this tutorial since servlets are basically java classes that have the properties inherited from HttpServlet, and if you are familiar with java just read the javax.servlet.http package documentation to see what servlets can do. For instance, to access the session a servlet can use the request object it receives in the doPost or doGet and execute an request.getSession().

For more detailed info on servlets read this tutorial: Servlet general guide

RUNNING A SERVLET IN TOMCAT

You must be familiar with TOMCAT or RESIN contexts. TOMCAT and RESIN are example of "servlet containers", that is, servlets which can understand JSP syntax and Servlets and make them accessible through the web.
Servlets usually are store in the folder "webapps" in the tomcat folder structure. Put your servlets compiled classes (*.class) in the "WEB-INF/classes" folder of your context.

Now, to make your servlets accessible from the web you must declare them in the "web.xml" file of your context. For more information on how to setup tomcat to run a servlet read this section, where i briefly explain how to setup tomcat and run a servlet.


COMMON STRUCTURE OF A JSP PAGE

As mentioned above, JSP pages are special tags intermixed with html tags. A JSP page define certain objects that are accessible always, like: request, out, response, application and session.

For instance, to print something you can do:

<html><title>TEST</title>
<body>
<%= "Hello World %>
</body>
</html>

Then save this in a file with JSP extension. The first time TOMCAT or RESIN (servers) see this page they need to convert it to a servlet !

Let's say now we would like to access a variable that a servlet put in the session. A JSP page would do the following:

<%
  Object myobject = session.getAttribute("anobject");
  out.println("The backend application returned this object: " + myobject.toString() );
%>


MORE DETAILED EXAMPLE OF JSP

I will assume there's a session variable of type User. User is a simple java bean (java class) with the methods getFullName() and sUserLoggedIn()

File: test1.jsp

 <%@ page contentType="text/html; charset=iso-8859-1" language="java" 
import="java.sql.*" i
mport="java.util.*"
errorPage="myerror.jsp" %>

<!-- This file inclusion will check for a user login status -->
<%@ include file="../checklogin.jsp" %>
<html><head><title>Test of Page</title></head></title> <body> <p> Welcome again <%= user.getFullName() %> </p> <p>
<% Object myobject = session.getAttribute("anobject"); out.println("The backend application returned this object: " + myobject.toString() ); %> </p>
</body> </html>

File: checklogin.jsp

<jsp:useBean class="bean.User" id="user" scope="session"></jsp:useBean>
<%
if ( user.isUserLoggedIn() == false ){

response.sendRedirect("index.jsp");
return;
}
%>


You can learn the JSP syntax by going to this Java Server Pages Tutorial

You can learn the JSP syntax by going to this Java Server Pages Tutorial

There is something called JSTL (JavaServer Tag Library) which are tags with a predefined behavior. So, before writing any JSP it would be wise to see if there exists a JSTL tag that can do the same thing!

HOW TO EXECUTE YOUR JSP files

In order to execute your jsp code put your files in your context folder. If you are not sure what a context is, a context is a folder where your web application files are stored. For more information read this section, that explains how to setup tomcat and run a servlet.

The first time the JSP page is accessed it will take a little longer because the JSP will be compiled into a servlet internally. After that, future accesses to the JSP page must be faster.

Every time you modify your JSP you must either restart the TOMCAT server or change a property in the "server.xml" file of the TOMCAT server (reload option), that will allow TOMCAT to detect changes without restarting. You must disable this feature in production time tough.

 

BEST PRACTICES TO DEVELOP JAVA WEB APPLICATIONS

- Use java beans
- Use Custom Tags
- Find if the custom tag exists before rewriting it ( ex: in Standard Tag Library (JSTL) ).
- Use JSTL Expression Language
- Use MVC (model view controller) . See Apache Struts
- Find about Java Faces
- Create a connection Pool for DB Connections


REFERENCE AND SUGGESTED LINKS

  • Java Enterprise API, See documentation
  • Java Standard API,  See documentation
  • JAVA documentation for J2EE technologies Here
  • Designing Entrerprise Applications with J2EE Here
  • Best Practices for Java Servlets/ Jsp here
  • JavaServer Pages: A Developer's Perspective here
  • JSP Tutorial here
  • General Servlet/JSP tutorial here