Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC 2720 Building Web Applications

Similar presentations


Presentation on theme: "CSC 2720 Building Web Applications"— Presentation transcript:

1 CSC 2720 Building Web Applications
Java Servlet (Part 1) The Basics

2 Overview of Server-Side Scripting
Client sends a request via HTTP protocol A HTTP request consists of A request method: GET, POST, HEAD, PUT, etc. A URI that identifies the requested resource Header fields A body (which can be empty) Web server locates the corresponding server-side script and dispatches the HTTP request to the script. The server-side script processes the data embedded in the HTTP request and produces a HTTP response. The web server returns the generated HTTP response to the client.

3 Server-Side Scripting with Java Servlet
Servlets are the Java platform technology of choice for extending and enhancing Web servers. A servlet is a module of Java code that is executed at the server side to process a request and generates a response based on that request. A servlet is not a standalone Java program nor it is a CGI-script written in Java. A servlet is an object with a specific interface and it can only be "executed" in a special environment known as servlet container. The Servlet technology offers a framework to write, deploy, and run servlets. It also serves as a foundation for other Java-based server-side technologies. e.g., JSP and JSF.

4 Servlet Application Architecture
HTTP Request Servlet Container Browser HTTP Response Static Content HTTP Request HTTP Server Browser Static Content HTTP Response Servlet Container Servlet

5 Servlet Container A servlet container is a specialized web server or a component of a web server that supports servlet execution. It is responsible for Managing the lifecycle of servlets (load, initialize, dispatch requests, destroy, etc.) Mapping a URL to a particular servlet Providing access controls to the hosted resources Providing services defined in the Servlet API such as managing sessions, etc.

6 The Tomcat Container Apache Tomcat 6.0
Supports Servlet 2.5 and JavaServer Pages 2.1 The one bundled with NetBeans 6.0 is version If you want to test your Servlets (without NetBeans), typically you have to Install and configure the Tomcat web server Set environment variables such as CLASSPATH Create proper directory structure for your web applications

7 How a Servlet Work Receive Request Send Response Is servlet loaded? up to date? Load Servlet Process Request No Yes Loaded by the container the first time a servlet is requested Handle the request Resides in memory and waits for future requests A servlet may get reloaded if modified

8 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 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( "<html><head><title>Hello World Servlet</title>" + "</head><body>" + "Hello World" + "</body></html>" ); out.close(); } A servlet that output "Hello World".

9 Writing a Servlet Create a public class as a subclass of javax.servlet.http.HttpServlet Import the Java Servlet packages javax.servlet.* javax.servlet.http.* Override one or more doXXX() methods to process HTTP request and to produce HTTP response Typically, we override doGet(), doPost(), or both

10 Writing a Servlet Within the doGet() or doPost() methods, we typically perform the following tasks: Retrieve the data from HTTP request e.g.: Form data, parameters encoded in the URL, cookies, HTTP header fields Process the retrieved data Generate the content of the HTTP response: e.g.: Add header fields, set cookies, generate HTML codes, etc.

11 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletEx1 extends HttpServlet { public void doGet( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException { // Retrieving value of parameters named "x" and "y" String x = req.getParameter("x"); String y = req.getParameter("y"); String sum = "Undefined"; // Process the data (calculate the sum) try { int v1 = Integer.parseInt(x); int v2 = Integer.parseInt(y); sum = "" + (v1 + v2); // Store the result as string } catch (Exception e) { } A servlet that adds the value of two parameters.

12 PrintWriter out = res.getWriter();
out.println( "<html><head><title>ServletEx1: Adding 2 #'s</title>" + "</head><body>" ); out.println("Value of x is: " + x + "<br />"); out.println("Value of y is: " + y + "<br />"); out.println("Their sum is: " + sum + "<br />"); out.println("</body></html>"); out.close(); } // End of doGet() } // end of class ServletEx1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

13 Getting Parameters Instance methods of HttpServletRequest for retrieving parameter values: String getParameter(String paramName) Use this method when a parameter has at most one value String [] getParameterValues(String paramName) Use this method if a parameter can have multiple values Both methods return null if the specified parameter does not exist. Instance methods of HttpServletRequest for retrieving all parameter names: java.util.Enumeration getParameterNames()

14 Parameter names are case sensitive.
Getting Parameters Parameter names are case sensitive. Parameter values are retrieved as strings. You need to write code to convert them from strings to respective data types. Always validate the parameter values before processing the data Users may omit or mistype the values in a form. Hackers can bypass HTML form and JavaScript validation and generate HTTP POST/GET request programmatically.

15 Servlets Packages Package: javax.servlet Package: javax.servlet.http
Contains many interfaces and abstract classes for protocol independent generic servlets Package: javax.servlet.http Contains interfaces and abstract classes for servlets that understand HTTP protocols Extends from the interfaces and classes used in the generic servlets Ref: Java Servlet 2.3 API documentation Servlet implemented by GenericServlet extended by HttpServlet extended by MyServlet

16 Characteristics of Servlet Class
Every servlet directly or indirectly implements the javax.servlet.Servlet interface. That means, every servlet contains the following methods: void init(ServletConfig config) void service(ServletRequest req, ServletResponse res) void destroy() ServletConfig getServletConfig() String getServletInfo() A servlet container interacts with a servlet through these methods.

17 Servlet Life Cycles Initialization Handling Requests Termination
The servlet's init() method is called once in a servlet's lifetime when a servlet is first loaded. If an exception is thrown or uncaught in init(), the servlet won't run. Handling Requests The servlet's service() method is called whenever a servlet is needed to service a request. A servlet can serve multiple requests concurrently (The container create threads to serve multiple requests) Termination The servlet's destroy() method is called once when the servlet is being unloaded from memory.

18 init() destroy() service() Servlet Life Cycles
Overload this method only if you need to perform a task once in a servlet's lifecycle. e.g.: To open a database connection destroy() Overload this method only if you need to perform some cleanup tasks before a servlet is being unloaded from memory. e.g.: To close a database connection or to remove some temporary files service() Overload this method only if you need to handle ALL types of HTTP requests (GET, POST, DELETE, HEADER, PUT, etc.) To handle a specific type of HTTP requests, we can just overload one of doXXX() methods.

19 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyPrimitiveServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Handle POST request } public void doGet(HttpServletRequest request, // Handle GET request HttpServlet implemented the method service() which dispatches various types of request (GET, POST, etc.) to the proper doXXX() methods respectively. Subclass should override at least one of the doXXX() methods.

20 HttpServletRequest object
To obtain the data encapsulated in a HTTP request Form data, cookies, header fields, body contents Query string and additional path info embedded in the URL To obtain additional info about a request e.g.: The name of authentication scheme used To obtain info about the requester e.g.: Client's host name, IP address, etc. To obtain session information associated with the current request To carry additional data between servlets when a request is dispatched or forwarded from one servlet to another.

21 HttpServletResponse object
To send data in the request body This object contains an output buffer which can be obtained via ServletOutputStream getOutputStream() Suitable for writing binary data java.io.PrintWriter getWriter() Suitable for writing texts Only one of the above methods can be called. Data written to the output buffer is sent to the client in the request body. To add header fields, add/set cookies, set content type, set status code, send error code and error message, send redirection instruction

22 ServletConfig object The ServletConfig object can be obtained by calling getServletConfig() The object contains some info specified in web application deployment/configuration file – web.xml Servlet's name Parameters to be passed to the servlet e.g., URL of the database A ServletContext object

23 ServletContext object
A ServletContext object contains APIs for a servlet to communicate with its servlet container. e.g.: Get server info and version of the servlet API Write to the log file Get the MIME type of a file Dispatch requests There is one context per "web application" per servlet container. A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file. Servlets belong to the same application can share data through the ServletContext object.

24 Summary Fundamentally, all server-side scripts work in the following manner: Obtains data from a HTTP request Processes the data Produces HTTP response Java Servlet technology provides a framework to write, deploy and execute servlets. Serlvet APIs help programmers to Obtain data from a HTTP request (HttpServletRequest) Obtain info from the servlet container (ServletConfig and ServletContext) Set data in a HTTP response (HttpServletResponse) Manage session information (HttpServletRequest and HttpSession) References: "Java for the Web with Servlets, JSP, and EJB" by Budi Kurniawan Wiki: Java Servlets ( Servlet Essentials (


Download ppt "CSC 2720 Building Web Applications"

Similar presentations


Ads by Google