Presentation is loading. Please wait.

Presentation is loading. Please wait.

Server Side Programming: Java Servlets

Similar presentations


Presentation on theme: "Server Side Programming: Java Servlets"— Presentation transcript:

1 Server Side Programming: Java Servlets

2 Server-side Programming
The combination of HTML: HyperText Markup Language JavaScript DOM: Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It is sometimes referred to as Dynamic HTML (DHTML) Web pages that include scripting are often called dynamic pages (vs. static)

3 Server-side Programming
Similarly, web server response can be static or dynamic Static: HTML document is retrieved from the file system of the WebServer and returned to the client Dynamic: HTML document is generated by a program that is running on the server and builds a response to an HTTP request Java servlets are one technology for producing dynamic server responses Servlet is a class instantiated by the server to produce a dynamic response ASP.net and PHP provide similar technologies

4 Servlet

5 Servlet Overview Servlet technology is used to create web application that resides at the server side and generates dynamic web page Before Servlet, CGI (Common Gateway Interface) scripting language was popular as a server-side programming language. What is a Servlet? A technology that is used to create dynamic web applications An API that provides many interfaces and classes An interface that must be implemented for creating any servlet A class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests A web component that is deployed on the server to create dynamic web page

6 Servlet vs. CGI A Servlet has:
Better performance: because it creates a thread for each request not process. Portability: because it uses java language. Robustness: because it is managed by the JVM, thus we don't need to worry about memory leak, garbage collection etc.

7 What is a Java Servlet? Java Servlets are:
Technology for generating dynamic Web pages (like PHP, ASP, ASP.NET, ...) Protocol and platform-independent server side components, written in Java, which extend the standard Web servers Java programs that serve HTTP requests The HttpServlet class Provides dynamic Web content generation (HTML, XML, …)

8 Servlet Services Java Servlets provide many useful services
Provides low-level API for building Dynamic Internet services Serves as foundation to Java Server Pages (JSP) and Java Server Faces (JSF) technologies Can deliver multiple types of data to any client XML, HTML, WML, GIF, etc... Can serve as “Controller” of JSP/Servlet application in the MVC architectural model

9 Why Use Servlets? Portability Write once, serve everywhere Power
* 07/16/96 Why Use Servlets? Portability Write once, serve everywhere Power Can take advantage of all Java APIs Elegance Simplicity due to abstraction Efficiency & Endurance Highly scalable (c) 2006 National Academy for Software Development -

10 Why Use Servlets? (2) Safety Integration Extensibility & Flexibility
* 07/16/96 Why Use Servlets? (2) Safety Strong type-checking Memory management Integration Servlets tightly coupled with server Extensibility & Flexibility Servlets designed to be easily extensible, though currently optimized for HTTP uses Flexible invocation of servlet Server-Side Includes (SSI) servlet-chaining, Filters etc. (c) 2006 National Academy for Software Development -

11 Servlet Overview Web Browser Client Web Server

12 Servlet Container It is the part of web server which can be run in a separate process. We can classify the servlet container states in three types: Standalone: It is typical Java-based servers in which the servlet container and the web servers are the integral part of a single program. For example:- Tomcat running by itself In-process: It is separated from the web server, because a different program runs within the address space of the main server as a plug-in. For example:- Tomcat running inside the JBoss. Out-of-process: The web server and servlet container are different programs which run in a different process.

13 Servlet Overview When server starts it instantiates servlets (Object)
Server receives HTTP request, determines the need for dynamic response Server selects the appropriate servlet to generate the response, creates request/response objects, and p asses them to a method on the servlet instance Servlet adds information to response object via method calls Server generates HTTP response based on information stored in response object

14 Hello World! Servlet

15 Hello World! Servlet All servlets we will write are subclasses of
HttpServlet

16 Hello World! Servlet Server calls doGet() in response to the HTTP GET request

17 Hello World! Servlet Interfaces implemented by request/response objects

18 Hello World! Servlet Production servlet should catch these exceptions

19 Hello World! Servlet First two things done by typical servlet;
must be in this order

20 Hello World! Servlet HTML generated by calling print() or println()
on the servlet’s PrintWriter object Good practice to explicitly close the PrintWriter when done

21 Servlets vs. Java Applications
Servlets do not have a main() The main() is in the server Entry point to servlet code is via call to a method (doGet() in the example) Servlet interaction with end user is indirect via request/response object APIs Actual HTTP request/response processing is handled by the server Primary servlet output is typically HTML

22 Running Servlets Simple way to run a servlet (better later):
Compile servlet (make sure that JWSDP libraries are on path) Copy .class file to shared/classes directory (Re)start the Tomcat web server If the class is named ServletHello, browse to

23 Dynamic Content

24 Dynamic Content

25 Dynamic Content

26 Dynamic Content Potential problems:
Assuming one instance of servlet on one server, but Many Web sites are distributed over multiple servers Even a single server can (not default) create multiple instances of a single servlet Even if the assumption is correct, this servlet does not handle concurrent accesses properly We’ll deal with this later in the chapter

27 Servlet Life Cycle

28 Servlet Life Cycle Servlet API life cycle methods
init(): called when servlet is instantiated; must return before any other methods will be called service(): method called directly by server when an HTTP request is received; default service() method calls doGet() (or related methods covered later) destroy(): called when and before server shuts down

29 * 07/16/96 Servlets Life-Cycle The Web container manages the life cycle of servlet instances The life-cycle methods should not be called by your code init() ...() service() doGet() doPost() doDelete() destroy() doPut() New Destroyed Running You can provide an implementation of these methods in HttpServlet descendent classes to manipulate the servlet instance and the resources it depends on (c) 2006 National Academy for Software Development -

30 Life Cycle of a Servlet The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet: Servlet class is loaded. Servlet instance is created. init method is invoked. service method is invoked. destroy method is invoked

31 * 07/16/96 The init() Method Called by the Web container when the servlet instance is first created The Servlets specification guarantees that no requests will be processed by this servlet until the init method has completed Override the init() method when: You need to create or open any servlet-specific resources that you need for processing user requests You need to initialize the state of the servlet (c) 2006 National Academy for Software Development -

32 * 07/16/96 The service() Method Called by the Web container to process a user request Dispatches the HTTP requests to one of the : doGet(…), doPost(…), etc. depending on the HTTP request method: GET, POST, and so on Sends the result as HTTP response Usually we do not need to override this method (c) 2006 National Academy for Software Development -

33 * 07/16/96 The destroy() Method Called by the Web container when the servlet instance is being eliminated The Servlet specification guarantees that all requests will be completely processed before this method is called Override the destroy method when: You need to release any servlet-specific resources that you had opened in the init() method You need to persist the state of the servlet (c) 2006 National Academy for Software Development -

34 Servlet Life Cycle Example life cycle method:
attempt to initialize visits variable from file Exception to be thrown if initialization fails and servlet should not be instantiated

35 Servlets Architecture
The HttpServlet class Serves client's HTTP requests For each of the HTTP methods, GET, POST, and others, there is corresponding method: doGet(…) – serves HTTP GET requests doPost(…) – serves HTTP POST requests doPut(…), doHead(…), doDelete(…), doTrace(…), doOptions(…) The Servlet usually must implement one of the first two methods or the service(…) method

36 Servlets Architecture (2)
The HttpServletRequest object Contains the request data from the client HTTP request headers Form data and query parameters Other client data (cookies, path, etc.) The HttpServletResponse object Encapsulates data sent back to client HTTP response headers (content type, cookies, etc.) Response body (as OutputStream)

37 Servlets Architecture (3)
* 07/16/96 Servlets Architecture (3) The HTTP GET method is used when: The processing of the request does not change the state of the server The amount of form data is small You want to allow the request to be bookmarked The HTTP POST method is used when: The processing of the request changes the state of the server, e.g. storing data in a DB The amount of form data is large The contents of the data should not be visible in the URL (for example, passwords) Example of HTTP GET: Google search Example of HTTP POST: Login page (c) 2006 National Academy for Software Development -

38 Servlets API The most important servlet functionality:
Retrieve the HTML form parameters from the request (both GET and POST parameters) Retrieve a servlet initialization parameter Retrieve HTTP request header information HttpServletRequest.getParameter(String) ServletConfig.getInitParameter() HttpServletRequest.getHeader(String)

39 Servlets API (2) Set an HTTP response header / content type
Acquire a text stream for the response Acquire a binary stream for the response Redirect an HTTP request to another URL HttpServletResponse.setHeader(<name>, <value>) / HttpServletResponse.setContentType(String) HttpServletResponse.getWriter() HttpServletResponse.getOutputStream() HttpServletResponse.sendRedirect()

40 Servlet API The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet API. The javax.servlet package contains many interfaces / classes used by the servlet or the web container (not protocol specific). The javax.servlet.http package contains interfaces / classes responsible for http requests only. Classes in javax.servlet package GenericServlet ServletInputStream ServletOutputStream ServletRequestWrapper ServletResponseWrapper ServletRequestEvent ServletContextEvent ServletRequestAttributeEvent ServletContextAttributeEvent ServletException UnavailableException Interfaces in javax.servlet package Servlet ServletRequest ServletResponse RequestDispatcher ServletConfig ServletContext SingleThreadModel Filter FilterConfig FilterChain ServletRequestListener ServletRequestAttributeListener ServletContextListener ServletContextAttributeListener

41 Servlet API Classes in javax.servlet.http package HttpServlet Cookie
HttpServletRequestWrapper HttpServletResponseWrapper HttpSessionEvent HttpSessionBindingEvent HttpUtils (deprecated now) Interfaces in javax.servlet.http package HttpServletRequest HttpServletResponse HttpSession HttpSessionListener HttpSessionAttributeListener HttpSessionBindingListener HttpSessionActivationListener HttpSessionContext (deprecated now)

42 Parameter Data

43 Parameter Data The request object (which implements HttpServletRequest) provides information from the HTTP request to the servlet One type of information is parameter data, which is information from the query string portion of the HTTP request Query string with one parameter Parameter data is the Web analog of arguments in a method call: Query string syntax and semantics

44 Parameter Data Query string syntax and semantics
Multiple parameters separated by & Order of parameters does not matter All parameter values are strings Value of arg is empty string But the value of color is “red”

45 Parameter Data Parameter names and values can be any 8-bit characters
URL encoding is used to represent non-alphanumeric characters: URL decoding applied by server to retrieve intended name or value Value of arg is ‘a String’

46 Parameter Data

47 Parameter Data

48 Servlet’s Collaboration

49 What is servlet collaboration
When one servlet communicates to another servlet, it is known as servlet collaboration. There are many ways of servlet collaboration: RequestDispacher interface RequestDispatcher rd=request.getRequestDispatcher(“SecondServletName "); rd.forward(request, response); sendRedirect() method etc. response.sendRedirect(“SecondServletName"); The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interface can also be used to include the content of another resource also. There are two methods defined in the RequestDispatcher interface.

50

51 RequestDispatcher rd=request.getRequestDispatcher(“WelcomeServlet");
//servlet2 is the url-pattern of the second servlet rd.forward(request, response); //method may be include or forward RequestDispatcher rd = request.getRequestDispatcher("/index.html");   rd.include(request, response);  

52 SendRedirect in servlet
The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file. It accepts relative as well as absolute URL. It works at client side because it uses the url bar of the browser to make another request. So, it can work inside and outside the server. Difference between forward() and sendRedirect() method forward() method sendRedirect() method The forward() method works at server side. The sendRedirect() method works at client side. It sends the same request and response objects to another servlet. It always sends a new request. It can work within the server only. It can be used within and outside the server. Example: request.getRequestDispacher("servlet2").forward(request,response); Example: response.sendRedirect("servlet2"); OR response.sendRedirect("

53 ServletConfig and ServletContext
An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from web.xml file. If the configuration information is modified from the web.xml file, we don't need to change the servlet. So it is easier to manage the web application if any specific content is modified from time to time. Methods of ServletConfig interface public String getInitParameter(String name) Returns the parameter value for the specified parameter name. public Enumeration getInitParameterNames() Returns an enumeration of all the initialization parameter names. public String getServletName() Returns the name of the servlet. public ServletContext getServletContext() Returns an object of ServletContext. ServletConfig config=getServletConfig();  

54 ServletConfig: init-param
<servlet> <init-param> <param-name>ParameterName</param-name> <param-value>ParameterValue</param-value> </init-param> </servlet>     PrintWriter out = response.getWriter();       ServletConfig config=getServletConfig();       String pvalue=config.getInitParameter("ParameterName");       out.print(“initial value is : "+pvalue);  

55 ServletConfig and ServletContext
An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application. If any information is shared to many servlet, it is better to provide it from the web.xml file using the <context- param> element. Commonly used methods of ServletContext interface public String getInitParameter(String name) Returns the parameter value for the specified parameter name. public Enumeration getInitParameterNames() Returns the names of the context's initialization parameters. public void setAttribute(String name,Object object) sets the given object in the application scope. public Object getAttribute(String name) Returns the attribute for the specified name. public void removeAttribute(String name) Removes the attribute with the given name from the servlet context. ServletContext application=getServletConfig().getServletContext(); OR ServletContext application=getServletContext();  

56 ServletContext: init-param
<web-app> <context-param> <param-name>ParameterName</param-name> <param-value>ParameterValue</param-value> </context-param> </web-app>     PrintWriter out = response.getWriter();       ServletContext context=getServletContext();       String pvalue=context.getInitParameter("ParameterName");       out.print(“initial value is : "+pvalue);  


Download ppt "Server Side Programming: Java Servlets"

Similar presentations


Ads by Google