Servlet concepts : 1. What's the difference between applets and servlets? A: There are many fundamental differences between Applet and Servlet classes, the Java API documentation for the two types will show you they have little in common. Applets are essentially graphical user interface (GUI) applications that run on the client side in a network environment, typically embedded in an HTML page. Applets are normally based on Abstract Windowing Toolkit components to maintain backward-compatibility with the widest range of browsers' Java implementations. The application classes are downloaded to the client and run in a Java Virtual Machine provided by the browser, in a restrictive security environment called a "sandbox". Servlets are used to dynamically generate HTTP responses and return HTML content to Web browsers on the server side. Servlets are often used to validate and process HTML form submissions and control a series of user interactions in what is known as a Web application. Servest can be used to control all aspects of the request and response exchange between a Web browser and the server, called a servlet container. 2. Do we open servlet classes directly instead of HTML? A: Servlets are used to deliver HTML to Web browsers, but they are not like static HTML documents. When you set up a servlet in a Web application it has a URL like a static HTML document, so you can link to it, bookmark it or send the URL by email, just as you would with an standard Web page. The main difference is that the HTML sent to the Web browser is composed dynamically by the servlet and its contents can be customized based on the details of the request sent by the Web browser. When you open a servlet URL the browser does not display content of the servlet class, but a dynamic HTML document created by the servlet. The servlet class is written as a standard Java class that extends the HttpServlet class. In its most basic form, the HTML output can be created by a series of print() statements on a PrintWriter. The method that handles simple Web requests is called doGet(), as below.
public final void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter output = response.getWriter(); output.println("<html>"); output.println(" <head>"); output.println(" <title>"); // Other HTML output output.flush(); output.close(); }

3. What part of the Java platform do servlets and JSP belong to? A: The servlet and JSP APIs are a standard extension to the core Java API and runtime system. Their package names are prefixed javax to indicate they are standard extensions, but that means that they rely upon a code implementation provided by a specific vendor.

For example, the Apache Tomcat project supplies its own implementation of the servlet and JSP API that is integrated with the servlet container. Developers must compile their code using the vendor's servlet package implementation by including it in the compiler's classpath. The servlet container includes the same package classes in its runtime system and feeds concrete instances of the servlet interface types to the servlet's lifecycle methods. 4. How does the JVM execute a servlet compared with a regular Java class? A: Servlets are standard Java classes and are executed by the Java Virtual Machine in exactly the same way as any other. However, the environment or context in which servlets are executed is different. A servlet is not invoked directly through a main() method, the class is loaded and run by a servlet container. When you run a servlet container, it reads its configuration, identifies the servlet classes to make available, and uses the Java classloader system to load and run the servlets. When the servlets are first brought into service, the servlet container calls the servlet's init() method and passes the ServletConfig object as an argument. Whenever a request is made to the servlet, the container creates a new thread in which to handle it. 5. How can I tell when a servlet is instantiated? A: A servlet must be instantiated before it is brought into service by the servlet container, so one way to check is to make a request to the servlet and check the response. If you need to check indirectly, you can override the init(ServletConfig) method and add log(String)statements to it. This method is called after the servlet container has instantiated the servlet before it is brought into service. Servlet programming 6. How can I write a servlet using Javascript? A: Java servlets is a server side technology that delivers dynamic content to Web browsers and other clients. Javascript is also delivered by a Web server, but the code is only interpreted and executed after it has been downloaded by the Web browser. This means that it is not possible to write servlet code in Javascript. It is possible to include Javascript in the output of servlets and Java Server Pages, just like standard Web pages. It is also possible to dynamically generate Javascript using a servlet and use it as the source for a script tag, though this is only advisable in rare cases. 7. Can I use a normal class to handle my requests? A: Servlets are normal Java classes, they compile and run just like any other class. All that is required is that servlets implement the javax.servlet.Servlet interface. Usually, they extend a protocol-specific class such as javax.servlet.http.HttpServlet. … full answer hidden, click for full answers Premium members click below for full answer Can I use a normal class to handle my requests? 8. Can I include normal Java classes in servlets?

A: Any Java class can be used in a Web application, provided you make the classes available to the servlet container at runtime. The Java API classes can be used directly by adding import statements to your servlet class. Other supporting classes can also be imported, but these classes must be added to the classes or lib directory of your application. If you need to configure the supporting classes, this can be done with standard servlet configuration features using the ServletConfig and ServletContext objects available to theinit(ServletConfig) method. 9. Can I use a constructor in my servlet? A: A servlet is a normal Java class, so when there are no custom constructors, there is an implicit default constructor with no arguments. Servlet containers typically use theClass.newInstance() method to load servlets, so you must be careful to add an explicit default constructor if you add non-default constructors. … full answer hidden, click for full answers Premium members click below for full answer Can I use a constructor in my servlet? 10.What happens if I add a main method to my servlet? A: It is possible to write a main method for a servlet, but it will not be called by the servlet container, it is not part of the servlet lifecycle process. If you invoke your servlet through themain method using the java command it will behave exactly like a standard Java class, it cannot operate as a Web application in its own right and cannot be addressed using HTTP requests. Servlets must run in a servlet container to deliver Web applications as intended. Servlet start up 11.Can one JSP or Servlet extend another Servlet or JSP A: It is possible and necessary for servlets to extend other classes, they are standard Java classes in most respects. Most servlets extend the abstract HttpServlet class included in a servlet container's API implementation. This abstract class implements the generic Servletinterface with HTTP-specific methods and provides a minimal basis to extend and create your own servlet classes. If you need to develop complex behaviour across a set of servlets you can extend this hierarchy to create numerous servlet subclasses. The automatic source code generation and compilation scheme used to create JSP servlets means that extension of the JSP servlet class is more complex and should generally be avoided. 12.How do I compile a servlet? A: To compile a servlet, you will need to have the Java Servlet API classes in your classpath. Most Java servlet containers come with a copy, it may be called servlet.jar or something similar. The basic classes are in the packages javax.servlet and javax.servlet.http. … full answer hidden, click for full answers Premium members click below for full answer How do I compile a servlet?

MYJAVAHUB.g.class 2. The servlet operates as an extension of the servlet container and its code is executed on the server. it only receives standard Web content and renders it accordingly. Create a Web application directory structure under the webapp directory of your servlet container (or use an existing one). e. 9. There are different techniques that can be used to complete these stages. 1. {webapps-dir}/example/WEB-INF/classes 6. In a production environment the servlet container is usually installed on a server that is accessible from the Internet.class 8. Servlet code is compiled to Java class byte code which is physically located on the server hardware with the servlet container. e.Where is the servlet stored and where does it run? A: When you create a servlet. {webapps-dir}/example/WEB-INF/web.COM 13. Place your servlet class file in the WEB-INF/classes directory for your application. Write and compile your servlet. The servlet JAR file is normally distributed with your servlet container. {webapps-dir}/example/WEB-INF 5.xml file for your application (or edit an existing one) and addservlet and servlet-mapping elements for your servlet. 7. click for full answers Premium members click below for full answer Why won't my servlet compile? 14. 15. e.BLOGSPOT. {webapps-dir}/example 4. For Apache Tomcat it is a file named{CATALINA_HOME}/common/lib/servlet-api. the code must be installed in a servlet container which operates as an HTTP server application.g. In the a development environment the servlet container is often installed on a developer's own workstation. Web browsers operate as clients which connect to the servlet container. Add this to your compiler classpath as follows.xml 10. . {webapps-dir}/example/WEB-INF/classes/ExampleServlet.Start the servlet container. so it cannot find the servlet class files.g. e. issue HTTP requests and receive HTTP responses from the servlet container. 3. ExampleServlet. or a hardware server in the local network where it can be accessed privately for testing. but the Java software arrangement is basically the same.Why won't my servlet compile? A: All those "cannot find symbol" error messages mean that you do not have the Java servlet JARfile on your compiler's classpath. described in other FAQ answers.What are the basic steps to run a servlet? A: The key steps in creating and running a servlet are outlined below in the simplest form.jar. The servlet code is not downloaded or executed by the Web browser at all.g. mostly in the form of HTML pages and other Web content. … full answer hidden. Create a WEB-INF/web.

include and redirection? . … full answer hidden.COM 16. request path. HTTP redirection is different from the RequestDispatcher forward() method.What is the difference between JAR and WAR files? A: There is no difference between the binary form of JAR and WAR files. they both use zip compression provided by the jar tool. You can create a WAR file by navigating to the root directory of your Web application and typing the jar command. The source code for chapter 3 is available online.sendRedirect(otherURL). The String argument is the URL for the address you want to direct people to. the servlet container includes it in the hyperlink URLs it generates for servlets and JSP.BLOGSPOT. The browser should automatically create a new HTTP request for the given URL that will be entirely separate from the original request.What's the difference between forward. When you call this method it will issue an HTTP redirect request to the browser. response. commit the servlet response and end the HTTP exchange. HTTP header values and view the headers returned by a Web application. as 19. click for full answers Premium members click below for full answer What is the difference between JAR and WAR files? 17. 18. click for full answers Premium members click below for full answer What is URL-rewriting? 20. String otherURL = "http://example. servlets do not run in their own right. which sends the forwarded content in the original HTTP response stream.Can I access a servlet from a stand alone client? A: It is certainly possible to access a servlet that is hosted in a servlet container. However.How can I redirect a request to another URL? A: The standard servlet method to redirect one HTTP request to another is theHttpServletResponse sendRedirect(String) method. Any HTTPclient should be able to connect to a properly configured servlet container and make requests to a servlet. Look for WebClient. they are not server applications. This application allows you to manually input the and supporting classes. Rather than exchange a session ID in a cookie.jsp".MYJAVAHUB.What is URL-rewriting? A: URL-rewriting is a way of maintaining a session between an HTTP client and a servlet container which does not use cookies. … full answer hidden.How can I write a servlet client for testing? A: Marty Hall provides the source code for a basic HTTP client in his book Core Servlets and Java Server Pages. 21.

click for full answers 22.xml entry. you can overload any servlet lifecycle method. Can't I use a constructor instead of init(ServletConfig)? A: It is possible to have a custom constructor for a servlet. but your overloaded method will not be called directly by the servlet container in preference over the standard lifecycle methods. so long as you also add a default constructor with no arguments. You could create a custom doGet() method to conditionally handle the outcome of the standard doGet() method call. click to get full answers Premium members click below for full answer Can we overload methods in the servlet lifecycle? 24. … full answer hidden.COM A: The RequestDispatcher forward() and include() methods are mechanisms that are internal to a servlet container and do not affect the public URL of a Web resource. At this point. with no arguments. When a servlet is first brought into service. the servlet container will call its init(ServletConfig) method with a servlet configuration object based on its web. … full answer hidden. Can we overload methods in the servlet lifecycle? A: Yes.MYJAVAHUB. the servlet is in its normal service phase and can handle standard service methods.BLOGSPOT. click to get full answers Premium members click below for full answer What is the servlet lifecycle? 23. When you call the forward() method on a RequestDispatcher with a JSP path. it calls the servlet's destroy() method. this effectively becomes the response of the servlet itself. … full answer hidden. Between initialisation and destruction. 25. What is the servlet lifecycle? A: The servlet lifecycle is a standard sequence of callback events that a servlet container will apply to a servlet to bring it into service and control its shut down. the servlet container returns the JSP content on the original servlet's URL. You would need to include a call to your overloaded method in the body of one of the standard lifecycle methods. so it cannot do any useful start-up activity. but constructors are not called in the standard servlet lifecycle. These configuration references are only available through the init(ServletConfig) method. the servlet has no reference to its configuration or the general servlet context.init(config)? A: Servlet programmers are expected to call the super. Servlets are usually instantiated by the servlet container using the Class. When the servlet container takes a servlet out of service.init(ServletConfig) in the init(ServletConfig) method so that the abstract superclass implementation of the method in .newInstance() method. as in the simple example below. Why is it necessary to call super.

26. 27. you must ensure all operations are synchronized or you will get unpredictable results. … full answer hidden. How do I get configuration parameters for a servlet? A: To pass variable values to a servlet. How can I load a Properties file for my servlet? A: There are standard methods for identifying and loading this type of static property set into servlets via the ServletContext object. The close() method of a pooled Connection instance just returns it to the pool.BLOGSPOT. The path must begin . This way you can handle the case where the connection fails. Generally it is better to use the init(ServletConfig) method to register the database driver and get a reference to the DriverManager. The primary method is getResourceAsStream(String path). click to get full answers Premium members click below for full answer What's the difference between ServletConfig and ServletContext? 29. and ensure that all connections are closed in any case. a DataSource or database connection pool. and contains initialisation parameters that are shared amongst all servlets in the application.MYJAVAHUB. Then use the connection provider to get a connection for each request within a try/catch block. The ServletConfig object represents the configuration for a single specific servlet. you should add an initialization parameter to your servlet configuration.COM GenericServlet stores the servlet configuration object. When the configuration object is stored in this way. You must also ensure the connection is closed when the servlet is taken out of service by overriding the servlet's destroy() method. not for each new servlet thread. Should I get my database connection in the init() method? A: The init(ServletConfig) method is only called once when a servlet is brought into service by the servlet container. see the answer to the question What's the difference between ServletConfig and ServletContext? … full answer hidden. the servlet methods getInitParameter(String) and getInitParameterNames() can be called instead of calling the equivalent methods on the configuration object. click to get full answers Premium members click below for full answer How do I get configuration parameters for a servlet? 28. What's the difference between ServletConfig and ServletContext? A: The ServletContext object represents the context for the whole Web application in which a servlet is deployed. If you create a single database connection in the init(ServletConfig) method and use it to all handle servlet requests. which opens an InputStream to the path given in the argument.

If you have a typical destroy() method that does servlet clean-up work before the servlet is taken out of service. /. If the destroy() method is called from the init(ServletConfig) method. What happens if I call destroy() from init()? A: The destroy() method is usually called by the servlet container immediately before it takes a servlet out of service. Normally your application code should not call servlet lifecycle methods. so your servlet is safe to use destroy methods with other signatures. What happens if destroy() is not called? A: The destroy() method and other servlet lifecycle methods are called by the servlet container. but the overloaded version will not be called directly by a servlet container's lifecycle methods. so it would be a serious error if the servlet container did not call the destroy() method as it takes a servlet out of service. 31. It is typically used to clean-up any resource references. Is it possible to overload the destroy() method? A: Any Java method may be overloaded. click to get full answers Premium members click below for full answer How can I load a Properties file for my servlet? The destroy() method 30. so it is not a problem if your application does not call the method at all.MYJAVAHUB. whatever statements are contained in the method will be executed and the method . The servlet container expects all servlets to have a standard no argument destroy() method. but is a normal method in all other respects. so for instance you might use the path: /WEB-INF/servlet.COM with a forward slash. Normally. It is not advisable for your application code to call the destroy() method directly. it is difficult to imagine why you would want to call it from the service() method. though it is … full answer hidden. 33. save temporary data and suchlike.BLOGSPOT. Can I call destroy() from the service() method? A: The destroy() method has a special significance in the servlet lifecycle when it is called by the servlet container. you should handle service requests by overriding the relevant doGet() or doPost() method. public void destroy(final String arg) { // Overloaded method body } 32. and is relative to the context root. it would be confusing and potentially destructive.

If so. the statements it contains are executed like any other method and there is no “special” behaviour triggered beyond that. the servlet container will put the servlet into service regardless.servlet. … full answer hidden. Can I catch an exception and give my own error message? A: Yes. The destroy() method does not stop the servlet. For clarity. it would be better to put whatever statements you want to execute in a separate prepare() or reset() method. If an exception is thrown in your init(ServletConfig) method.RequestDispatcher. you should still throw a ServletException to ensure the servlet is not put into service in this state. The destroy() method could also call those methods as part of its shut-down behaviour.How do I include files in my servlet? A: To achieve an include scheme in a servlet. but if there are exceptional conditions you can anticipate. … full answer hidden. you can catch servlet errors and give custom error pages for them. not a POST request. it would be better for your application to address these directly and try to avoid them in the first place. 34. 37. If the init(ServletConfig) method returns without exception. it depends what statements are in the destroy() method.COM will return. or from ServletRequest or HttpServletRequest in doGet or doPost. So if I call destroy() it won't kill the servlet? A: The destroy() method is designed to be called by the servlet container as it takes the servlet out of service and is intended to allow the servlet to save state and release any resources it may be holding. it may be appropriate to use the destroy() method to help handle the case. which takes the path of the target document in its constructor.MYJAVAHUB. The servlet container is responsible for actually destroying the servlet. In this case any values given in the form's input elements are passed as request parameters to the URL specified in the form's action attribute. A RequestDispatcher can be obtained from the ServletContext object (via ServletConfig) in your servlet's init method. Post requests are normally produced by the submission of an HTML form whose method attribute is post.Can I call the doPost() method from a hyperlink? A: Following a hyperlink in a Web document normally creates an HTTP GET request to the given URL.BLOGSPOT. click to get full answers . it will not affect the lifecycle status of the servlet from the container's point of view. 35. click to get full answers Premium members click below for full answer Can I catch an exception and give my own error message? 36. In principle it can be safe to call the destroy() method from your servlet application. use javax.

which is either an HTML document or an image or some other content item.getProperty("os.Should I use a static variable or Hashtable to store a list of strings? A: The difficulty you are facing is that Web browsers see your servlet output as a single HTTP response stream.version"). Depending on the nature of the application. To link the separate CAPTCHA form. the HTML img element requires a reference to an image at a separate URL source.How can I feed a CAPTCHA image into the servlet page output? A: The static modifier for a variable is different from the object type of the").getProperty("os. 40. If you want all servlet instances to be able to read and write data to a field. But the servlet that checks the CAPTCHA must know the decoded contents and the human input.BLOGSPOT.version"). String osVersion = System.How can I display system properties in a servlet? A: You can obtain the operating system. String javaVersion = System. . operating system version and Java version for a servlet container through standard Java system properties. It is not possible to encode the CAPTCHA image content inline into the HTML markup. The typical request sequence for a CAPTCHA form page would be: Request CAPTCHA form page (servlet) Download CAPTCHA form page HTML with image reference Request CAPTCHA image (servlet) Download CAPTCHA image as part of the main page load Submit CAPTCHA form with image reference and human input (servlet) Servlet checks CAPTCHA image content with human input and sends response Download HTML success or error page output accordingly It is critical the HTML page. When the CAPTCHA image servlet generates the “encoded” text it should store the decoded value in the session variable so the CAPTCHA check servlet can read the session and know what the value should be. it should be static. There is a wide range of standard properties that can be obtained from the static System class method getProperty(String).COM Premium members click below for full answer Can I call the doPost() method from a hyperlink? 38. form and image reference must not indicate the “decoded” contents of the CAPTCHA image. add a server-side session variable to carry the decoded value. it may also be necessary to synchronize access to the variable. image and form submission requests.getProperty("java. using the following keys: String osName = System.MYJAVAHUB. These system properties are common to all Java runtime systems including servlets. 39.

and a write(File) method to store the contents via a standard Java File object. so you must be very careful to ensure that you restrict who has access. which may physically store the uploaded content as a temporary file on the server. 42.MYJAVAHUB. Using request information 41. factory. A Vector is a List type and its implementation is synchronized. and that the public do not have arbitrary access to the file via the Internet. As you can imagine.COM If you want to store a simple list of strings.How can I enable users to upload a file? A: A file upload servlet should control what type of files are permitted.How do I get the uploaded file name? A: As with many things to do with Java I/O. // Set factory constraints factory. to process the byte stream and decide where the content is stored.BLOGSPOT.setSizeThreshold(yourMaxMemorySize). // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory).setRepository(yourTempDirectory). you can request a DiskFileItem subclass. private static final List stringList = new Vector().setSizeMax(yourMaxRequestSize). what they upload. // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(). The Apache commons file upload package would be a good place to start. a java. the commons file upload library treats HTTP file upload as a byte stream. allowing anybody to upload any file to your Web server is a significant security hazard. but this is not related to a standard Java File object. not necessarily as a file. However.List type variable would be most appropriate. Each FileItem has a getName() method that returns the original file name on the user's file system.util. The file upload API represents each uploaded file as a FileItem object. 43. .How do I limit the file upload size? A: This example code is for the Apache commons file upload package. // Set overall request size constraint upload.

or iterate through all parameters.Can I get the client IP and MAC address? A: The ServletRequest type has a getRemoteAddr() method that returns the Internet Protocol (IP) address of the client that made the request. so must be parsed further if you want to extract numeric references from it.How can I check what parameters are available in the request? A: There are two main approaches to checking request parameters: either look up named parameters you expect to be present. click to get full answers Premium members click below for full answer Can I get the client IP and MAC address? 46.COM Various factory configuration options let you set the maximum file size for the upload. The Java Mail API enables you to develop sophisticated email enabled applications. as in the profile avatar upload example below.How do I get the server port number for redirected requests? A: If your servlet container is listening on port 8080 then the HttpServletRequest getServerPort() method will return the int 8080. 45. click to get full answers Premium members click below for full answer How can I check what parameters are available in the request? . In JSP you can access this method it directly through the request variable. but it operates as a client or intermediary to existing system email services.BLOGSPOT. POP3 and other email services and is included with the Apache Tomcat servlet container and others.MYJAVAHUB. so look up values using the getParameterValues(String) method. which takes the name of the parameter as an argument and returns a string array. as below. this example takes the first value in the array. the temporary file directory and other settings. click to get full answers Premium members click below for full answer How do I get the uploaded file name? 44. You need to decide what should happen if there is more than one value. not as an email server in its own right. Process parameters 47. It is always possible there is more than one value for each named parameter. … full answer hidden.How do I upload and process a file then email it? A: The Java Mail API provides an interface with the Simple Mail Transport Protocol (SMTP). The address is returned as a String. … full answer hidden. … full answer hidden.

the example below shows how to markup your submit buttons to distinguish which was activated. … full answer hidden. ampersand is ASCII character number 38. This is known as URL-encoding and is normally done automatically by Web browsers when you submit a form. For instance.How can I tell which submit button was activated? A: In design terms. it is not a good idea for your application to have different outcomes from equivalent actions unless the consequences are quite clear to the person using the form. click to get full answers Premium members click below for full answer The & in the parameter value truncates the string! 50. HttpServletResponse) method.BLOGSPOT. click to get full answers Premium members click below for full answer How do I get parameter values from a form submission? 49. Nontheless. This is especially important for people with impaired vision.The & in the parameter value truncates the string! A: To pass non-ASCII characters in servlet parameters without them being interpreted as part of the URL structure. or those using screen readers. … full answer hidden. which is %26 expressed as a hexadecimal.How do I get parameter values from a form submission? A: The simple form below invites people to input their name. as"> <input type="text" name="name" /> <input type="submit" /> </form> To handle this submission. you must encode the characters as hexadecimal (base 16) values prefixed by the percent symbol.COM 48.MYJAVAHUB. click to get full answers Premium members click below for full answer How can I tell which submit button was activated? . … full answer hidden. See the table below for other conversion values. <form action="http://www. %.codestyle. extend HttpServlet and provide a doPost(HttpServletRequest.

BLOGSPOT. click to get full answers Premium members click below for full answer Which link was followed to request my servlet? Integration methods 52.How can I show my HTML markup as plain text? A: To display HTML output in plain text format.MYJAVAHUB. If you want to reproduce this format in detail and with precision you should read OpenOffice. … full answer hidden. … full answer hidden. your Javascript will not parse correctly. If you miss or fail to correctly escape a literal quote. click to get full answers Premium members click below for full answer How can I fix the Javascript in my servlet? 55. For simplicity.How can I make the servlet output open in Microsoft Excel? A: The binary file format of Microsoft Excel documents is extremely complex.COM 51. click to get full answers Premium members click below for full answer How can I show my HTML markup as plain text? 54. … full answer hidden. it would be preferable to use an external Javascript file. click to get full answers Premium members click below for full answer How can I make the servlet output open in Microsoft Excel? 53.How can I fix the Javascript in my servlet? A: It can be very tricky inserting inline Javascript in servlet output because of the level of quoted output escaping that can be necessary.How do I include CSS in my servlet? .Which link was followed to request my servlet? A: You should not rely upon the HTTP referer (sic) header to be sent to your servlet because some Web browsers (and other client types) do not send them for privacy reasons. you must set the HTTP Content-Type header to text/plain. as below: … full answer's Documentation of the Microsoft Excel File Format.

The GenericServlet class has general purpose implementations of servlet methods that are common to all. click to get full answers Premium members click below for full answer How do I include CSS in my servlet? 56.COM A: It is best to use an external style sheet reference. click here for all answers Premium members click below for full answer What types of Servlet are there? 59. so that you can edit your servlet and CSS rules independently. a service method and various supporting methods for getting servlet configuration parameters and for logging.BLOGSPOT.. … full answer hidden. … full answer hidden. … full answer hidden. click to get full answers Premium members click below for full answer How can I pass user input through my spelling checker? 57.How do I send data from an applet to a servlet? A: The applet sandbox security environment only permits connections with the host from which the applet was loaded.How can I pass user input through my spelling checker? A: create an instance of your SpellChecker class in the doGet() or doPost() method of your servlet and pass the relevant parameter to it as a string. however they must fulfil the Servlet and GenericServlet interface. ServletResponse) abstract for sub-class implementation. .What types of Servlet are there? A: In the Java servlet API there are several sub-interfaces and implementations of the Servlet interface.MYJAVAHUB. which has no host. full answer hidden. click to get full answers 58.What is the class structure of servlets? A: The class structure of servlets is fundamentally the same as any other Java class. This can also cause problems when you are testing an applet loaded from the local file system. init(ServletConfig) and log(String). If you attempt a connection with a different host. the applet will throw a SecurityException and fail. These interfaces define a set of socalled lifecycle methods.. as in the code sample below . GenericServlet is abstract and leaves the key method service(ServletRequest. including getInitParameter(String).

Why is HttpServlet declared abstract? A: The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. 63. such as an FtpServlet for example. 62. The basic service(ServletRequest. but it would be pointless because the default implementations of the service methods doGet().Who creates the servlet request object? A: The servlet container creates an instance of the interface type HttpServletRequest to represent the details of a single HTTP request.What's the difference between GenericServlet and HttpServlet? A: The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP protocol-specific methods.What's the problem if HttpServlet was concrete? A: HttpServlet would be viable as a concrete class because it has no abstract methods. there is no need to write a doPost() method too. ServletResponse) method is called whenever a servlet request is received by the servlet container. doPost() etc.MYJAVAHUB. sessions and setting response headers. If your servlet is required to handle doGet() requests for example. In this case the abstract modifier is a design compromise that provides the default implementation of un-supported methods with a minimal safeguard to suggest these methods should be overridden. which means that developers do not need to implement all service methods. Java application developers normally extend the HttpServlet because it implements all the HTTP features necessary to create a Web application. cookies. In principle.BLOGSPOT. The HttpServlet class is part of a public Application Programming Interface (API). click here for all answers Premium members click below for full answer What is the class structure of servlets? 60. so the abstract modifier is a useful signal to programmers that the class has no practical use in itself and is intended to be extended to create HTTP servlets.COM The lifecycle methods init(ServletConfig) and destroy() are called when the servlet container first puts the servlet into service and ultimately removes it. This is a convenience implementation of the Servlet interface. which is passed to a servlet's service method . The HttpServlet subclass passes generic service method requests to the relevant doGet() or doPost method. the GenericServlet could be extended to implement other protocols. The GenericServlet does not include protocol-specific methods for handling request parameters. simply report that the relevant HTTP request methods are not supported. … full answer hidden. 61.

BLOGSPOT. The implementation classes for the HttpServletRequest and HttpServletResponse objects are provided by the servlet container and may include proprietary code to support the vendor's overall container implementation. The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behaviour is to pass all method calls directly to the underlying objects. The HTTP protocol is stateless. largely managed by the servlet container. only those provided by the servlet API.MYJAVAHUB. it is essentially a request-response scheme. click here for all answers Premium members click below for full answer What's the use of the servlet wrapper classes? 67.What's the difference between getAttribute() and getParameter()? .What's the use of the servlet wrapper classes? A: The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it easy for developers to create custom implementations of the servlet request and response types. passed to a servlet's init(ServletConfig) method.What's the difference between a servlet session and a servlet context? A: A servlet session is a very different thing from a servlet context. so servlet sessions are maintained by passing a unique HTTP cookie value for each request. Servlet containers must provide their own implementations of these types. 66. or from the servlet getServletConfig() method. An HttpSession is a mechanism used to simulate and maintain a continuous user session between a Web browser and Web application. 64. From a programmer's point of view you should not need to concern yourself with the vendor-specific features of these objects. or by dynamically including an identifier in servlet URLs. forward requests and load resources.Why are there separate ServletRequest and HttpServletRequest types? A: ServletRequest and HttpServletRequest are interfaces. which are passed to servlets' doGet and doPost methods. click here for all answers Premium members click below for full answer Why are there separate ServletRequest and HttpServletRequest types? 65. The servlet context is usually obtained indirectly through the ServletConfig object. A ServletContext object represents the overall configuration of the servlet container and has several methods to get configuration parameters. … full answer hidden. not a classes.COM (with an instance of HttpServletResponse). exchange data amongst servlets. known as URL-rewriting. … full answer hidden.

Developers can add Java objects to a request with the request. doPost() or doGet()? A: Neither doPost() or doGet() methods are intrinsically faster than each other. 70. how do I get an instance? A: The HttpServletRequest interface is implemented by the servlet container.setAttribute(String.MYJAVAHUB. but in this case they are not displayed as part of the URL on the form action handler.Which is faster. The most visible example of HTTP request parameters are those you see appended to a search engine URL after you submit a Attributes should be named like Java package names to ensure they don't clash. If any servlet request handler does a great deal of data retrieval. The speed with which a servlet container responds to such requests is partly a matter of how much data is submitted with the request and the statements your servlet methods contain. … full answer hidden. only the doGet or doPost methods. This example shows the results of an HTTP GET request passed by an HTML form. click here for all answers Premium members click below for full answer What's the difference between getAttribute() and getParameter()? 68. e. The container instantiates and passes servlet request and response objects to the servlet's service method. as below.COM A: The servlet request getParameter(String) method gets the value of the named request parameter and returns it as a String. but this is not necessarily the case. The servlet request getAttribute(String) method is used to retrieve Java Object properties that may be added to the servlet request by the servlet container or Web application developer.I have overridden the service In this case a call to request. what next? A: For most common servlet implementations you should not override the service method. HTTP post forms are often designed to submit longer free-form text content. .HttpServletRequest is an interface. which calls doGet or doPost in turn.getParameter("q") would return the String getParameter(). The servlet container provides its own abstract implementation of the HttpServlet class and its service method forwards requests to the doGet or doPost methods as appropriate. the parameter name q is the name of the text input field.BLOGSPOT. http://www.g. Servlet request attributes are most often used with RequestDispatcher methods to pass object references through the forward() and include() methods. 69. Request parameters may also be included in an HTTP POST submission too. Object) method.

MYJAVAHUB. JSP pages are compiled into servlets and processed automatically by the servlet container.What's the difference between doGet() and doPost()? A: The doGet() and doPost() methods are designed to handle HTTP GET and POST type requests respectively. it will not include a query string. click here for all answers Premium members click below for full answer Does the servlet request contain the source of the Web page? 74.Why are there two different getRequestDispatcher() methods? A: There is very little difference between the ServletContext and ServletRequest versions of this method. so there is no need to write any additional processor code yourself. If both methods called each other you would create an endless loop that would quickly throw an exception. bear in mind several properties of the servlet request object will be different for POST requests. the RequestDispatcher you get operates in exactly the same way. However. you can use the getResourceAsStream(String path) method of the ServletContext object to get an InputStream of the file. However. regardless of the submission method. When a GET request is submitted to a servlet container. you should use JSP script elements or JSP tags in the body of the document and let the servlet container handle the processing. Normally.COM network communication and processing it will take longer to execute.Does the servlet request contain the source of the Web page? A: The HttpServletRequest object contains all the key information for the HTTP request. the ServletRequest method also allows you to use a path argument that is relative to the . The doGet() and doPost() methods both take the same arguments and will handle the servlet response in an equivalent manner. 72.Must doPost() call doGet()? A: There is no requirement for doGet() to call doPost() or vice versa. … full answer hidden.BLOGSPOT. 71. not the source of the requested Web resource. If you really want to process the source of a static HTML document or suchlike. and its getMethod() method will return "post". If you need to dynamically configure the servlet response. it calls the doGet method of the servlet that handles the request via the service method. 73. As a convenience some servlets are set up so their doPost() method calls doGet() because they are intended to handle GET and POST requests identically. so for convenience a doPost() request can be passed to a doGet() method and vice-versa.

The RequestDispatcher forward() method is used to show a different resource in place of the servlet that was originally called.BLOGSPOT. JSP or static HTML document. 75. as if it were part of the calling servlet.jsp".jsp".What is the use of sessions in servlets? A: The servlet HttpSession interface is used to simulate the concept that a person's visit to a Web site is one continuous series of interactions.COM "current" resource. The forward() method is often used where a servlet is taking a controller role. … full answer hidden.Why do I get a compilation error with getRequestDispatcher(String)? A: This error means the compiler does not recognise this method signature in the context that you are calling it. The ServletContext getRequestDispatcher method should only be used for paths relative to the application root. you could use. any such request will be ignored. HttpServletRequest or ServletContext object. 77. the included resource must not attempt to change the response status code or HTTP headers. processing some input and deciding the outcome by returning a particular response page.. The forwarded resource may be another servlet. The include() method is often used to include common "boilerplate" text or template markup that may be included by many servlets. starting with ".MYJAVAHUB. click to get full answers Premium members click below for full answer What is the use of sessions in servlets? . it can only be called on a ServletRequest. This is often the case.. In other words. it is not the same as a redirection. starting with "/Example. It generally avoids ambiguity and possible confusion to use a path relative to the application root. … full answer hidden./Example.jsp" or ". click here for all answers Premium members click below for full answer Why do I get a compilation error with getRequestDispatcher(String)? 76. The getRequestDispatcher method is not an HttpServlet method.What's the difference between the include() and forward() methods? A: The RequestDispatcher include() method inserts the contents of the specified resource directly in the flow of the servlet response.. but the HTTP protocol is basically a request-response mechanism with no necessary connection between one request and the next. For instance. but the response is issued under the same URL that was originally requested. If you include a servlet or JSP document./Example.

How can I assemble data from multiple input forms? A: First. which has two key features necessary for a servlet container to simulate continuous user sessions: cookies and URL-based navigation. it is best to use a single servlet to handle each form submission.How can I recover an expired session? .servlet. but only as a token reference. 80. Servlet-based sessions are designed only for interactions using the HTTP protocol. click to get full answers Premium members click below for full answer How do I clean up object references when a session ends? 82. … full answer hidden. Web clients must pass back a valid session identifier as a cookie header value or dynamically generated URL parameter. Give each servlet responsibility to validate a single form input. The servlet container keeps track of all the sessions it manages and fulfills servlet API requests to get HttpSessions. A single servlet for all input would be too complicated. the session ID reference is invalidated so any further requests for the session will return null. and session references are only available through classes in this package. or the application calls the session's invalidate() method in response to a "log out" type request.Are sessions created on the server side? A: A servlet session is created and stored on the server side.http package. general purpose Servlet interface.Can I create a session with GenericServlet? A: There are no protocol-specific features in GenericServlet.How do I clean up object references when a session ends? A: In normal service conditions a servlet session may expire when the application user exceeds the maximum inactive time interval for the session.BLOGSPOT.COM 78. the session is also stored by the client. In both cases. The servlet API therefore places the HttpSession interface in the javax. To the maintain the session. 79.MYJAVAHUB. which is an implementation of the basic. and pass the error cases on to JSP documents that explain the problem and allow users to amend the input. click to get full answers Premium members click below for full answer How can I assemble data from multiple input forms? 81. … full answer hidden. manipulate object data stored with them and trigger event callbacks. In this sense. then all the object references associated with the session are unbound and made available for garbage collection (if no other references remain). which supports URL-rewriting.

Many servlet containers also support persistent sessions. To delete an existing cookie. there is no way to re-construct it. which are stored between separate invocations of the container. Servlet containers usually discard sessions after a standard time-out period. There is no obligation for a Web browser to accept the cookie or maintain the information it is sent. so they do not have to maintain sessions indefinitely. The session ID value should be managed by the servlet container. 84. … full answer hidden. A negative value means the cookie should not be stored and will expire when the browser is shut down. call setMaxAge(0) before issuing the servlet response. Generally. click to get full answers Premium members click below for full answer How do I disable a cookie? 86. A positive value means the cookie should be stored for the given number of milliseconds from the present time. such as a cookie entry. for example: … full answer hidden.How can I pass values between JSPs without using sessions? .MYJAVAHUB. If the session has expired on the server side.How do I disable a cookie? A: The storage of cookies is controlled by their maximum age property. 83. for which the servlet container has no record. you should not attempt to change users' session ID values because it is very likely to result in the loss of the session or with people acquiring other users' data. Use the code below to delete all cookies for the current site. it is not bound to a particular page. but configuration details vary. Some people disable cookies in their browser settings and you should design your application with this possibility in mind. it means a browser has made a new request that carries a session identifier. It is possible to request sessions live longer using the HttpSession setMaxInactiveInterval(int) method.What are persistent cookies and pre-session cookies? A: Cookies are relatively simple information stores that may be maintained by a Web browser using data sent in the response header from a Web server.How can I change the session ID of the page? A: The servlet session represents a relationship between the servlet container and the end user's browser over a number of request-response cycles. click to get full answers Premium members click below for full answer What are persistent cookies and pre-session cookies? 85.BLOGSPOT.COM A: If a session has expired. because no reference remains.

Where you have the if / else conditions the servlet should execute the contents of the relevant statement block. What happens when you force the error. to replace the previous one? Check the webapps directory for the deployed web.BLOGSPOT. Apache Ant is a Java build and deployment application that works with JUnit to test your application code.COM A: There are four main alternatives to full session-based transfer of data values.I get a servlet 404 error at /examples/WEB-INF/classes/HelloWorld! A: It appears you have deployed your servlet to the correct location. two of them use features of the session tracking API: cookies and URL-rewriting. click to get full answers 87.xml entries like those below. … full answer hidden.xml file for your application and you are requesting the wrong URL for the servlet. … full answer hidden. but you have probably not configured the servlet in the web. between the curly braces. When you are working with servlets it helps to have a standard deployment process that ensures that the latest version of your code is successfully compiled and deployed before you test. which error page is issued? What does the error log tell you? Is the new configuration being deployed properly. It seems most likely that this working version of the controller servlet has not successfully been deployed to the servlet container and you are actually testing an earlier version of the servlet.MYJAVAHUB. Does it include your custom error configuration? Check the work directories under the Tomcat installation to see the which compiled JSP servlets are present. detailed below. and not the other. Perhaps there is a compilation error with your custom error page? 88.My custom error page doesn't show! A: There are many things that could be wrong with your configuration. restart and request the URL http://localhost:8080/examples/HelloWorld.xml file. click for full answers Premium members click below for full answer I get a servlet 404 error at /examples/WEB-INF/classes/HelloWorld! 89.My servlet's if and else code is executed! A: The code sample you have given is correct. Ideally you should write unit tests to check the logic of your application too. You should add web. .

For example. not getWrite().I get "cannot override doGet()" throwing an Exception! A: This compiler error means that your method throws an exception that is not declared by the superclass method it is intended to override. fall back to a simpler output or fixed error response. you may choose to send an HTTP 400. so the first servlet request. Your servlet must trigger the process by which the browser prompts for the login.The getRemoteUser method returns null after basic authentication! A: Basic authentication details are carried in the HTTP headers that a browser passes to the servlet container when it makes a request. Since Exception is a superclass of the declared exceptions. When the browser makes an initial request. bad request. The browser will then issue a second HTTP request with an Authorization header that carries the login details. error response. The method may also throw the runtime exception UnsupportedEncodingException if the character set specified by the setContentType() method is not supported.getRemoteUser() method returns null. an IOException or any subclass of those types. click for full answers Premium members click below for full answer My servlet cannot locate my XSLT file! 91. … full answer hidden.MYJAVAHUB. … full answer hidden.Could compiling a package cause an internal server error? . 94. you may report the problem in the servlet output. it is not permitted.BLOGSPOT. If the exception originates from invalid servlet input. click for full answers Premium members click below for full answer The getRemoteUser method returns null after basic authentication! 92.COM 90. and IllegalStateException if the getOutputStream() method has already been called. If your doGet() method includes calls that may throw undeclared exceptions you should catch those exceptions and handle them. or throw a new ServletException with the details of the primary exception. including the drive letter and the path separator backslashes escaped. and may throw an IOException. it does not include an Authorization header.My servlet cannot locate my XSLT file! A: On Windows systems. The servlet doGet() method may throw a ServletException. 93.I get "cannot find symbol" with getWrite()! A: The HttpServletResponse class method for getting a PrintWriter is called getWriter(). the path to files referenced in servlet classes should be given in full.

I get "Error allocating a servlet instance"! A: It is difficult to solve Java servlet errors without more detailed diagnostic information but the most likely reason for this error is a class definition not found. as below.I get "HTTP GET method is not in use"! A: The servlet you are referring to has not implemented the doGet(HttpServletRequest. but compiling a package wouldn't normally cause a 500 error directly. If you attempted to compile a servlet or a utility class on the host machine and the classpath environment setting was not configured properly. Check your servlet container documentation and adjust the configuration as necessary. ? A: The answer to the question is in the first line of the stack trace. The interpreter attempted to get the array list item at index 4. HttpServletResponse) method. It is possible the servlet has been designed to handle HTTPpost requests from HTML form submissions only. 98. … full answer hidden. In other words.. click for full answers Premium members click below for full answer Could compiling a package cause an internal server error? 95.COM A: Possibly. which is required to handle the type of requests made by typing the address into a Web browser. Otherwise. there may be a security policy for your servlet container that restricts the rights your applications have to access the file system. The container may be configured with strict security policy by default. This may be a symptom of concurrent modification of the array list by a separate thread. … full answer hidden. your servlet class or one of the classes required by your servlet was not found by the servlet container when it tried to bring the servlet into service. The user profile that the servlet container is using does not have permission to access this file.BLOGSPOT. you should add a check for the size of the array before you reference an item at a specific index. To guard against this case. click for full answers Premium members click below for full answer I get "HTTP GET method is not in use"! 96. Modify the permissions on the file to allow read access by the servlet container user if one exists.. Whatever code was supposed to fill the list has not done so. but the size of the array list was zero.My file throws an AccessControlException! A: The AccessControlException explains the problem without having to look any code extracts. .What does this servlet stack trace mean: IndexOutOfBoundsException. In this case. you would have to create a form whose action attribute is the servlet URL with the method attribute post. 97.MYJAVAHUB. the classes would just fail to compile.

This is a problem because it may obscure any genuinely helpful error messages you try to present to the user. Use the servlet method log(String) or log(String. click for full answers Premium members click below for full answer Internet Explorer does not show my custom 500 error page! 101. to be sure only one response is attempted. 102. Internet Explorer does not show my custom 500 error page! A: The problem is with your browser. but if those statements attempt to make further calls on the servlet response it will throw an IllegalStateException. 99.MYJAVAHUB. This can be useful if you want to log status or store data after the response has been handled for example. you must call super.COM The most likely solution is to re-compile your servlet and associated classes and re-deploy them to your servlet container. For this reason it is best to handle forwarding logic with exclusive if / else blocks.I get an IllegalStateException with my forward() call! A: The RequestDispatcher forward() method call will effectively end the servlet response because the response stream will be committed in the process. make sure they are deployed to the appropriate Web application directory or common container library directory. Throwable). You should put debugging log output in your servlet to find the point at which the exception is thrown. This government Web site throws a servlet error. so we cannot tell whether it is a runtime exception or checked exception thrown by your application. A build tool like Apache Ant can help ensure that you do not miss vital steps in the compilation and deployment of your Web application.Exception! A: It is very difficult to tell from this information alone what the problem is. not your servlet container.init(config) in the first line of the method to enable these log methods. If you use third party libraries with your servlet.Exception class is the superclass of all exceptions. etc. The java. Internet Explorer shows what it regards as "friendly" error messages when it receives HTTP error codes such as 500. My 500 error is java. 404.BLOGSPOT. 100. what can I do? A: Web server errors caused by Java servlets are the responsibility of the Web site owner and you should alert them to the problem. Server errors can be caused by temporary . You may need to stop and re-start your servlet container. If you have overridden the init(ServletConfig config) method.lang. but the controller servlet will continue to execute any remaining statements in its doGet() or doPost() method.lang. … full answer hidden.

What does HTTP status 405. "Method not supported". another possibility is that it throws a ServletException in the init(ServletConfig) method. Are servlets multi-threaded? A: Yes. What is a service thread and how do I create one? A: The most common use of service threads are those used by a servlet container to handle the HTTP request-response process with a Java servlet. Servlet containers use an . One common technique to easily enable a servlet to support POST requests is for the doPost() method to call the doGet() method. a servlet may only have a doGet() method. Check your log files for any details. 106. If your servlet compiles successfully. One possibility is that your Web browser has an exceptionally long "user agent". 104.COM problems with a Web server or there may be fundamental programming errors that are only seen in certain circumstances. Try the problem page with a different Web browser to see if you can isolate the problem. but you can use static variables to store and present information that is common to all threads. though some the HttpServletRequest object properties will vary from a normal GET request. and therefore be unable to issue an HTML document for the response body. Why does my servlet give a 404 error? A: There are many reasons why a servlet container may issue an HTTP 404 error for a servlet. Use the Code Style EchoRequest servlet to see the user-agent for yourself. servlets are normally multi-threaded. not doPost(). which may be more than the servlet expects. The servlet container allocates a thread for each new request for a single servlet without any special programming. Each request thread for your servlet runs as if a single user were accessing it alone.MYJAVAHUB. If so. like a hit counter for instance. the response means you can't make that kind of request for this servlet. For example. You should check you have added a servlet configuration and mapping to your web. means that the submitted request method is not implemented by the servlet that handled the response. method not supported mean? A: The HTTP 405 status. In other words. It is possible that those problem circumstances include unexpected differences in the way your Web browser works or your computer is set up. Most Web site managers would welcome the opportunity to make a correction if you can provide information about the browser you use and what happened immediately before the error.xml file and make sure you are requesting the URL path specified in the mapping. the servlet container will log the exception and take the servlet out of service. a software code name that is a hidden part of your browser's Web page requests. 105. Your browser's code name is 2063 characters long. 103.BLOGSPOT.

so they are named service threads. This is why it is important to design for concurrency when you write a servlet. the sequence in which the thread is executed depends on the thread scheduling system of the Java Runtime Environment (JRE). 110. but the actual execution sequence also depends on the thread scheduling scheme in the Java virtual machine. so they do not need to be created explicitly in your servlet code. start sequences in contention with other service threads. they may use servlet pooling. What is the single threaded model? .BLOGSPOT. The natural principle is that it should be first come first served. New threads are not necessarily created for every servlet request but may be recycled through a worker thread pool for efficiency. Threads can enter complex stop.MYJAVAHUB. In other words. which is why your servlet code needs to be thread safe. they may use a single servlet. because multiple requests may be handled by the same servlet instance. Are servlet requests handled first come. 109. run anywhere. Once a service thread is assigned to a request. How does the container handle concurrent requests? A: Servlet containers usually manage concurrent requests by creating a new Java thread for each request. The point is that you should write your servlet code to take account of a multi-threaded context regardless of the container implementation you happen to be using. For each HTTP request the servlet container assigns a worker thread in which to execute the servlet code and a reference to the relevant servlet instance to call its service methods. 108. The priority order by which the service threads are acquired and process the request depends on the detailed implementation of the servlet container. but other Java applications may use a similar service scheme. Servlet containers automatically create or obtain service threads from a thread pool when a new HTTP request is received. which issues the response through the same thread. Servlet requests are handled through the service() method. you should adhere to the principle of write once. The new thread is given an object reference to the requested servlet. 107. Servlet containers normally limit the number of service threads that can be run concurrently. Are you saying there is only one servlet instance for all requests? A: The way that servlet containers handle servlet requests is not prescribed to this extent. it depends on the vendor's system architecture. so pending requests are typically added to a queue. first served? A: The use of a single servlet to handle multiple requests is usually done with Java threads.COM independent thread of execution so they can process many concurrent requests to many servlets and manage the overall performance of the server.

there are no extra methods to fulfil. it gets a guarantee from the servlet container that any single instance of the servlet will only be accessed by one thread at a time. How do I implement the single threaded model? A: To create a servlet that a container will manage on a single threaded basis it must declare that it implements the javax. The container either synchronizes access to the servlet's service() method. The SingleThreadedModel interface has been deprecated. it is best to ensure synchronized access to servlet resources in your application code. but this is sufficient for the container to identify the type and manage it accordingly. which means that it should not be used and may be removed in a later release of the Java servlet specification and Application Programming Interface (API).SingleThreadModel interface. The single threaded model adds a performance overhead to locking or managing servlet instances. Generally. servlets should be written to run safely in a multi-threaded environment. and modification of shared resources must be considered carefully. A number of virtually simultaneous requests for a single servlet could be handled by different threads using the same servlet instance. If your servlet implements the SingleThreadModel interface. Why use SingleThreadedModel if servlets are multi-threaded? A: The SingleThreadedModel interface is used to ensure the safety of servlets that are vulnerable to thread safety issues.COM A: Standard servlets are normally handled in a multi-threaded context in the servlet container.BLOGSPOT.servlet. 113. This is a marker interface. Any number of threads could access or modify the static and instance fields of a single servlet instance in an unpredictable sequence. Public class SingleThreadServlet extends HttpServlet implements SingleThreadModel { // Standard HTTP servlet methods } The servlet container will typically synchronize access to a single instance of the servlet. Should I use the SingleThreadedModel? A: Not unless you have very good reason. This makes the instance fields of servlets as vulnerable to threading issues as static fields. so should not be used lightly. It has never . and are executed in this context.MYJAVAHUB. 112. 111. The SingleThreadedModel is a way to override the normal multi-threaded execution context of the servlet container. Normally. or create a pool of servlet instances and allocate one request per instance. or uses a single instance of the servlet drawn from a pool.

<Connector className="org. 114. The minProcessors attribute sets the number of request processors that are created when the servlet container starts up.HttpConnector" minProcessors="3" maxProcessors="20" acceptCount="10"/> The acceptCount attribute sets the number of requests that can be queued waiting to be handled.apache. By doing away with the single threaded model. you should always aim to address thread safety issues in servlets using standard Java programming techniques.BLOGSPOT.MYJAVAHUB. Apache Tomcat uses the synchronized approach. you might create a synchronized block around the statements that are vulnerable to threading issues. 115. If you are concerned about the performance impact of synchronized access to the servlet instance.COM really been advisable to implement the SingleThreadedModel. as below.connector.catalina. so that only one request is processed at a time. A single threaded model implementation may also synchronize access to a single servlet instance to achieve the same outcome. You should configure the number of concurrent requests to accept in your servlet container configuration.xml file's Connector element. The maxProcessors attribute sets the total number of request processors or that can be used to handle requests. How can I invoke servlet pooling with SingleThreadedModel? A: The SingleThreadedModel servlet specification does not require the creation of a pool of servlets. it would be preferable to re-design your servlet so that it does not depend on this mechanism at all. . other servlet containers may use the pooled approach.http. For example. Can my servlet control the number of threads it accepts? A: Your servlet should be designed to be thread safe and not to anticipate any limit to the number of concurrent requests it will receive. In Apache Tomcat this property is set in the server. you will minimise the performance impact of thread control.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.