Servletsin JSP

Under construction… Please be patient and feel free to make corrections or suggestion. After all, isn’t that what a Wiki is for?

Servlets and Java Server Pages (JSP)

What you will need:

  1. Application Server - something like Websphere Application Server, or Apache Tomcat, or even something else. The beauty is that Servlets are portable from platform to platform.
  2. Java Programming Knowledge - or at least a general working knowledge of object oriented coding practices.

First lets take a look at the basic structure of a Servlet.

package tutorialPackage;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SimpleServlet extends HttpServlet
{
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		try
		{

		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doGet(request,response);
	}
}

Lets start at the beginning and see what is going on. The package reference tells us which package this class belongs to in our project. All classes you create will belong to a package.

Next we see a series of import statements. These import the java classes that you will need to support your Servlet. After that you see the actual Servlet code itself. The first line is very important to the success of your Servlet. You need to extend this class so that it inherits the basic properties of the HttpServlet class that you imported. Next we need to make two methods to handle the http requests and responses for our Servlet. There are two ways to make a request is http. One way is to use a Get and the second way is to use a Post. Both of these cases should be covered so that your Servlet is as portable and flexible as possible. In this example as in most basic uses of Servlets you probably want to do the same thing no matter if it is a Post or a Get. Its generally recommended that a Get statement be used when retrieving data instead of a Post. I’ll just let it at that since that can be a top for another day. In order to keep from duplicating your code you just need to call your doGet() method from inside of your doPost() and no matter which request is sent to the Servlet it will now go right to the doGet() and run its code.


This page may have a more recent version on pmwiki.org: PmWiki:ServletsinJSP, and a talk page: PmWiki:ServletsinJSP-Talk.