Presentation is loading. Please wait.

Presentation is loading. Please wait.

Enterprise Computing with Java (MCA-305) Unit 1: J2EE and Servlet

Similar presentations


Presentation on theme: "Enterprise Computing with Java (MCA-305) Unit 1: J2EE and Servlet"— Presentation transcript:

1 Enterprise Computing with Java (MCA-305) Unit 1: J2EE and Servlet
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh 1

2 Enterprise Computing with Java (MCA-305)
Java, J2SE, J2EE and J2ME “Java” refers to both, a language and a platform. The Java programming language is a high-level, object-oriented language that has a particular syntax and style. A Java platform is a particular environment in which Java programming language applications run. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

3 Java Programming Language Platforms
Enterprise Computing with Java (MCA-305) Java Programming Language Platforms Java Platform, Standard Edition (Java SE) Java Platform, Enterprise Edition (Java EE) Java Platform, Micro Edition (Java ME) All Java platforms consist of a Java Virtual Machine (JVM) and an Application Programming Interface (API). The JVM is a program, for a particular hardware and software platform, that runs Java technology applications. An API is a collection of software components that you can use to create other software components or applications. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

4 Standard Edition (Java SE)
Enterprise Computing with Java (MCA-305) Standard Edition (Java SE) Java SE platform is: the most basic and standard version of Java. a basic foundation for all other editions. (API) provides the core functionality of the Java programming language. Java SE platform consists of: a virtual machine, development tools, deployment technologies, etc. used in Java technology applications. mainly used to create applications for Desktop environment. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

5 Enterprise Edition (Java EE)
Enterprise Computing with Java (MCA-305) Enterprise Edition (Java EE) The Java EE platform is built on top of the Java SE platform. It provides an API and runtime environment for developing and running large-scale, multi-tiered, scalable, reliable, and secure network applications. It uses many components of SE, as well as, has many new features of it’s own like Servlets, JavaBeans, etc., adding a whole new functionalities to the language. It uses HTML, CSS, JavaScript etc., so as to create web pages and web services. It is one of  the most widely accepted web development standard. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

6 Micro Edition (Java ME)
Enterprise Computing with Java (MCA-305) Micro Edition (Java ME) The Java ME platform provides an API and a small-footprint JVM for running Java programming language applications on small devices, like mobile phones, set top boxes, etc. The API is a subset of the Java SE API, along with special class libraries useful for small device application development. Java ME applications are often clients of Java EE platform services. Most of the apps, developed for the phones (prior to smartphones era), were built on J2ME platform . Old Nokia phones, which used Symbian OS, used this technology. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

7 Enterprise Computing with Java (MCA-305)
JavaFX JavaFX is another edition of Java technology, which is now merged with SE 8. It is mainly used to create rich GUI (Graphical User Interface) in Java applications. It replaces Swings (in SE), with itself as the standard GUI library. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

8 Developing Enterprise Applications
Enterprise Computing with Java (MCA-305) Developing Enterprise Applications The Java EE platform is designed to help developers create large-scale, multi-tiered, scalable, reliable, and secure network applications A shorthand name for such applications is “enterprise applications,” so called because these applications are designed to solve the problems encountered by large enterprises. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

9 Multitiered Application Model
Enterprise Computing with Java (MCA-305) Multitiered Application Model The Java EE platform uses a distributed multi-tiered application model for enterprise applications. In a multi-tiered application, the functionality of the application is separated into isolated functional areas, called tiers. Usually, multi-tiered applications have a client tier, a middle tier, and a data tier (often called the enterprise information systems tier) © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

10 Multitiered Application Model
Enterprise Computing with Java (MCA-305) Multitiered Application Model © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

11 Enterprise Computing with Java (MCA-305)
Client Tier The client tier consists of application clients that access a Java EE server and that are usually located on a different machine from the server. The clients make requests to the server. The server processes the requests and returns a response back to the client. A Java EE client can be a web client or an application client. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

12 Client Tier: Web Clients
Enterprise Computing with Java (MCA-305) Client Tier: Web Clients A web client consists of two parts: dynamic web pages containing various types of markup language (HTML, XML, and so on), which are generated by web components running in the web tier, and a web browser, which renders the pages received from the server © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

13 Client Tier: Application Clients
Enterprise Computing with Java (MCA-305) Client Tier: Application Clients An application client runs on a client machine and provides a way for users to handle tasks that require a richer user interface than can be provided by a markup language. It typically has a GUI created from the Swing or the AWT API. A command-line interface is also possible. Many different types of applications can be Java EE clients, and they are not always, or even often Java applications. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

14 Client Tier: Web and Application Clients
Enterprise Computing with Java (MCA-305) Client Tier: Web and Application Clients © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

15 Enterprise Computing with Java (MCA-305)
Web Tier The web tier consists of components that handle the interaction between clients and the business tier. Its primary tasks are the following: dynamically generate content in various formats for the client collect input from users of the client interface and return appropriate results from the components in the business tier control the flow of screens or pages on the client maintain the state of data for a user's session © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

16 Web Components Servlets JavaServer Pages (JSP) JavaServer Faces
Enterprise Computing with Java (MCA-305) Web Components Servlets Servlets are Java programming language classes that dynamically process requests and construct responses JavaServer Pages (JSP) JSP pages are text-based documents that execute as servlets and define how dynamic content can be added to static pages, such as HTML pages JavaServer Faces JavaServer Faces technology builds on servlets and JSP technology and provides a user interface component framework for web applications. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

17 Web Tier and Java EE Applications
Enterprise Computing with Java (MCA-305) Web Tier and Java EE Applications © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

18 Enterprise Computing with Java (MCA-305)
Business Tier The business tier consists of components that provide the business logic for an application. Business logic is code that provides functionality to a particular business domain, like the financial industry, or an e-commerce site. In a properly designed enterprise application, the core functionality exists in the business tier components. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

19 Business Components Enterprise JavaBeans (EJBs)
Enterprise Computing with Java (MCA-305) Business Components Enterprise JavaBeans (EJBs) Components that encapsulate the core functionality of an application. Business code, which is logic that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. Java Persistence API Entities An API for accessing data in underlying data stores and mapping that data to Java programming language objects. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

20 Business Tier Enterprise Computing with Java (MCA-305)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

21 Enterprise Information Systems Tier
Enterprise Computing with Java (MCA-305) Enterprise Information Systems Tier The enterprise information systems (EIS) tier consists of database servers and other legacy data sources. It may contain data-related logic in the form of stored procedures. These resources typically are located on a separate machine than the Java EE server, and are accessed by components on the business tier. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

22 Characteristics of n-tier Architecture
Enterprise Computing with Java (MCA-305) Characteristics of n-tier Architecture Deployment costs are low It is much cheaper to deploy and configure software in a controlled server-side environment than to deploy software on thousands of end user terminals. Database switching costs are low Clients no longer access the database directly, but rather go through the middle tier for data access. This enables to migrate database schemas, change to different database drivers, or even change your persistent storage type without re-deploying clients. Scalability The key benefit of three-tier is improved scalability since the application servers can be deployed on many machines. Also, the database no longer requires a connection from every client; it only requires connections from a smaller number of application servers. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

23 Characteristics of n-tier Architecture
Enterprise Computing with Java (MCA-305) Characteristics of n-tier Architecture Business logic migration costs are low Changing the business logic layer may not necessitate recompiling and redeploying the client tier Maintenance costs are high You are deploying in three or more physically separate tiers. Software installation costs, software upgrade costs, redeployment costs, and administration costs increase significantly Improved Security Security is improved since it can be implemented at multiple levels (not just the database) © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

24 Characteristics of n-tier Architecture
Enterprise Computing with Java (MCA-305) Characteristics of n-tier Architecture Improved Availability Mission-critical applications can make use of redundant application servers and redundant database servers. With redundant servers, it is possible to architect an application so that it can recover from network or server failures © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

25 MVC

26 Enterprise Computing with Java (MCA-305)
What is Servlet? Servlet can be described in many ways, depending on the context: Servlet is a technology used to create web applications Servlet is an API that provides many interfaces and classes including documentations Servlet is an interface that must be implemented for creating any servlet Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests Servlet is a web component that is deployed on the server to create dynamic web page © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

27 Advantages of Servlets: Background
Enterprise Computing with Java (MCA-305) Advantages of Servlets: Background In order to understand the advantages of servlets, consider a request for a static web page: A user enters a Uniform Resource Locator (URL) into a browser. The browser generates an HTTP request to the appropriate web server. The web server maps this request to a specific file. That file is returned in an HTTP response to the browser. The HTTP header in the response indicates the type of the content. The Multipurpose Internet Mail Extensions (MIME) are used for this purpose. For example, ordinary ASCII text has a MIME type of text/plain. The Hypertext Markup Language (HTML) source code of a web page has a MIME type of text/html. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

28 Advantages of Servlets: Background
Enterprise Computing with Java (MCA-305) Advantages of Servlets: Background Now consider a request for dynamic web page: In the early days of the Web, a server could dynamically construct a page by creating a separate process to handle each client request. The process would open connections to one or more databases in order to obtain the necessary information. It communicated with the web server via an interface known as the Common Gateway Interface (CGI). CGI allowed the separate process to read data from the HTTP request and write data to the HTTP response. A variety of different languages were used to build CGI programs. These included C, C++, and Perl. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

29 Problems with CGI / Advantages of Servlets
Enterprise Computing with Java (MCA-305) Problems with CGI / Advantages of Servlets CGI suffered serious performance problems: It was expensive in terms of processor and memory resources to create a separate process for each client request For each request, it starts a process and Web server is limited to start processes. It was also expensive to open and close database connections for each client request If number of clients increases, it takes more time for sending response. In addition, the CGI programs are not platform-independent. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

30 Advantages of Servlets
Enterprise Computing with Java (MCA-305) Advantages of Servlets Servlets offer several advantages in comparison with CGI-Perl: Performance is significantly better because it creates a thread for each request not process Servlets are platform-independent because they are written in Java The Java security manager on the server enforces a set of restrictions to protect the resources on a server machine The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

31 Life Cycle of a Servlet init() service() destroy()
Enterprise Computing with Java (MCA-305) Life Cycle of a Servlet init() This method is invoked only when the servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure itself. service() This method is called to process the HTTP request. destroy() The server may decide to unload the servlet from its memory. The algorithms by which this determination is made are specific to each server. The server calls the destroy() method to relinquish any resources such as file handles that are allocated for the servlet. The memory allocated for the servlet and its objects can then be garbage collected. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

32 Life Cycle of a Servlet

33 A Simple Generic Servlet
Enterprise Computing with Java (MCA-305) A Simple Generic Servlet import java.io.*; import javax.servlet.*; public class HelloServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>Hello!"); pw.close(); } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

34 Enterprise Computing with Java (MCA-305)
How a Servlet Works 1. User sends request for a servlet by clicking a link that has URL to a servlet. Source of Figure: © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

35 Enterprise Computing with Java (MCA-305)
How a Servlet Works 2. The container finds the servlet using deployment descriptor and creates two objects: HttpServletRequest HttpServletResponse Source of Figure: © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

36 Enterprise Computing with Java (MCA-305)
How a Servlet Works 3. Then the container creates or allocates a thread for that request and calls the Servlet's service() method and passes the request, response objects as arguments. Source of Figure: © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

37 Enterprise Computing with Java (MCA-305)
How a Servlet Works 4. The service() method, then decides which servlet method, doGet() or doPost(), … … to call, based on HTTP request method (GET, POST, etc.) sent by the client. Source of Figure: © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

38 Enterprise Computing with Java (MCA-305)
How a Servlet Works 5. Then, the Servlet uses response object to write the response back to the client. Source of Figure: © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

39 Enterprise Computing with Java (MCA-305)
How a Servlet Works 6. After the service() method is completed, the thread dies and the request and response objects are ready for garbage collection. Source of Figure: © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

40 HTTP (Hyper Text Transfer Protocol)
Enterprise Computing with Java (MCA-305) HTTP (Hyper Text Transfer Protocol) The Hypertext Transfer Protocol (HTTP) is application-level protocol used to establish communication between client and server. HTTP is TCP/IP based communication protocol, which is used to deliver the data like image files, query results, HTML files, etc. on the World Wide Web (WWW). It provides the standardized way for computers to communicate with each other. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

41 Characteristics of HTTP
Enterprise Computing with Java (MCA-305) Characteristics of HTTP It is the protocol that allows web servers and browsers to exchange data over the web. It is a request-response protocol. It uses the reliable TCP connections on port 80. It is stateless (each request is considered as the new request). © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

42 Enterprise Computing with Java (MCA-305)
HTTP Requests The request sent by the computer to a web server that contains all sorts of potentially interesting information is known as HTTP request. The HTTP client sends the request to the server in the form of request message which includes following main information: Analysis of source IP address, proxy and port Analysis of destination IP address, protocol, port and host Requested URI (Uniform Resource Identifier) A URI is a sequence of characters that identifies a logical or physical resource. Request method and Content Connection control header © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

43 Enterprise Computing with Java (MCA-305)
HTTP Request Methods The HTTP request method indicates the method to be performed on the resource identified by the requested URI Two commonly used methods for a request-response between a client and server are: GET and POST GET: Requests data from a specified resource The query string (name/value pairs) is sent in the URL of a GET request: /test/demo_form.php?name1=value1&name2=value2 POST: Submits data to be processed to a specified resource The query string (name/value pairs) is sent in the HTTP message body of a POST request: POST /test/demoform.php HTTP/1.1 Host: w3schools.com name1=value1&name2=value2 © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

44 Enterprise Computing with Java (MCA-305)
GET vs. POST GET In case of Get request, only limited amount of data can be sent because data is sent in header Get request is not secured because data is exposed in URL bar Get request can be bookmarked Get request is idempotent. It means second request will be ignored until response of first request is delivered Get request is more efficient and used more than Post POST In case of post request, large amount of data can be sent because data is sent in body Post request is secured because data is not exposed in URL bar Post request cannot be bookmarked Post request is non-idempotent Post request is less efficient and used less than get © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

45 Enterprise Computing with Java (MCA-305)
Servlet API Servlet API consists of two important packages that encapsulates all the important classes and interface, namely: javax.servlet javax.servlet.http © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

46 Servlet API: Interfaces of javax.servlet
Enterprise Computing with Java (MCA-305) Servlet API: Interfaces of javax.servlet Main interfaces of javax.servlet package Servlet – Declares life cycle methods {init(), service(), and destroy()} for a servlet ServletRequest – Used to read data from a client request ServletResponse – Used to write data to a client response ServletConfig – Allows servlets to get initialization parameters RequestDispatcher - Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server ServletContext - Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

47 Servlet API: Classes of javax.servlet
Enterprise Computing with Java (MCA-305) Servlet API: Classes of javax.servlet Main classes of javax.servlet package GenericServlet (Abstract Class) java.lang.Object ∟javax.servlet.GenericServlet ServletException ∟java.lang.Throwable ∟java.lang.Exception ∟javax.servlet.ServletException © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

48 Servlet Life Cycle Methods (called by servlet container )
Enterprise Computing with Java (MCA-305) Servlet Interface Servlet Interface Servlet Interface provides five methods. Out of these five methods, three methods are servlet life cycle methods and rest two are non life cycle methods. Methods: void init(ServletConfig) void service(ServletRequest, ServletResponse) void destroy() ServletConfig getServletConfig() - Returns a ServletConfig object, which contains initialization and startup parameters for this servlet. String getServletInfo() -  Returns information about the servlet, such as author, version, and copyright. Note: A servlet container (web container) is a component of web server that interacts with Java servlets. It provides run time environment for Java applications. It performs many operations including life cycle management and multithreaded. Servlet Life Cycle Methods (called by servlet container ) © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

49 ServletRequest Interface
Enterprise Computing with Java (MCA-305) ServletRequest Interface Main methods of ServletRequest interface String getParameter(String) - Returns the value of a request parameter as a String, or null if the parameter does not exist. Enumeration getParameterNames() - Returns an Enumeration of String objects containing the names of the parameters contained in this request. RequestDispatcher getRequestDispatcher(String) - Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. void setAttributes(String, Object) -  Stores an attribute in this request. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

50 ServletResponse Interface
Enterprise Computing with Java (MCA-305) ServletResponse Interface Main methods of ServletResponse interface void setContentType(String) - Sets the content type of the response being sent to the client. PrintWriter getWriter() - Returns a PrintWriter object that can send character text to the client. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

51 ServletDispatcher Interface
Enterprise Computing with Java (MCA-305) ServletDispatcher Interface Main methods of ServletDispatcher interface void forward(ServletRequest, ServletResponse) - Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. void include(ServletRequest, ServletResponse) - Includes the content of a resource (servlet, JSP page, HTML file) in the response. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

52 Working of forward() Method
Enterprise Computing with Java (MCA-305) Working of forward() Method Source of Figure: © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

53 Working of include() Method
Enterprise Computing with Java (MCA-305) Working of include() Method Source of Figure: © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

54 Use of forward() and include() Methods
Enterprise Computing with Java (MCA-305) Use of forward() and include() Methods Source of Figure: © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

55 ServletConfig Interface
Enterprise Computing with Java (MCA-305) ServletConfig Interface When Web Container initializes a servlet, it creates a ServletConfig object for servlet. ServletConfig object is used to pass information to a servlet during initialization by getting configuration information from web.xml. Main methods of ServletConfig interface String getInitParameter(String) - Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. ServletContext getServletContext() - Returns a reference to the ServletContext in which this servlet/caller is executing. String getServletName() - Returns the name of this servlet instance. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

56 Example of ServletConfig Program
Enterprise Computing with Java (MCA-305) Example of ServletConfig Program Name of Parameter Value of Parameter © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

57 ServletContext Interface
Enterprise Computing with Java (MCA-305) ServletContext Interface For every Web Application a ServletContext object is created by the Web Container. ServletContext object is used to get configuration information from web.xml which will be available to any servlet or JSPs that are part of the Application. Main methods of ServletContext interface String getInitParameter(String) - Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist. void addAttribute(String, Object) - Binds an object to a given attribute name in this servlet context. void removeAttribute(String) - Removes the attribute with the given name from the servlet context. ServletContext getContext(String uriPath) - Returns a ServletContext object that corresponds to a specified URL on the server. String getMimeType (String file) - Returns the MIME type of the specified file, or null if the MIME type is not known. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

58 Example of ServletContext Program
Enterprise Computing with Java (MCA-305) Example of ServletContext Program <context-param> is for whole application so it is put inside the <web-app> tag but outside any <servlet>tag Value of Parameter Name of Parameter © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

59 ServletContext vs. ServletConfig

60 GenericServlet Class Main methods of GenericServlet class
Enterprise Computing with Java (MCA-305) GenericServlet Class Main methods of GenericServlet class void init(ServletConfig) - Called by the servlet container to indicate to a servlet that the servlet is being placed into service. abstract void service(ServletRequest, ServletResponse) - Called by the servlet container to allow the servlet to respond to a request. void destroy() - Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. String getInitParameter(String) - Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. ServletConfig getServletConfig() - Returns this servlet's ServletConfig object. ServletContext getServletContext() - Returns a reference to the ServletContext in which this servlet is running. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

61 GenericServlet Class Main methods of GenericServlet class (contd..)
Enterprise Computing with Java (MCA-305) GenericServlet Class Main methods of GenericServlet class (contd..) String getServletInfo() - Returns information about the servlet, such as author, version, and copyright.  String getServletName() - Returns the name of this servlet instance. void log(String) - Writes the specified message to a servlet log file. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

62 Servlet API: Interfaces and Classes of javax.servlet.http
Enterprise Computing with Java (MCA-305) Servlet API: Interfaces and Classes of javax.servlet.http Main interfaces of javax.servlet.http package HttpServletRequest – Enables servlets to read data from an HTTP request. HttpServletResponse – Enables servlets to write data to an HTTP response. HttpSession – Allow session data to be read and written. Main classes of javax.servlet.http package Cookie – Allows state information to be stored on a client machine. HttpServlet – Provides methods to handle HTTP requests and responses. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

63 Methods of HttpServletRequest Interface
Enterprise Computing with Java (MCA-305) Methods of HttpServletRequest Interface ServletRequest ∟HttpServletRequest Main methods of HttpServletRequest interface Cookie [] getCookies() - Returns an array containing all of the Cookie objects the client sent with this request. String getMethod() - Returns the name of the HTTP method with which this request was made, for example, GET, POST, etc. String getQueryString() - Returns the query string that is contained in the request URL after the path. HttpSession getSession() - Returns the current session associated with this request, or if the request does not have a session, creates one. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

64 Methods of HttpServletResponse Interface
Enterprise Computing with Java (MCA-305) Methods of HttpServletResponse Interface ServletResponse ∟HttpServletResponse Main methods of HttpServletResponse interface void addCookie(Cookie ck) - Adds the specified cookie to the response. void addHeader(String name, String value) - Adds a response header with the given name and value. void sendError(int sc) - Sends an error response to the client using the specified status code. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

65 Methods of HttpServlet Class
Enterprise Computing with Java (MCA-305) Methods of HttpServlet Class Object ∟GenericServlet ∟HttpServlet (Abstract Class) implements Servlet, ServletConfig HttpServlet is an abstract class which is to be subclassed to create an HTTP servlet suitable for a Web Application. A subclass of HttpServlet must override at least one method, usually one of these: doGet(), doPost(), doPut(), doDelete(), init(), destroy(), getServletInfo() There's almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above). © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

66 Session Management Managing Session in Servlet
Enterprise Computing with Java (MCA-305) Session Management Managing Session in Servlet Session is a conversional state between client and server and it can consists of multiple request and response between client and server.  As HTTP is a stateless protocol, all requests and responses are independent. Sometimes we need to keep track of client's activity across multiple requests. For eg., when a user logs into a website, not matter on which web page he visits after logging in, his credentials will be with the server, until he logs out. This is managed by creating a session. Session Management (also known as Session Tracking) is a mechanism used by the Web Container to store session information for a particular user. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

67 Session Management in Servlet
Enterprise Computing with Java (MCA-305) Session Management in Servlet Techniques used by Servlet Application for Session Management: Cookies HttpSession Hidden Form Field URL Rewriting © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

68 Enterprise Computing with Java (MCA-305)
Working of Session Whenever a user starts using application, a unique identification information about him/her can be saved in an object which is available throughout the application, until its destroyed. Source of Figure: © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

69 Using Cookies for Session Management
Enterprise Computing with Java (MCA-305) Using Cookies for Session Management Cookies are small pieces of information that are sent in response from the web server to the client.  Cookies are the simplest technique used for storing client state. Cookies are stored on client's computer. They have a lifespan and are destroyed by the client browser at the end of that lifespan. Cookies are created using Cookie class present in Servlet API. Cookies are added to response object using the addCookie() method. This method sends cookie information over the HTTP response stream.  getCookies() method is used to access the cookies that are added to response object. Using Cookies for storing client state has one shortcoming though, if the client has turned off Cookie saving settings in his browser then, client state can never be saved. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

70 Using Cookies for Session Management
Enterprise Computing with Java (MCA-305) Using Cookies for Session Management Creating a new Cookie (Example) Cookie ck = new Cookie(“userName”, name); Setting Lifespan for a Cookie ck.setMaxAge(100);  Time is Seconds Sending Cookie to Client response.addCookie(ck); Getting Cookies from Client Request Cookie [] cks = request.getCookies(); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

71 Program of Cookie Enterprise Computing with Java (MCA-305)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

72 Program of Cookie Enterprise Computing with Java (MCA-305)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

73 Program of Cookie Enterprise Computing with Java (MCA-305)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

74 Using HttpSession for Session Management
Enterprise Computing with Java (MCA-305) Using HttpSession for Session Management HttpSession interface enables a servlet to read and write the state information that is associated with an HTTP session. We can store, retrieve and remove attribute from HttpSession object. Any servlet can have access to HttpSession object throughout the getSession() method of the HttpServletRequest. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

75 Working of HttpSession
Enterprise Computing with Java (MCA-305) Working of HttpSession On client's first request, the Web Container generates a unique session ID and gives it back to the client with response. This is a temporary session created by web container. The client sends back the session ID with each request. Making it easier for the web container to identify where the request is coming from. The Web Container uses this ID, finds the matching session with the ID and associates the session with the request. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

76 Using HttpSession for Session Management
Enterprise Computing with Java (MCA-305) Using HttpSession for Session Management Creating a new session:- HttpSession session = request.getSession(); getSession() returns a session . If the session already exist, it returns the existig else creates a new session. HttpSession session = request.getSession(true); getSession(true) always returns a new session. Getting a pre-existing session:- HttpSession session = request.getSession(false); getSession() returns a pre-existing session. Destroying a session:- session.invalidate(); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

77 Methods of HttpSession
Enterprise Computing with Java (MCA-305) Methods of HttpSession Main methods of HttpSession interface long getCreationTime() - Returns the time when the session was created. String getId() - Returns a string containing the unique identifier assigned to the session. long getLastAccessedTime() - Returns the last time the client sent a request associated with the session. void invalidate() - Destroy the session. boolean isNew() - Returns true if the session is new else false. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

78 Program of HttpSession
Enterprise Computing with Java (MCA-305) Program of HttpSession © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

79 Program of HttpSession
Enterprise Computing with Java (MCA-305) Program of HttpSession © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

80 Program of HttpSession
Enterprise Computing with Java (MCA-305) Program of HttpSession © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

81 Using URL Rewriting for Session Management
Enterprise Computing with Java (MCA-305) Using URL Rewriting for Session Management In URL rewriting, a token(parameter) is added at the end of the URL. The token consist of name/value pair separated by an equal (=) sign. The token (parameter) part of the requested URL can be fetched and used for session management. getParameter() method is used to get the parameter value at the server side. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

82 Program of URL Rewriting
Enterprise Computing with Java (MCA-305) Program of URL Rewriting © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

83 Program of URL Rewriting
Enterprise Computing with Java (MCA-305) Program of URL Rewriting © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

84 Using Hidden Form Field for Session Management
Enterprise Computing with Java (MCA-305) Using Hidden Form Field for Session Management In case of hidden form field, a hidden field is used to store client state. In this case user information is stored in hidden field value and retrieved from another servlet. Advantages: Does not have to depend on browser whether the cookie is disabled or not. Inserting a simple HTML Input field of type hidden is required. Hence, its easier to implement. Disadvantages: Extra form submission is required on every page. This is a big overhead. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

85 Hidden Form Field: Working

86 Hidden Form Field: Example
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //Getting value submitted in form from HTML file String user = request.getParameter("user"); //Creating a new hidden form field out.println("<form action='Second'>"); out.println("<input type='hidden' name='user' value='"+user+"'>"); out.println("<input type='submit' value='submit' >"); out.println("</form>"); }

87 Servlet Collaboration
Enterprise Computing with Java (MCA-305) Servlet Collaboration The exchange of information among servlets of a particular Java web application is known as Servlet Collaboration. Collaboration enables passing/sharing information from one servlet to the other through method invocations. Following are the main approaches for Servlet Collaboration: Using RequestDispatcher’s include() and forward() methods Using HttpServletResponse’s sendRedirect() method Using ServletContext’s setAttribute() and getAttribute() methods © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh

88 Servlet Collaboration: Using include() and forward() Methods
…… …… …… if(uName.equals(“SunilPratapSingh”)) { RequestDispatcher rd = req.getRequestDispatcher(“Welcome"); rd.forward(req, res); } else pw.println(“Wrong User Name”); RequestDispatcher rd = req.getRequestDispatcher(“Login.htm"); rd.include(req, res);

89 Servlet Collaboration: Using sendRedirect() Method
…… …… …… response.sendRedirect(“Welcome/#q=" + uName);

90 Servlet Collaboration: Using setAttribute() and getAttribute() Methods
Servlet A: …… …… …… ServletContext sContext = getServletContext(); sContext.setAttribute(“Institute”,”BVICAM, New Delhi”); out.println("<a href=‘B'>Visit B</a>"); Servlet B: String inst = (String)sContext.getAttribute(“Institute"); out.println("Welcome to “ + inst);

91 Creating Servlet Applications (Using Tomcat Server)
91

92 Server Server is a device or a computer program that accepts and responds to the request made by other program. There are two types of servers: Web Server: A program which delivers web contents like web pages using HTTP over the WWW. Application Server: A software framework devoted to the effective execution of programs, scripts, and routines to assist the creation of various applications.

93 Web Server and Application Server
Basis Web Server Application Server Basic Web servers are suitable for static content. Application servers are suitable for dynamic content. Features Involve only web or servlet container and cannot be used for EJB. Assists scripting languages through plugins such as Perl, PHP, ASP, JSP etc. Could contain a web server as an aggregate part of them and also contain web and EJB containers. Assists application level services such as object pooling, connection pooling, transaction support, messaging services, etc. Examples Apache Tomcat Apache is an HTTP Server, serving HTTP. Tomcat is a Servlet and JSP Server serving Java technologies. Glassfish (Sun Microsystem – Oracle) Jboss (Open Source) Weblogic (Oracle) Websphere (IBM)

94 Steps to Creating Servlet Applications
Create Directory Structure for the Application Create a Servlet Compile the Servlet Create Deployment Descriptor for the Application Start the Server and Deploy the Application

95 1. Create Directory Structure for the Application
C:\Program Files\Apache Software Foundation\Apache Tomcat \webapps

96 2. Create a Servlet

97 3. Compile the Servlet In Apache Tomcat Server, servlet-api.jar file is required to compile a Servlet. Different servers require different JAR files. Configuration of servlet-api.jar C:> set classpath = .; C:\Program Files\Apache Software Foundation\Apache Tomcat \lib\servlet-api.jar Compilation of Servlet C:> javac MyServlet.java

98 4. Create Deployment Descriptor

99 5. Deploy the Application
Start the Server (Tomcat) C:\Program Files\Apache Software Foundation\Apache Tomcat \bin\startup Place compiled Servlets in the webapps/ROOT (Name/Folder of Application)/WEB-INF/classes subdirectory. Load

100 Bibliography https://docs.oracle.com http://www.studytonight.com
Enterprise Computing with Java (MCA-305) Bibliography “Inside Servlets” by Dustin R. Callaway “Enterprise Java Computing: Applications and Architectures” by Govind Sesadari © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Sunil Pratap Singh


Download ppt "Enterprise Computing with Java (MCA-305) Unit 1: J2EE and Servlet"

Similar presentations


Ads by Google