0% found this document useful (0 votes)
1 views55 pages

Unit 2

The document provides an overview of web application technologies, focusing on HTTP, web applications, CGI, and Servlets. It explains the architecture of HTTP, the differences between static websites and dynamic web applications, and the lifecycle and advantages of Servlets over CGI. Additionally, it covers deployment descriptors and the Servlet API, detailing how Servlets handle client requests and manage their lifecycle.

Uploaded by

210303124556
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
1 views55 pages

Unit 2

The document provides an overview of web application technologies, focusing on HTTP, web applications, CGI, and Servlets. It explains the architecture of HTTP, the differences between static websites and dynamic web applications, and the lifecycle and advantages of Servlets over CGI. Additionally, it covers deployment descriptors and the Servlet API, detailing how Servlets handle client requests and manage their lifecycle.

Uploaded by

210303124556
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 55
pyte*', it ea cys Objectives Discuss HTTP and HTTP architecture. + What is Web Site and Web Application ? + Understand Web Application Architecture. What is CG! ? how CGI handle client request ? + What is Servlet ? how Servlet handle client request ? What is deployment descriptor ? Oe Web Application Technologies HTTP ( Hypertext Transfer Protocol) * HTTP is the protocol that enables the transfer of data over the internet, allowing users to access websites and other online resources. It is also called communication protocol which is employed for delivering data (usually HTML files, multimedia files, etc.) on the World Wide Web. + HTTP is one of the most commonly used application-level protocol used for hyper-text data distribution, collaboration, and hypertext information system. * The combination of the HTTP protocol and the HTML page description language is the foundation technology of the World Wide Web (WWW). Oe Architecture of HTTP The HTTP is meant for request/response depending on a client-server architecture where the user requests information through a web browser to the web server, which then responds to the requested data. HTTP Request Le) am, Glient f---L P-- Web server ane HTTP Response OS Web Application Technologies Web Client + The client of this client-server architecture asks for a request to a specific server through the HTTP (TCP/IP connection) as a request method in the form of a URL. * It also contains a MIME (Multipurpose Internet Mail Extension) like message that contains request modifier and client information. Web Server * This accepts the request and process with a response by a status line, together with the version of the message's protocol as well as the success or error code, followed by a MIME (Multipurpose Internet Mail Extension) like message having server information, some metadata, and possible the entity-body content holding the requested information. OS What is Web Sites and Web Applications + AWeb site is a collection of static files such as HTML pages, Graphics, and various other resources related to web site. + Aweb application is a web site with dynamic functionality ( Server-side technologies) which will get execute on web server and send back generated output ( HTML format ) back to the client. + Aweb application run programs on the server, for example: + Aclient browser makes a request to the server. + Server responds by sending the HTML form back to the browser in an HTTP request stream. * Again, the client browser sends another request with data to the server. + The server passes the request and data to a program that responds by sending data back to the browser. Oe Web Application Architecture Users ap "Tens th ast Pen vs a aceon 0, Poses, CGI ( Common Gateway Interface ) + Before Servlets, CGI(Common Gateway Interface) programming was used to create web applications. + User clicks a link that has URL to a dynamic page instead of a static page. * The URL decides which CGI program to execute. Web Servers run the CGI program in separate OS shell. The shell includes OS environment and the process to execute code of the CGI program. The CGI response is sent back to the Web Server, which wraps the response in an HTTP response and send it back to the web browser. OS How CGI application handle clients request ? ‘Web Server Client Request Client Request Ss CGI ( Common Gateway Interface ) Advantages + Can be written ina variety of languages * ACGI program with bugs does not crash the Web server * Concurrency issues are isolated at the database Disadvantages * Response time of the CGI programs is high * Itis not scale well + Itis not always secure or object oriented. * CGI code is combined with HTML, which is not a good separation of presentation and business logic OS What is Servlet ? + Servlet is a class that handles requests, processes them and reply back with a response. + It is used to collect input from a user through an HTML form, query records from a database, and create web pages dynamically. + Servlets are under the control of another Java application called a Servlet Container. When an application running in a web server receives a request, the Server hands the request to the Servlet Container — which in turn passes it to the target Servlet. + Properties of Servlets are as follows: + Servlets work on the server-side. + Servlets are capable of handling complex requests obtained from the webserver. + Servlets are build from two packages: + javax.serviet(Basic) + javax.serviet.http(Advance) Oe How Servlet application handle clients request ? Web Server Web Container Client ast ate Client Request = y_Threed | Client Request seen Web Server LL)

element, then define a mapping from a URL path to a servlet declaration with the element. * The element declares the servlet class and a logical name used to refer to the servlet by other elements in the file. * You can declare multiple servlets using the same class but name for each servlet must be unique across the deployment descriptor. + The URL pattern can use an asterisk (*) at the beginning or end of the pattern to indicate zero or more of any character. OS Structure of deployment descriptor file - web.xml accom pay - paruluniversity.servlet. practices. Practice - Itcan be any name Practicé1 | /welcome byt text Life Cycle of a Servlet * The life cycle of Servlet is managed by the Servlet Container which uses the javax.servlet.Serviet interface to understand the serviet object and manage it. * There are four Stages of the Servlet Life Cycle. 1. Loading a Servlet. 2. Initializing the Servlet. 3. Request handling. 4. Destroying the Servlet. OS Life Cycle of a Servlet 1. Loading a Servlet + The first stage of the Servlet lifecycle involves loading and initializing the Servlet by the Servlet container. * The Web container or Servlet Container can load the Servlet at either of the following two stages : 1. Initializing the context, on configuring the Servlet with a zero or positive integer value. 2. If the Servlet is not preceding stage, it may delay the loading process until the Web container determines that this Servlet is needed to service a request. Oe Life Cycle of a Servlet - Loading a Servlet + Loads the Servlet class. * It create a new instance of the Servlet, the container uses the no-argument constructor. Life Cycle of a Servlet 2. Initializing a Servlet * Once the Servlet is instantiated successfully, the Servlet container initializes the instantiated Servlet object. * The container initializes the Servlet object by invoking the Servlet. init(ServletConfig) method which accepts ServletConfig object reference as parameter * It invoke once through out the servlet lifecycle. It is used to initialized the resources such as JDBC data source. * If the Servlet fails to initialize, then it informs the Servlet container by throwing the ServletException or UnavailableException. Oe Life Cycle of a Servlet 3. Handling Request * After initialization, the Servlet instance is ready to serve the client requests. + The Servlet container performs the following operations when the Servlet instance is located to service a request. * It creates the ServietRequest and ServletResponse objects. In this case, if this is a HTTP request, then the Web container creates HttpServletRequest and HttpServietResponse objects which are subtypes of the ServietRequest and ServietResponse objects respectively. * After creating the request and response objects it invokes the Servlet.service(ServletRequest, ServietResponse) method by passing the request and response objects. + The service() method while processing the request may throw the ServietException or UnavailableException or IOException. Oe Life Cycle of a Servlet 3. Destroying the Servlet + When a Servlet container decides to destroy the Servlet, it performs the following operations. * It allows all the threads currently running in the service method of the Servlet instance to complete their jobs and get released. + After currently running threads have completed their jobs, the Servlet container calls the destroy() method on the Servlet instance. + After the destroy() method is executed, the Servlet container releases all the references of this Servlet instance so that it becomes eligible for garbage collection. OS Servlet Life Cycle Events Methods Init() method called once by the web container in a servlet life cycle. Therefore, “connected architecture” code is written inside the method. public void init(ServletConfig con)throws ServletException{ } service() handles multiple client requests and sends response back to the client. This method also calls various other methods such as doGet(), doPost(), doPut(), doDelete(), etc. as required. It accepts two parameters only i.e ServietRequest, ServletResponse. public void service(ServietRequest request, ServletResponse response) throws ServletException, IOException { } destroy() method called once through-out the servlet life cycle. It is used to releasing memory allocated to the servlet and other cleanup activities. public void destroy() {} Example import javax.servlet import javax. servlet. annotation.WebServlet; @ebServlet("/ServletMethodExample" ) public class ServletMethodExample extends GenericServlet { private static final long serialVersionUID = 1L; private String msg; public void init() throws Servletéxception { msg = "This is init() method
"; } @0verride public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response. setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.print1n(msg); pw.printIn("This is service() method
"); pw.print1n(msg); } public void destroy() { msg = "This is destroy() method
"; } + Oe Servlet API * Servlets are the Java programs that run on the Java-enabled web server or application server. * They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver consists of various interfaces, classes, and methods. * They are available in the following packages * javax.serviet * javax.serviet.http OS Servlet API —javax.serviet * This package provides the number of interfaces and classes to support Generic servlet which is protocol independent. * These interfaces and classes describe and define the contracts between a servlet class and the runtime environment provided by a servlet container. OS Servlet API -| GenericServiet Filter ServletContextAttributeEvent FilterChain ServletContextEvent FilterConfig ServletInputStream RequestDispatcher ServietOutputStream Servlet ServietRequestAttributeEvent ServletConfig ServletRequestEvent ServletContext ServietRequestWrapper ServletContextAttributeListener ServietResponseWrapper ServletContextListener ServletRequest Exception ServletRequestAttributeListener ServletException ServletRequestListener UnavailableException ServletResponse OS Servlet API - javax.serviet http * This package provides the number of interfaces and classes to support HTTP servlet which is HTTP protocol dependent. * These interfaces and classes describe and define the contracts between a servlet class running under HTTP protocol and the runtime environment provided by a servlet container. OS Servlet API — javax.servlet.http ( Packages )} HttpServletRequest Interfaces Cookie HttpServiet HttpServletResponse HttpServletRequestWrapper HttpSession HttpServletResponseWrapper HttpSessionActivationListener HttpSessionBindingEvent HttpSessionAttributeListener HttpSessionEvent HttpSessionBindingListener HttpSessionListener OS Servlet Interface — ( Selvlet API ) * It provides the methods that must be implemented by all the servlets. * All methods are implemented by the servlet class that extends from a GenericServiet or HttpServiet class. * The various methods of the Servlet class are: ® void init(ServletConfig config) throws ServletException ™ ServletConfig getServietConfig() ™ String getServietinfo() " void service(ServietRequest request, ServietResponse response) throws ServletException, IOException void destroy() Oe Servlet Interface Example import javax.servlet.*; public class DemoServlet implements Servlet { ServletConfig config=null; public void init(ServletConfig config) { this.config=config; } public void service(ServietRequest req,ServletResponse res) throws IOException,ServietException { } public void destroy() { System.out.printIn("serviet destroy"); } public ServletConfig getServletConfig() { return config;} public String getServletinfo(){ return “This is Servlet interface implementation ex"; } Oe ServletConfig Interface ( Servlet API ) * It is implemented by a Web container during the initialization of a servlet to pass the configuration information to a servlet. + It passed to the init()method of the servlet during initialization. + It can be used to pass initialization parameters to the servlets. ServletConfig is an object containing some initial parameters or configuration information created by Servlet Container and passed to the servlet during initialization. ServletConfig is for a particular servlet, which means one should store servlet-specific information in web.xml and retrieve them using this object. For example, the connection URL can be passed as an initialization parameter of the servlet. OS ServletConfig Interface Methods — ( Servlet API ) Some of the methods of the ServletConfig interface are: + String getinitParameter(String param) It returns a String object containing the value of the initialization parameters. + Enumeration getInitParameterNames() It returns the names of all the ini parameters as an enumeration of String objects. + ServietContext getServietContext() It returns the ServletContext object for the servlet in which the caller is executing. + String getServietName() It returns a String object containing the name of the servlet instance. OS ServletContext Interface — ( Servlet API ) * The ServletContext interface provides the environmental information to the servlets in which they are running. + Itcan be used to get configuration information from descriptor file (web.xml). * Itcan also used to set, get and remove attribute from the descriptor file (web.xml). * Each web application consists of only one ServletContext object. * Itis also known as a Web context. * It provides set of methods that can be used to communicate with the Web container. OS ServletContext Interface Methods — ( Servlet API ) Some of the methods of the ServletCotext interface are: 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 Enumeration getinitParameterNames() Returns the names of the context's init parameters as an Enumeration of String objects. * public void removeAttribute(String name): Removes the attribute with the given name from the servlet context. Oe ServietContext Interface — ( Servlet API ) How to get the object of ServietContext interface There two ways to get an object of ServletContext Interface: We can get the ServletContext object from ServietConfig object ServletContext application = getServletConfig().getServietContext(); Another convenient way to get the ServietContext object ServletContext application = getServietContext(); OS ServletContext Interface — ( Servlet API )- Example Wek I file drvname com.mysq].cj,jdbc.Driver ConnectionURL jdbc:mysq://localhost:3307/classicmodels username root password password OS ServletContext Interface — ( Servlet API )- Example public class DemoServlet extends HttpServiet { public void doGet(HttpServietRequest req,HttpServietResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter pw = res.getWriter(); ServletContext context=getServletContext(); Enumeration e=context.getInitParameterNames(); String si while(e.hasMoreElements()){ str=e.nextElement(); pw.print("
"+context.getinitParameter(str)); ServletRequest Interface — ( Servlet API ) * ServietRequest is used to provide the client request information data to the Servlet as a content type, a content length, parameter names, and the values, header information and the attributes. * Some of the methods of the ServietRequest interface are: public String getParameter(String paramName) This method is used to obtain the value of a parameter by its name public String[] getParameterValues(String paramName) This methods returns an array of String containing all values of given parameter name. public Enumeration getParameterNames() It returns an enumeration for all of the request parameter names public String getContentType() Returns the Internet Media Type(IMT) of the requested entity of data, or null if not known to it Oe ServiletResponse Interface — ( Servlet API ) * The ServietResponse interface contains methods that enable a servlet to respond to the client requests. + AServletResponse object is created by the servlet container and passed as an argument to the servlet’s service function. * Some of the methods of the ServietResponse interface are: public ServletOutputStream getOutputStream() throws IOException This method returns a ServletOutputStream that may be used to write binary data to the response. public PrintWriter getWriter() throws IOException The PrintWriter object is used to transmit character text to the client. public void setContentType(String type) Sets the type of the response data Oe HttpServletRequest Interface - Javax.servlet.http — ( Servlet API ) * HttpServietRequest interface extends the ServietRequest interface to provide request information for HTTP servlets. + The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service methods (doGet, doPost, etc). * The HttpServietRequest breaks a request down into parsed elements, such as request URI, query arguments and headers. Various get methods allow you to access different parts of the request. For Example http://localhost:8080/MyApp/personal/info/top.htm|?info=intro String uri = request.getRequestURI(); - /MyApp/personal/info/top.htm! String contextPath = request.getContextPath(); - /MyApp String servletPath = request.getServietPath(); - /personal String pathInfo = request.getPathInfo(); - /info/top.html String queryStr = request.getQueryString(); - info=intro Oe HttpServletResponse Interface - Javax.servlet.http — ( Servlet API ) * The HttpServietResponse interface extends the ServietResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies. The servlet container creates an HttpServietResponse object and passes it as an argument to the servlet's service methods (doGet, doPost, etc). * Some Important Methods of HttpServietResponse. void addCookie(Cookie cookie) void sendRedirect(String location) void setHeader(String name, String value) String getHeader(String name) void setStatus(int statuscode) void getStatus( ) void sendError(int statuscode, String message) OS RequestDispacher Interface - Javax.servlet — ( Servlet API ) + It provides the facility of dispatching the request to another resource it may be html, servlet or jsp. + It can also be used to include the content of another resource using RequestDispacher methods. + It is one of the way of servlet collaboration between resources. * There are two methods defined in the RequestDispatcher interface. public void forward(ServietRequest request,ServietResponse response) throws ServietException,java.io.IOException Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. public void include(ServietRequest request,ServietResponse response) throws ServletException,java.io.IOException Includes the content of a resource (servlet, JSP page, or HTML file) in the response. Oe RequestDispacher Interface - Javax.servlet — ( Servlet API ) forward() method Ces Fl Syntax : public RequestDispatcher getRequestDispatcher(String resource) RequestDispatcher reqdis =request.getRequestDispatcher|"serviet2") reqdis.forward(request, response);//method may be include or forward OS RequestDispacher Interface - Javax.servlet — ( Servlet API ) include() method Meets Goa Syntax : public RequestDispatcher getRequestDispatcher(String resource) RequestDispatcher reqdis =request.getRequestDispatcher|"serviet2") reqdis.include(request, response);//method may be include or forward OS Session Tracking Session is a conversional state between client and server and it can consists of multiple request and response between client and server. Http protocol is a stateless in nature so we need to maintain state using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user. Servlet API provides Session management through HttpSession interface. HttpSession allows us to set objects as attributes that can be retrieved in future requests. You can get session from HttpServietRequest object using following methods. HttpSession getSession() - This method always returns a HttpSession object. It returns the session object attached with the request, if the request has no session attached, then it creates a new session and return it. HttpSession getSession(boolean flag) - This method returns HttpSession object if request has session else it returns null. Oe Session Tracking There are four techniques used in Session Tracking: 1. Cookies 2. Hidden Form Field 3. URL Rewriting 4, HttpSession OS Session Tracking 1. Cookies * Cookies are small piece of information that is sent by web server in response header and gets stored in the browser cookies. When client make further request, it adds the cookie to the request header and can utilize it to keep track of the session. Client can maintain a session with cookies but if the client disables the cookies, then it won’t work. There are two types of cookies. * Non-persistent cookie It is valid for single session only. It is removed each time when user closes the browser. * Persistent cookie It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout or signout. Oe Session Tracking byte”! Session Tracking 2. Hidden Form Field + The Server embeds new hidden Fields in every dynamically generated From page for the client. when the client submits the form to the server the hidden fields identify the client. + Hidden field is an invisible text box of the form page, hidden field value goes to the server as a request parameter when the form is submitted. * It always work whether cookie is disabled or not. Disadvantages: * The documents need to be embedded the data inside, waste bandwidth. Need to embed the result from the previous page on the next page. Everyone can see the embedded data by viewing the original source code. We cannot store all kinds of java objects in hidden boxes except text/string values. Oe Session Tracking 3. URL Rewriting * URL rewriting is a process of appending or modifying any url structure while loading a page. It will always work whether cookie is disabled or not (browser independent). * Extra form submission is not required on each pages. * It works only with Link. OS Session Tracking 4. HttpSession * HttpSession interface enables a servlet to read and write the state information that is associated with an HTTP session. A session contains information, specific to a particular user across the whole application. When a user enters into a website for the first time. Session Management facility creates a unique session ID and typically sends it back to the browser as a cookie or store in request parameter. * Each subsequent request from this user passes the cookie containing the session ID, and the Session Management facility uses this ID to find the user's existing HttpSession object. + HttpSession is obtained via request.getSession(). * The default timeout value is 30 minutes. OS Session Tracking The HttpServietRequest interface provides two methods to get the object of HttpSession: public HttpSession getSession() Returns the current session associated with this request, or if the request does not have a session, creates one. public HttpSession getSession(boolean create) Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session. OS Session Tracking Commonly used methods of HttpSessi public String getld() Returns a string containing the unique identifier value. public long getCreationTime() Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. public long getLastAccessedTime() Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT. public void invalidate() Invalidates this session then unbinds any objects bound to it. Oe Session Tracking Commonly used methods of HttpSession interface public void setAttribute(String name, Object value) : Binds the object with a name and stores the name/value pair as an attribute of the HttpSession object. It replaces the existing ‘one If an attribute already exists. public Object getAttribute(String name) : Returns the String object specified in the parameter, from the session object. If no object is found for the specified attribute, then the getAttribute() method returns null. public Enumeration getAttributeNames() : Returns an Enumeration that contains the name of all the objects that are bound as attributes to the session object. public void removeAttribute(String name) : Removes the given attribute from session. setMVaxinactivelnterval(int interval) : Sets the session inactivity time in seconds. This is the time in seconds that specifies how long a sessions remains active since last request received from client. Oe

You might also like