Java Servlets Lec 27
Creating a Simple Web Application in Tomcat
Tomcat Directory Structure myapp
Tomcat Setup Folder for HTML and JSP pages Folder for servlet and other java classes
Servlet Types Servlets are based on two main packages javax.servlet javax.servlet.http GenericServlet For writing protocol independent servlets HttpServlet Extends from GenericServlet class Adds functionality for writing HTTP specific servlets
Servlet class hierarchy Object GenericServletServletResponse HttpServletRequest ServerRequest HttpServletHttpServletResponse javax.servlet javax.servlet.http
Writing Servlet Every servlet must implement the javax.servlet.Servlet interface Contains the servlet’s life cycle methods etc. These are implemented by GenericServlet and HttpServlet classes Extend your servlet from one of these classes and add your own functionality public class MyServlet extends GenericServlet public class HelloServlet extends HttpServlet
Types of HTTP Requests Get Post Delete Options Put Trace
How HTTP Sends Request Client Server Servlets Some HTTP request types Get -- Attr/Val pairs attached after ? of URL E.g. Post -- Attr/Val pairs attatched with the request body
HTTP Request Example Request parameters etc
Writing Servlet Steps for making a HelloWorldServlet 1. Create a directory structure for your application (myapp). This is a one time process for any application 2. Create a HelloWorldServlet source file by extending this class from HttpServlet and override your desired method 3. Compile it (If compiler complains of not having required packages, check your class paths)
Writing Servlet Steps for making a HelloWorldServlet 1. Place the class file in the classes folder of your webapplication. (myapp) If you are using packages (recommended) then create a complete directory structure under classes folder 2. Create a deployment descriptor ( web.xml ) and put it inside WEB- INF folder 3. Restart your server, if already running 4. Access your application using Web browser
HelloServlet Example Code
HelloWorldServlet import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorldServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println(“Hello World!”); }
web.xml HelloWorldServlet HelloWorldServlet /myfirstservlet
Compiling and Invoking Servlets Compile HelloWorldServlet.java using javac command Put HelloWorldServlet class in install_dir/webapps/myapp/WEB-INF/classes Put web.xml file in install_dir/webapps/myapp/WEB-INF Invoke your servlet by writing following command in the web browser
Lets do it LIVE
Free Servlet and JSP Engines Apache Tomcat Allaire/Macromedia JRun New Atlanta ServletExec Causho’s Resin