Presentation is loading. Please wait.

Presentation is loading. Please wait.

K. K. Wagh Polytechnic, Nashik

Similar presentations


Presentation on theme: "K. K. Wagh Polytechnic, Nashik"— Presentation transcript:

1 K. K. Wagh Polytechnic, Nashik
Advance Java Programming Ch. No Name Marks 01 AWT 24 02 Networking 18 03 JDBC 20 04 Swing 05 Servlet Mr. Suyog. S. Dhoot Lecturer (IF Dept) K. K. Wagh Polytechnic, Nashik

2 Request-response model.
Introduction – request-response model Request-response model. HTTP Request request Server <html> <head> <body> <html> <head> <body> Client response HTTP HTML

3 HTTP Request HTTP Response
Introduction – what is a request and response HTTP Request HTTP Response Key elements of a “request” stream: HTTP method (action to be performed). The page to access (a URL). Form parameters. Key elements of a “response” stream: A status code (for whether the request was successful). Content-type (text, picture, html, etc…). The content ( the actual content).

4 HTTP Methods GET HEAD POST OPTIONS PUT DELETE TRACE

5 Where does Servlet come into the picture?
Introduction – What is a Servlet Where does Servlet come into the picture? I can serve only static HTML pages Web Server Application Not a problem. I can handle dynamic requests. Helper Application Web Server machine “The Helper Application is nothing but a SERVLET”

6 Servlet Small Program execute on server side on web connection
Runs on server side Not depend on browser compability It reads Explicit and implicit data and generate result Useful in e -commerce application

7 CGI Scripts CGI stands for “Common Gateway Interface” server
Client sends a request to server Server starts a CGI script client server Script computes a result for server and quits script script Server returns response to client Another client sends a request Server starts the CGI script again Etc.

8 Servlets A servlet is like an applet, but on the server side server
Client sends a request to server Server starts a servlet client server Servlet computes a result for server and does not quit servlet Server returns response to client Another client sends a request Server calls the servlet again Etc.

9 Servlet Alternatives Cold Fusion
PHP: Open Source with file upload and session management ASP Windows IIS ASP.net JSP: Extension of Servlet

10 What is a Web Container? Servlet Architecture -Web Container Servlet
request GET. ….. GET. ….. GET. ….. Web Server Web Container Servlet Client

11 How does the Container handle a request?
Servlet Architecture – Web Container How does the Container handle a request? Servlet request Web Container Http request response Thread Web Server <Html> <Body> ……. </Body> </Html> response Service() Client doGet() Apache: Server Tomcat: Servlet Engine

12 Benefits Efficiency: More efficient – uses lightweight java threads
Persistency: Servlets remain in memory. They can maintain state between requests. Portability: Since servlets are written in Java, they are platform independent. Robustness: Error handling, Garbage collector to prevent problems with memory leaks. Security: Security provided by the server as well as the Java Security Manager. Widespread acceptance: Java is a widely accepted technology. This means that numerous vendors work on Java-based technologies

13 Disadvantages High Maintenance High Complexity
Working Disadvantages High Maintenance High Complexity Lower network efficiency More parts to be configure.

14 Servlet API Contains two package Javax.servlet.* Javax.servlet.http.*
GenericServlet HTTPServlet 14 IBM 14

15 Javax.servlet.* Interfaces Servlet ServletConfig
ServletContext: servlet access information about their environment ServletRequest ServletResponse SingleThreadModel 15 IBM 15

16 Javax.servlet.* Classes GenericServlet :implants Servlet
ServletInputSteam ServletOutputStream: ServletRequest Exception ServletException UnavailableException 16 IBM 16

17 Life Cylce of Servlet 17 IBM

18 Life Cylce of Servlet Init() 1) It request for servlet
2) Loading of servlet 3) Resources initialized 4) Once called 5) Parameter: ServletConfig 18 IBM

19 Life Cylce of Servlet Service() 1) Handle request of client
2) only single instance created 3) Process client request and give response 4) Parameters: ServletRequest, ServletResponse 5) Only work with generic servlet 19 IBM

20 Life Cylce of Servlet Destroy()
This method signifies the end of a servlet’s life. The resources allocated during init( ) are released. Save persistent information that will be used the next time the servlet is loaded. The servlet engine unloads the servlet. Calling destroy( ) yourself will not acutally unload the servlet. Only theservlet engine can do this. 20 IBM

21 First example import java.io.*; import javax.servlet.*;
public class Pract15 extends GenericServlet { public void service(ServletRequest r, ServletResponse res) throws IOException, ServletException res.setContentType("text/html"); PrintWriter p = res.getWriter(); p.println("<HTML>"); p.println("<HEAD> Hello </HEAD>"); p.println("</HTML>"); } 21 IBM

22 ServletConfig getServletContext() getInitParameter(String name)
getServletName() getInitParameterNames() - Enumeration 22 IBM 22

23 ServletRequest getContentLength() getContentType()
getParamenter(String name) getParameterNames() getParameterValues ( String name) getProtocol() getRemoteHost() getRemoteAddr() 23 IBM

24 ServletResponse getCharacterEncoding() setContentType(string type)
setContentLength(int length) 24 IBM

25 HttpServlet Interface HttpServletRequest HttpServletResponse
HttpSession : Allows session data to be read or written HttpSessionBindingListener: Informs Object that it bound or unbound from session 25 IBM

26 HttpServlet Classes HttpServlet Cookie HttpSessionEvent
HttpSessionBindingEvent 26 IBM

27 HttpServlet Method doGet doPost doTrace doOptions doDelete doPut
doHead

28 HttpServletRequset Method
getHeader (String field) getHeaderNames() getMethod() getPathInfo() getQueryString()

29 HttpServletResponse Method
containsHeader (String Field) sendError (int c) sendError (int c,String s) sendRedirect (String url) setHeader (String Field, String Value)

30 Error Constant 202 SC_ACCEPTED 400 SC_BAD_REQUEST 403 SC_FORBIDDEN 200
SC_OK 404 SC_NOT_FOUND

31 Session Management Session: how long Particular User alive in the application Session Expires: Server Stopped Client Logout Session Management: Keeping Track of User Activities throughout application

32 Need of Session Management
HTTP is stateless Protocol Separate Connection to web server when cient request for web page Server not maintain information of client E.g. Online Shopping

33 Techniques for session Tracking
User Authentication URL Rewriting Hidden Form Field Cookie

34 User Authentication Servlet stores client username and password
Easy to Implement and access site from different machine Client has to register his account

35 URL Rewriting Adding extra information along with client request
Extra information: Session ID More burden on server E.g. id=252

36 HiddenFormField Fields are added to html form
Fields are not visible in client browser Fields info pass to server that act as visible field Not for static document and document

37 Cookie Small amount of information
Sent from server that store in client Uniquely identify client Cookie send along with client request Present in javax.servlet.http.* package

38 Creating Cookie Cookie c1=new Cookie (String name, String value)
Name and Value is mandatory parameter Neither the name nor the value should contain white space or any of the following characters: [ ] ( ) = , " / : ; Cookie may be temporary or persistent browsers generally only accept 20 cookies per site and 300 cookies total and since each cookie can be limited to 4 kilobytes

39 Cookie Attribute Attribute Type Mandatory? Name String Yes Value
MaxAge int No Secure Boolean Comment Path Version

40 Cookie Methods setX() getX() X: Cookie Attribute Name

41 Cookie operations Send Cookie by server response.addCookie (Cookie c1)
Retrieve Cookie request.getCookies() Return array of cookie

42 Sample code PrintWriter out= response.getWriter()
Cookie c[]= request.getCookies() for( int i=0; i<c.length; i++) { Cookie c1=c[i]; out.println (“”+ c1. getName()); out.println (“”+ c1. getValue()); }

43 Servlet Filter A filter is an object that is invoked at the preprocessing and postprocessing of a request. It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc. The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove the entry of filter from the web.xml file, filter will be removed automatically and we don't need to change the servlet. The filters execute in the order that they are declared in the deployment descriptor. A filter is simply a Java class that implements the javax.servlet.Filter interface

44 javax.servlet.Filter methods

45 Servlet Chaining Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request.  . In servlet chaining, one servlet's output is piped to the next servlet's input. This process continues until the last servlet is reached. Its output is then sent back to the client. 

46 Servlet Chaining The javax.servlet.RequestDispatcher interface comes with only two methods of include() and forward() RequestDispatcher is used whenever the Programmer would like dispatch the request to another resource (like HTML. Servlet, JSP etc.) on the server .

47 Servlet Chaining


Download ppt "K. K. Wagh Polytechnic, Nashik"

Similar presentations


Ads by Google