SlideShare a Scribd company logo
Request Dispatching Request Dispatching is mechanism through which we can forward a request  to another servlet at server side. This is, We can write application where one servlet/jsp processes a request partially and then invokes another servlet, JSP or html page to do further processing. This functionality is provided in the servlet API in the form of javax.servlet.RequestDispatcher interface. An object implementing the RequestDispatcher interface may be obtained via the following methods:  ServletContext.getRequestDispatcher(String path)  ServletContext.getNamedDispatcher(String name)  ServletRequest.getRequestDispatcher(String path)  The ServletContext.getRequestDispatcher method takes a String argument describing a path within the scope of the ServletContext. This path must be relative to the root of the ServletContext and begin with a '/'.  The ServletContext.getNamedDispatcher method takes a String argument indicating the NAME of a servlet known to the ServletContext.
Request Dispatching The ServletContext.getRequestDispatcher method takes a String argument describing a path within the scope of the ServletContext. This path must be relative to the root of the ServletContext and begin with a '/'.  Suppose context path is  http://localhost:8080/myapp Then to forward request to http://localhost:8080/myapp/servlet/login Call getServletContext.getRequestDispatcher(“/servlet/login”); The ServletContext.getNamedDispatcher method takes a String argument indicating the NAME of a servlet known to the ServletContext. For ex: getServletContext.getRequestDispatcher(“HelloServlet”);
Request Dispatching To allow RequestDispatcher objects to be obtained using relative paths that are relative to the path of the current request (not relative to the root of the ServletContext), the ServletRequest.getRequestDispatcher method is provided in the ServletRequest interface.  The servlet container uses information in the request object to transform the given relative path against the current servlet to a complete path. For example, in a context rooted at '/' and a request to /garden/tools.html, a request dispatcher obtained via ServletRequest.getRequestDispatcher("header.html") will behave exactly like a call to ServletContext.getRequestDispatcher("/garden/header.html").
Request Dispatching RequestDispatcher creation and using.   public class Dispatcher extends HttpServlet {  public void doGet(HttpServletRequest req, HttpServletResponse res) {  RequestDispatcher dispatcher =  request.getRequestDispatcher("/template.jsp");  if (dispatcher != null)  dispatcher.forward(request, response);  } }  forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.
Request Dispatching public class Dispatcher extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner");  if (dispatcher != null)  dispatcher.include(request, response);  } } Includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic server-side includes. The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.
Request Dispatching: include Vs forward The include method of the RequestDispatcher interface may be called at ANY time. The target servlet of the include method has access to all aspects of the request object, but its use of the response object is more limited. It can only write information to the ServletOutputStream or Writer of the response object and commit a response by writing content past the end of the response buffer, or by explicitly calling the flushBuffer method of the ServletResponse interface. It CANNOT set headers or call any method that affects the headers of the response. Any attempt to do so must be ignored.  The forward method of the RequestDispatcher interface may be called by the calling servlet ONLY when NO output has been committed to the client. If output data exists in the response buffer that has not been committed, the content must be cleared before the target servlet's service method is called. If the response has been committed, an IllegalStateException must be thrown.
Request Dispatching: include Vs forward The ServletContext and ServletRequest methods that create RequestDispatcher objects using path information allow the optional attachment of query string information to the path. For example, a Developer may obtain a RequestDispatcher by using the following code:  String path = "/raisins.jsp?orderno=5";  RequestDispatcher rd = context.getRequestDispatcher(path); rd.include(request, response);  Parameters specified in the query string used to create the RequestDispatcher take precedence over other parameters of the same name passed to the included servlet. The parameters associated with a RequestDispatcher are scoped to apply only for the duration of the include or forward call.
sendRedirect sendRedirect method of HttpServletResponse object will tell the client that it should send a request to the specified path. So the client will build a new request and submit it to the server. protected void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException,IOException {    response.sendRedirect("pathToResource"); }
sendRedirect sendRedirect method of HttpServletResponse object will tell the client that it should send a request to the specified path. So the client will build a new request and submit it to the server. protected void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException,IOException {    response.sendRedirect("pathToResource"); } So the client will build a new request and submit it to the server, because a new request is being submitted all previous parameters stored in the request will be unavailable. The client's history will be updated so the forward and back buttons will work.
sendRedirect vs RequestDispatcher.forward In case of RequestDispatcher.forward the response will not be sent back to the client and so the client will not know about this change of resource on the server. This method is useful for communicating between server resources, (servlet to servlet). Because the request and response are forwarded to another resource all request parameters are maintained and available for use.  Since the client does not know about this forward on the server, no history of it will be stored on the client, so using the back and forward buttons will not work.  This method is faster than using sendRedirect as no network round trip to the server and back is required.
SendRedirect Example <html> <head> <title>New Page 1</title> </head> <body> <form method=&quot;POST&quot; action=&quot;/SendRedirect/SendRedirectServlet&quot;> <p>Enter your name   <input type=&quot;text&quot; name=&quot;username&quot; size=&quot;20&quot;></p>   <p>Enter your password<input type=&quot;text&quot; name=&quot;password&quot; size=&quot;20&quot;></p> <p> <input type=&quot;submit&quot; value=&quot;Submit&quot; name=&quot;B1&quot;></p> </form> </body>
SendRedirect Example import  java.io.*; import  javax.servlet.*; import  javax.servlet.http.*; public class  SendRedirectServlet  extends  HttpServlet{    protected void  doPost(HttpServletRequest request, HttpServletResponse response)    throws  ServletException, IOException {      response.setContentType(&quot;text/html&quot;);     PrintWriter pw = response.getWriter();     String name = request.getParameter(&quot;username&quot;);     String password = request.getParameter(&quot;password&quot;);      if (name.equals(&quot;James&quot;)&& password.equals(&quot;abc&quot;)){       response.sendRedirect(&quot;/SendRedirect/ValidUserServlet&quot;);     }      else {       pw.println(&quot;u r not a valid user&quot;);     }   } }
SendRedirect Example import  java.io.*; import  javax.servlet.*; import  javax.servlet.http.*; public class  ValidUserServlet  extends  HttpServlet{ protected void  doGet(HttpServletRequest request, HttpServletResponse response)                                          throws  ServletException, IOException  {   PrintWriter pw = response.getWriter();   pw.println(&quot;Welcome<br> &quot; + &quot; &quot;);   pw.println(&quot;how are you&quot;); } }
SendRedirect Example <?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?> <!DOCTYPE web-app  PUBLIC &quot;-//Sun Microsystems, Inc.//DTD Web  Application  2.3//EN&quot;  &quot;http://java.sun.com/dtd/web-app_2_3.dtd&quot;> <web-app>  <servlet>  <servlet-name>Zulfiqar</servlet-name>  <servlet- class >SendRedirectServlet</servlet- class >  </servlet>  <servlet-mapping>  <servlet-name>Zulfiqar</servlet-name>  <url-pattern>/SendRedirectServlet</url-pattern>  </servlet-mapping>  <servlet>  <servlet-name>Hello</servlet-name>  <servlet- class >ValidUserServlet</servlet- class >  </servlet>  <servlet-mapping>  <servlet-name>Hello</servlet-name>  <url-pattern>/ValidUserServlet</url-pattern>  </servlet-mapping> </web-app>
SendRedirect Example
SendRedirect Example
Session Tracking in Servlet As we know that the Http is a  stateless  protocol, means that it can't persist the information. It always treats each request as a new request. In Http client makes a connection to the  server , sends the request., gets the response, and closes the connection. In session management client first make a request for any servlet or any page, the container receives the request and generate a unique session ID and gives it back to the client along with the response. This ID gets stores on the client machine. Thereafter when the client request again sends a request to the server then it also sends the session Id with the request. There the container sees the Id and sends back the request.
Session Tracking in Servlet Session Tracking can be done in three ways: Hidden Form Fields:  This is one of the way to support the session tracking. As we know by the name, that in this fields are added to an HTML form which are not displayed in the client's request. The hidden form field are sent back to the server when the form is submitted. In hidden form fields the html entry will be like this :  <input type =&quot;hidden&quot; name = “sessionid&quot; value=“44b4&quot;>.  This means that when you submit the form, the specified name and value will be get included in get or post method. In this session ID information would be embedded within the form as a hidden field and submitted with the Http POST command.
Session Tracking in Servlet URL Rewriting:  This is another way to support the session tracking.  URLRewriting  can be used in place where we don't want to use cookies.  In this session id information is embedded in URL . In this way http:// mail.mysite.com/mail/compose.jsp;jsessionid =44b44  ? user= james Here sessionid info is stored after semicolon between target resource name and query string. To use URL rewriting one must encode all the URLs using encodeURL() method of HttpServletResponse class. encodeURL(String URL) – this method embed the session id into the passed URL and return new URL.
Session Tracking Cookies:  When cookie based session management is used, a token is generated which contains user's information, is sent to the browser by the server. The cookie is sent back to the server when the user sends a new request. By this cookie, the server is able to identify the user. In this way the session is maintained. Cookie is nothing but a name- value pair, which is stored on the client machine. By default the cookie is implemented in most of the browsers. If we want then we can also disable the cookie.
Session Handling in Servlet How to create a session: Session is created in servlet by calling getSession() method on HttpServletRequest object.  Two variant of getSession exist: HttpSession getSession(boolean flag)  -  returns HttpSession object associated with particular user if exist. If no session exist currently and flag argument is true then new session is created for the user. HttpSession getSession() – returns HttpSession object associated with current user if no session exist currently a new session is created.  So, This call is equivalent to calling getSession(true).
HttpSession Interface Methods: long getCreationTime() Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.  String getId()   Returns a string containing the unique identifier assigned to this session.  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, and marked by the time the container recieved the request.  getMaxInactiveInterval ()            Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.  getServletContext ()            Returns the ServletContext to which this session belongs.
HttpSession Interface 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, and marked by the time the container recieved the request.   int  getMaxInactiveInterval ()             Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.  void   invalidate ()            Invalidates this session then unbinds any objects bound to it.  boolean   isNew ()            Returns true if the client does not yet know about the session or if the client chooses not to join the session.  void   setMaxInactiveInterval (int interval)            Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.
Methods to do I/O in Servlet ServletRequest: ServletInputStream getInputStream() throws IOException Returns the binary input stream associated with this request object. BufferedReader getReader() throws IOException Returns a character stream associated with this request. ServletResponse OutputStream getOutputStream() throws IOException Returns the binary output stream associated with this request object. PrintWriter getWriter() throws IOException Returns a character output stream associated with this request.
Threading Model Default threading Model – Single instance multiple thread  By default the servlet container loads only a single instance of a servlet. Requests serviced by the servlet are run in a separate thread and share the same instance. Since there is only a single instance, there is also only one set of instance variables.  Instance variables are not thread Safe. Single Thread Model Although the single instance multiple thread model is the default, a servlet can change this behaviour by implementing SingleThreadModel. This interface, which has has no methods, informs the container that is should create a pool of instances and allocate each incoming request to its own instance and thread. Instance variables are thread safe in single thread model.
Methods to do I/O in Servlet ServletRequest: ServletInputStream getInputStream() throws IOException Returns the binary input stream associated with this request object. BufferedReader getReader() throws IOException Returns a character stream associated with this request. ServletResponse OutputStream getOutputStream() throws IOException Returns the binary output stream associated with this request object. PrintWriter getWriter() throws IOException Returns a character output stream associated with this request.
Threading Model Default threading Model – Single instance multiple thread  By default the servlet container loads only a single instance of a servlet. Requests serviced by the servlet are run in a separate thread and share the same instance. Since there is only a single instance, there is also only one set of instance variables.  Instance variables are not thread Safe. Single Thread Model Although the single instance multiple thread model is the default, a servlet can change this behaviour by implementing SingleThreadModel. This interface, which has has no methods, informs the container that is should create a pool of instances and allocate each incoming request to its own instance and thread. Instance variables are thread safe in single thread model.

More Related Content

Request dispatching in servlet

  • 1. Request Dispatching Request Dispatching is mechanism through which we can forward a request to another servlet at server side. This is, We can write application where one servlet/jsp processes a request partially and then invokes another servlet, JSP or html page to do further processing. This functionality is provided in the servlet API in the form of javax.servlet.RequestDispatcher interface. An object implementing the RequestDispatcher interface may be obtained via the following methods: ServletContext.getRequestDispatcher(String path) ServletContext.getNamedDispatcher(String name) ServletRequest.getRequestDispatcher(String path) The ServletContext.getRequestDispatcher method takes a String argument describing a path within the scope of the ServletContext. This path must be relative to the root of the ServletContext and begin with a '/'. The ServletContext.getNamedDispatcher method takes a String argument indicating the NAME of a servlet known to the ServletContext.
  • 2. Request Dispatching The ServletContext.getRequestDispatcher method takes a String argument describing a path within the scope of the ServletContext. This path must be relative to the root of the ServletContext and begin with a '/'. Suppose context path is http://localhost:8080/myapp Then to forward request to http://localhost:8080/myapp/servlet/login Call getServletContext.getRequestDispatcher(“/servlet/login”); The ServletContext.getNamedDispatcher method takes a String argument indicating the NAME of a servlet known to the ServletContext. For ex: getServletContext.getRequestDispatcher(“HelloServlet”);
  • 3. Request Dispatching To allow RequestDispatcher objects to be obtained using relative paths that are relative to the path of the current request (not relative to the root of the ServletContext), the ServletRequest.getRequestDispatcher method is provided in the ServletRequest interface. The servlet container uses information in the request object to transform the given relative path against the current servlet to a complete path. For example, in a context rooted at '/' and a request to /garden/tools.html, a request dispatcher obtained via ServletRequest.getRequestDispatcher(&quot;header.html&quot;) will behave exactly like a call to ServletContext.getRequestDispatcher(&quot;/garden/header.html&quot;).
  • 4. Request Dispatching RequestDispatcher creation and using. public class Dispatcher extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) { RequestDispatcher dispatcher = request.getRequestDispatcher(&quot;/template.jsp&quot;); if (dispatcher != null) dispatcher.forward(request, response); } } forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.
  • 5. Request Dispatching public class Dispatcher extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(&quot;/banner&quot;); if (dispatcher != null) dispatcher.include(request, response); } } Includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic server-side includes. The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.
  • 6. Request Dispatching: include Vs forward The include method of the RequestDispatcher interface may be called at ANY time. The target servlet of the include method has access to all aspects of the request object, but its use of the response object is more limited. It can only write information to the ServletOutputStream or Writer of the response object and commit a response by writing content past the end of the response buffer, or by explicitly calling the flushBuffer method of the ServletResponse interface. It CANNOT set headers or call any method that affects the headers of the response. Any attempt to do so must be ignored. The forward method of the RequestDispatcher interface may be called by the calling servlet ONLY when NO output has been committed to the client. If output data exists in the response buffer that has not been committed, the content must be cleared before the target servlet's service method is called. If the response has been committed, an IllegalStateException must be thrown.
  • 7. Request Dispatching: include Vs forward The ServletContext and ServletRequest methods that create RequestDispatcher objects using path information allow the optional attachment of query string information to the path. For example, a Developer may obtain a RequestDispatcher by using the following code: String path = &quot;/raisins.jsp?orderno=5&quot;; RequestDispatcher rd = context.getRequestDispatcher(path); rd.include(request, response); Parameters specified in the query string used to create the RequestDispatcher take precedence over other parameters of the same name passed to the included servlet. The parameters associated with a RequestDispatcher are scoped to apply only for the duration of the include or forward call.
  • 8. sendRedirect sendRedirect method of HttpServletResponse object will tell the client that it should send a request to the specified path. So the client will build a new request and submit it to the server. protected void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException,IOException { response.sendRedirect(&quot;pathToResource&quot;); }
  • 9. sendRedirect sendRedirect method of HttpServletResponse object will tell the client that it should send a request to the specified path. So the client will build a new request and submit it to the server. protected void doGet(HttpServletRequest request, HttpServletResponse response ) throws ServletException,IOException { response.sendRedirect(&quot;pathToResource&quot;); } So the client will build a new request and submit it to the server, because a new request is being submitted all previous parameters stored in the request will be unavailable. The client's history will be updated so the forward and back buttons will work.
  • 10. sendRedirect vs RequestDispatcher.forward In case of RequestDispatcher.forward the response will not be sent back to the client and so the client will not know about this change of resource on the server. This method is useful for communicating between server resources, (servlet to servlet). Because the request and response are forwarded to another resource all request parameters are maintained and available for use. Since the client does not know about this forward on the server, no history of it will be stored on the client, so using the back and forward buttons will not work. This method is faster than using sendRedirect as no network round trip to the server and back is required.
  • 11. SendRedirect Example <html> <head> <title>New Page 1</title> </head> <body> <form method=&quot;POST&quot; action=&quot;/SendRedirect/SendRedirectServlet&quot;> <p>Enter your name  <input type=&quot;text&quot; name=&quot;username&quot; size=&quot;20&quot;></p>   <p>Enter your password<input type=&quot;text&quot; name=&quot;password&quot; size=&quot;20&quot;></p> <p> <input type=&quot;submit&quot; value=&quot;Submit&quot; name=&quot;B1&quot;></p> </form> </body>
  • 12. SendRedirect Example import  java.io.*; import  javax.servlet.*; import  javax.servlet.http.*; public class  SendRedirectServlet  extends  HttpServlet{    protected void  doPost(HttpServletRequest request, HttpServletResponse response)    throws  ServletException, IOException {      response.setContentType(&quot;text/html&quot;);     PrintWriter pw = response.getWriter();     String name = request.getParameter(&quot;username&quot;);     String password = request.getParameter(&quot;password&quot;);      if (name.equals(&quot;James&quot;)&& password.equals(&quot;abc&quot;)){       response.sendRedirect(&quot;/SendRedirect/ValidUserServlet&quot;);     }      else {       pw.println(&quot;u r not a valid user&quot;);     }   } }
  • 13. SendRedirect Example import  java.io.*; import  javax.servlet.*; import  javax.servlet.http.*; public class  ValidUserServlet  extends  HttpServlet{ protected void  doGet(HttpServletRequest request, HttpServletResponse response)                                          throws  ServletException, IOException  {   PrintWriter pw = response.getWriter();   pw.println(&quot;Welcome<br> &quot; + &quot; &quot;);   pw.println(&quot;how are you&quot;); } }
  • 14. SendRedirect Example <?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?> <!DOCTYPE web-app  PUBLIC &quot;-//Sun Microsystems, Inc.//DTD Web  Application  2.3//EN&quot;  &quot;http://java.sun.com/dtd/web-app_2_3.dtd&quot;> <web-app>  <servlet>  <servlet-name>Zulfiqar</servlet-name>  <servlet- class >SendRedirectServlet</servlet- class >  </servlet>  <servlet-mapping>  <servlet-name>Zulfiqar</servlet-name>  <url-pattern>/SendRedirectServlet</url-pattern>  </servlet-mapping>  <servlet>  <servlet-name>Hello</servlet-name>  <servlet- class >ValidUserServlet</servlet- class >  </servlet>  <servlet-mapping>  <servlet-name>Hello</servlet-name>  <url-pattern>/ValidUserServlet</url-pattern>  </servlet-mapping> </web-app>
  • 17. Session Tracking in Servlet As we know that the Http is a stateless protocol, means that it can't persist the information. It always treats each request as a new request. In Http client makes a connection to the server , sends the request., gets the response, and closes the connection. In session management client first make a request for any servlet or any page, the container receives the request and generate a unique session ID and gives it back to the client along with the response. This ID gets stores on the client machine. Thereafter when the client request again sends a request to the server then it also sends the session Id with the request. There the container sees the Id and sends back the request.
  • 18. Session Tracking in Servlet Session Tracking can be done in three ways: Hidden Form Fields: This is one of the way to support the session tracking. As we know by the name, that in this fields are added to an HTML form which are not displayed in the client's request. The hidden form field are sent back to the server when the form is submitted. In hidden form fields the html entry will be like this : <input type =&quot;hidden&quot; name = “sessionid&quot; value=“44b4&quot;>. This means that when you submit the form, the specified name and value will be get included in get or post method. In this session ID information would be embedded within the form as a hidden field and submitted with the Http POST command.
  • 19. Session Tracking in Servlet URL Rewriting: This is another way to support the session tracking. URLRewriting can be used in place where we don't want to use cookies. In this session id information is embedded in URL . In this way http:// mail.mysite.com/mail/compose.jsp;jsessionid =44b44 ? user= james Here sessionid info is stored after semicolon between target resource name and query string. To use URL rewriting one must encode all the URLs using encodeURL() method of HttpServletResponse class. encodeURL(String URL) – this method embed the session id into the passed URL and return new URL.
  • 20. Session Tracking Cookies: When cookie based session management is used, a token is generated which contains user's information, is sent to the browser by the server. The cookie is sent back to the server when the user sends a new request. By this cookie, the server is able to identify the user. In this way the session is maintained. Cookie is nothing but a name- value pair, which is stored on the client machine. By default the cookie is implemented in most of the browsers. If we want then we can also disable the cookie.
  • 21. Session Handling in Servlet How to create a session: Session is created in servlet by calling getSession() method on HttpServletRequest object. Two variant of getSession exist: HttpSession getSession(boolean flag) - returns HttpSession object associated with particular user if exist. If no session exist currently and flag argument is true then new session is created for the user. HttpSession getSession() – returns HttpSession object associated with current user if no session exist currently a new session is created. So, This call is equivalent to calling getSession(true).
  • 22. HttpSession Interface Methods: long getCreationTime() Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. String getId()   Returns a string containing the unique identifier assigned to this session. 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, and marked by the time the container recieved the request. getMaxInactiveInterval ()           Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. getServletContext ()           Returns the ServletContext to which this session belongs.
  • 23. HttpSession Interface 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, and marked by the time the container recieved the request. int getMaxInactiveInterval ()            Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. void invalidate ()           Invalidates this session then unbinds any objects bound to it. boolean isNew ()           Returns true if the client does not yet know about the session or if the client chooses not to join the session. void setMaxInactiveInterval (int interval)           Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.
  • 24. Methods to do I/O in Servlet ServletRequest: ServletInputStream getInputStream() throws IOException Returns the binary input stream associated with this request object. BufferedReader getReader() throws IOException Returns a character stream associated with this request. ServletResponse OutputStream getOutputStream() throws IOException Returns the binary output stream associated with this request object. PrintWriter getWriter() throws IOException Returns a character output stream associated with this request.
  • 25. Threading Model Default threading Model – Single instance multiple thread By default the servlet container loads only a single instance of a servlet. Requests serviced by the servlet are run in a separate thread and share the same instance. Since there is only a single instance, there is also only one set of instance variables. Instance variables are not thread Safe. Single Thread Model Although the single instance multiple thread model is the default, a servlet can change this behaviour by implementing SingleThreadModel. This interface, which has has no methods, informs the container that is should create a pool of instances and allocate each incoming request to its own instance and thread. Instance variables are thread safe in single thread model.
  • 26. Methods to do I/O in Servlet ServletRequest: ServletInputStream getInputStream() throws IOException Returns the binary input stream associated with this request object. BufferedReader getReader() throws IOException Returns a character stream associated with this request. ServletResponse OutputStream getOutputStream() throws IOException Returns the binary output stream associated with this request object. PrintWriter getWriter() throws IOException Returns a character output stream associated with this request.
  • 27. Threading Model Default threading Model – Single instance multiple thread By default the servlet container loads only a single instance of a servlet. Requests serviced by the servlet are run in a separate thread and share the same instance. Since there is only a single instance, there is also only one set of instance variables. Instance variables are not thread Safe. Single Thread Model Although the single instance multiple thread model is the default, a servlet can change this behaviour by implementing SingleThreadModel. This interface, which has has no methods, informs the container that is should create a pool of instances and allocate each incoming request to its own instance and thread. Instance variables are thread safe in single thread model.