The following are some questions you might encounter with respect to the J2EE Technology in any Interview for a Java J2EE Developer. The questions below are pretty exhaustive and practically speaking, you might not be asked most of the questions because - interviewers might prefer to test out your knowledge of core J2EE technologies like Servlets, JSPs, Struts, Hibernate etc. Nonetheless, there is nothing wrong in being prepared and the questions below would help you prepare for your J2EE Interview.
Questions:
1. What is J2EE?
J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitier, web-based applications.
2. What is the J2EE module?
A J2EE module consists of one or more J2EE components for the same container type and one component deployment descriptor of that type.
3. What are the components of J2EE application?
A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:
* Application clients and applets are client components.
* Java Servlet and JavaServer Pages (JSP) technology components are web components.
* Enterprise JavaBeans (EJB) components are business components.
* Resource adapter components provided by EIS and tool vendors.
4. What does application client module contain?
The application client module contains:
*class files
*an application client deployment descriptor.
Application client modules are packaged as JAR files with a .jar extension.
5. What does web module contain?
The web module contains:
*JSP files,
*class files for servlets,
*GIF and HTML files, and
*a Web deployment descriptor.
Web modules are packaged as JAR files with a .war (Web ARchive) extension.
6. What are the differences between Ear, Jar and War files? Under what circumstances should we use each one?
There are no structural differences between the files; they are all archived using zip-jar compression. However, they are intended for different purposes.
*Jar files are intended to hold generic libraries of Java classes, resources, auxiliary files, etc.
*War files are intended to contain complete Web applications.
*Ear files are intended to contain complete enterprise applications.
Each type of file (.jar, .war, .ear) is processed uniquely by application servers, servlet containers, EJB containers, etc.
7. What is an applet?
A J2EE component that typically executes in a Web browser but can execute in a variety of other applications or devices that support the applet programming model.
8. What is applet container?
A container that includes support for the applet programming model.
9. What is application assembler?
A person who combines J2EE components and modules into deployable application units
10. What is application client?
A first-tier J2EE client component that executes in its own Java virtual machine. Application clients have access to some J2EE platform APIs.
11. What is application client container?
A container that supports application client components.
12. What is application client module?
A software unit that consists of one or more classes and an application client deployment descriptor.
13. What is application component provider?
A vendor that provides the Java classes that implement components' methods, JSP page definitions, and any required deployment descriptors.
14. What is application configuration resource file?
An XML file used to configure resources for a Java Server Faces application, to define navigation rules for the application, and to register converters, Validator, listeners, renders, and components with the application.
15. What is build file?
The XML file that contains one or more ant targets. A target is a set of tasks you want to be executed. When starting asant, you can select which targets you want to have executed. When no target is given, the project's default target is executed.
ant - is a tool that is used to build web applications
16. What is deployment?
The process whereby software is installed into an operational environment. For ex: deploying an EAR file into a Weblogic Server.
17. What is deployment descriptor?
An XML file provided with each module and J2EE application that describes how they should be deployed. The deployment descriptor directs a deployment tool to deploy a module or application with specific container options and describes specific configuration requirements that a deployer must resolve.
18. What is HTML?
Hypertext Markup Language. A markup language for hypertext documents on the Internet. HTML enables the embedding of images, sounds, video streams, form fields, references to other objects with URLs, and basic text formatting.
19. What is HTTP?
Hypertext Transfer Protocol. The Internet protocol used to retrieve hypertext objects from remote hosts. HTTP messages consist of requests from client to server and responses from server to client.
20. What is HTTPS?
HTTP layered over the SSL protocol. It is the secure version of the HTTP protocol
21. What is Java 2 Platform, Micro Edition (J2ME)?
A highly optimized Java runtime environment targeting a wide range of consumer products, including pagers, cellular phones, screen phones, digital set-top boxes, and car navigation systems.
22. What is JDBC?
An JDBC for database-independent connectivity between the J2EE platform and a wide range of data sources.
23. What is JNDI?
Abbreviate of Java Naming and Directory Interface. It is used as part of JDBC
24. What is query string?
A component of an HTTP request URL that contains a set of parameters and values that affect the handling of the request
25. What is resource adapter?
A system-level software driver that is used by an EJB container or an application client to connect to an enterprise information system. A resource adapter typically is specific to an enterprise information system. It is available as a library and is used within the address space of the server or client using it. A resource adapter plugs in to a container. The application components deployed on the container then use the client API (exposed by the adapter) or tool-generated high-level abstractions to access the underlying enterprise information system. The resource adapter and EJB container collaborate to provide the underlying mechanisms-transactions, security, and connection pooling-for connectivity to the enterprise information system.
26. What is Secure Socket Layer (SSL)?
A technology that allows Web browsers and Web servers to communicate over a secured connection.
27. What is URI?
Uniform resource identifier. A globally unique identifier for an abstract or physical resource. A URL is a kind of URI that specifies the retrieval protocol (http or https for Web applications) and physical location of a resource (host name and host-relative path). A URN is another type of URI.
28. What is URL?
Uniform resource locator. A standard for writing a textual reference to an arbitrary piece of data in the World Wide Web. A URL looks like this:
protocol://host/local info
where protocol specifies a protocol for fetching the object (such as http or ftp), host specifies the Internet name of the targeted host, and local info is a string (often a file name) passed to the protocol handler on the remote host.
29. What is URL path?
The part of a URL passed by an HTTP request to invoke a servlet. A URL path consists of the context path + servlet path + path info, where Context path is the path prefix associated with a servlet context of which the servlet is a part. If this context is the default context rooted at the base of the Web server's URL namespace, the path prefix will be an empty string. Otherwise, the path prefix starts with a / character but does not end with a / character. Servlet path is the path section that directly corresponds to the mapping that activated this request. This path starts with a / character. Path info is the part of the request path that is not part of the context path or the servlet path
30. What is URN?
Uniform resource name. A unique identifier that identifies an entity but doesn't tell where it is located. A system can use a URN to look up an entity locally before trying to find it on the Web. It also allows the Web location to change, while still allowing the entity to be found.
If you have any questions that you want answer for - please leave a comment on this page and I will answer them.
If you have any more questions on J2EE concepts that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.
More Java & J2EE Interview Questions with Answers - Click Here
Topics Covered in the Blog - Synopsis
Showing posts with label j2ee interview questions. Show all posts
Showing posts with label j2ee interview questions. Show all posts
Tuesday, April 19, 2011
Monday, April 18, 2011
Core Java Interview Questions - Exception Handling
The following are some questions you might encounter with respect to Java Exception Handling in any Interview. Exception Handling is an important part of any Java Application because, this determines how gracefully you capture and handle unexpected situations.
Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Exception Handling that you might find useful. You can use them to revise/review your understanding of Exception Handling.
They are:
Exception Handling
Common Exceptions & Errors
Questions:
1. How could Java classes direct messages to a file instead of the Console?
The System class has a variable "out" that represents the standard output, and the variable "err" that represents the standard error device. By default, they both point at the system console.
The standard output could be re-directed to a file as follows:
Stream st = new Stream(new FileOutputStream("output.txt"));
System.setErr(st);
System.setOut(st);
2. Does it matter in what order catch statements for FileNotFoundException and IOException are written?
Yes, it does. The child exceptions classes must always be caught first and the "Exception" class should be caught last.
3. What is user-defined exception in java ?
User-defined expections are the exceptions defined by the application developer which are errors related to specific application. Application Developer can define the user defined exception by inheriting the Exception class. Using this class we can create & throw new exceptions.
4. What is the difference between checked and Unchecked Exceptions in Java ?
Checked exceptions must be caught using try-catch() block or thrown using throws clause. If you dont, compilation of program will fail. whereas we need not catch or throw Unchecked exceptions.
5. What is the catch or declare rule for method declarations?
If a checked exception may be thrown within the body of a method, the method must either catch that exception or declare it in its throws clause. This is done to ensure that there are no orphan exceptions that are not handled by any method.
6. What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. It is usually used in places where we are connecting to a database so that, we can close the connection or perform any cleanup even if the query execution in the try block caused an exception.
7. What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.
8. Can an exception be rethrown?
Yes, an exception can be rethrown any number of times.
9. When is the finally clause of a try-catch-finally statement executed?
The finally clause of the try-catch-finally statement is always executed after the catch block is executed, unless the thread of execution terminates or an exception occurs within the execution of the finally clause.
10. What classes of exceptions may be thrown by a throw statement?
A throw statement may throw any expression that may be assigned to the Throwable type.
11. What happens if an exception is not caught?
An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.
12. What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?
The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.
13. Can try statements be nested?
Try statements can be tested. It is possible to nest them to any level, but it is preferable to keep the nesting to 2 or 3 levels at max.
14. How does a try statement determine which catch clause should be used to handle an exception?
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception that was thrown, is executed. The remaining catch clauses are ignored.
15. What is difference between error and exception
Error occurs at runtime and cannot be recovered, Outofmemory is one such example. Exceptions on the other hand are due conditions which the application encounters, that can be recovered such as FileNotFound exception or IO exceptions
16. What is the base class from which all exceptions are subclasses
All exceptions are subclasses of a class called java.lang.Throwable
17. How do you intercept and control exceptions
We can intercept and control exceptions by using try/catch/finally blocks.
You place the normal processing code in try block
You put the code to deal with exceptions that might arise in try block in catch block
Code that must be executed no matter what happens must be place in finally block
18. When do we say an exception is handled
When an exception is thrown in a try block and is caught by a matching catch block, the exception is considered to have been handled. Or when an exception thrown by a method is caught by the calling method and handled, an exception can be considered handled.
19. When do we say an exception is not handled
There is no catch block that names either the class of exception that has been thrown or a class of exception that is a parent class of the one that has been thrown, then the exception is considered to be unhandled, in such condition the execution leaves the method directly as if no try has been executed
20. In what sequence does the finally block gets executed
If you put finally after a try block without a matching catch block then it will be executed after the try block
If it is placed after the catch block and there is no exception then also it will be executed after the try block
If there is an exception and it is handled by the catch block then it will be executed after the catch block
21. What can prevent the execution of the code in finally block
Theoretically, the finally block will execute no matter what. But practically, the following scenarios can prevent the execution of the finally block.
* The death of thread
* Use of system.exit()
* Turning off the power to CPU
* An exception arising in the finally block itself
22. What are the rules for catching multiple exceptions?
A more specific catch block must precede a more general one in the source, else it gives compilation error about unreachable code blocks.
23. What does throws statement declaration in a method indicate?
This indicates that the method throws some exception and the caller method should take care of handling it. If a method invokes another method that throws some exception, the compiler will complain until the method itself throws it or surrounds the method invocation with a try-catch block.
24. What are checked exceptions?
Checked exceptions are exceptions that arise in a correct program, typically due to user mistakes like entering wrong data or I/O problems. Checked Exceptions can be caught and handled by the programmer to avoid random error messages on screen.
25. What are runtime exceptions
Runtime exceptions are due to programming bugs like out of bound arrays or null pointer exceptions.
26. What is difference between Exception and errors
Errors are situations that cannot be recovered and the system will just crash or end. Whereas, Exceptions are just unexpected situations that can be handled and the system can recover from it. We usually catch & handle exceptions while we dont handle Errors.
27. How will you handle the checked exceptions
You can provide a try/catch block to handle it or throw the exception from the method and have the calling method handle it.
28. When you extend a class and override a method, can this new method throw exceptions other than those that were declared by the original method?
No it cannot throw, except for the subclasses of the exceptions thrown by the parent class's method.
29. Is it legal for the extending class which overrides a method which throws an exception, not to throw in the overridden class?
Yes, it is perfectly legal
If you have any questions that you want answer for - please leave a comment on this page and I will answer them.
If you have any more questions on Exception Handling that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.
More Java & J2EE Interview Questions with Answers - Click Here
Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Exception Handling that you might find useful. You can use them to revise/review your understanding of Exception Handling.
They are:
Exception Handling
Common Exceptions & Errors
Questions:
1. How could Java classes direct messages to a file instead of the Console?
The System class has a variable "out" that represents the standard output, and the variable "err" that represents the standard error device. By default, they both point at the system console.
The standard output could be re-directed to a file as follows:
Stream st = new Stream(new FileOutputStream("output.txt"));
System.setErr(st);
System.setOut(st);
2. Does it matter in what order catch statements for FileNotFoundException and IOException are written?
Yes, it does. The child exceptions classes must always be caught first and the "Exception" class should be caught last.
3. What is user-defined exception in java ?
User-defined expections are the exceptions defined by the application developer which are errors related to specific application. Application Developer can define the user defined exception by inheriting the Exception class. Using this class we can create & throw new exceptions.
4. What is the difference between checked and Unchecked Exceptions in Java ?
Checked exceptions must be caught using try-catch() block or thrown using throws clause. If you dont, compilation of program will fail. whereas we need not catch or throw Unchecked exceptions.
5. What is the catch or declare rule for method declarations?
If a checked exception may be thrown within the body of a method, the method must either catch that exception or declare it in its throws clause. This is done to ensure that there are no orphan exceptions that are not handled by any method.
6. What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. It is usually used in places where we are connecting to a database so that, we can close the connection or perform any cleanup even if the query execution in the try block caused an exception.
7. What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.
8. Can an exception be rethrown?
Yes, an exception can be rethrown any number of times.
9. When is the finally clause of a try-catch-finally statement executed?
The finally clause of the try-catch-finally statement is always executed after the catch block is executed, unless the thread of execution terminates or an exception occurs within the execution of the finally clause.
10. What classes of exceptions may be thrown by a throw statement?
A throw statement may throw any expression that may be assigned to the Throwable type.
11. What happens if an exception is not caught?
An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.
12. What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?
The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination.
13. Can try statements be nested?
Try statements can be tested. It is possible to nest them to any level, but it is preferable to keep the nesting to 2 or 3 levels at max.
14. How does a try statement determine which catch clause should be used to handle an exception?
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception that was thrown, is executed. The remaining catch clauses are ignored.
15. What is difference between error and exception
Error occurs at runtime and cannot be recovered, Outofmemory is one such example. Exceptions on the other hand are due conditions which the application encounters, that can be recovered such as FileNotFound exception or IO exceptions
16. What is the base class from which all exceptions are subclasses
All exceptions are subclasses of a class called java.lang.Throwable
17. How do you intercept and control exceptions
We can intercept and control exceptions by using try/catch/finally blocks.
You place the normal processing code in try block
You put the code to deal with exceptions that might arise in try block in catch block
Code that must be executed no matter what happens must be place in finally block
18. When do we say an exception is handled
When an exception is thrown in a try block and is caught by a matching catch block, the exception is considered to have been handled. Or when an exception thrown by a method is caught by the calling method and handled, an exception can be considered handled.
19. When do we say an exception is not handled
There is no catch block that names either the class of exception that has been thrown or a class of exception that is a parent class of the one that has been thrown, then the exception is considered to be unhandled, in such condition the execution leaves the method directly as if no try has been executed
20. In what sequence does the finally block gets executed
If you put finally after a try block without a matching catch block then it will be executed after the try block
If it is placed after the catch block and there is no exception then also it will be executed after the try block
If there is an exception and it is handled by the catch block then it will be executed after the catch block
21. What can prevent the execution of the code in finally block
Theoretically, the finally block will execute no matter what. But practically, the following scenarios can prevent the execution of the finally block.
* The death of thread
* Use of system.exit()
* Turning off the power to CPU
* An exception arising in the finally block itself
22. What are the rules for catching multiple exceptions?
A more specific catch block must precede a more general one in the source, else it gives compilation error about unreachable code blocks.
23. What does throws statement declaration in a method indicate?
This indicates that the method throws some exception and the caller method should take care of handling it. If a method invokes another method that throws some exception, the compiler will complain until the method itself throws it or surrounds the method invocation with a try-catch block.
24. What are checked exceptions?
Checked exceptions are exceptions that arise in a correct program, typically due to user mistakes like entering wrong data or I/O problems. Checked Exceptions can be caught and handled by the programmer to avoid random error messages on screen.
25. What are runtime exceptions
Runtime exceptions are due to programming bugs like out of bound arrays or null pointer exceptions.
26. What is difference between Exception and errors
Errors are situations that cannot be recovered and the system will just crash or end. Whereas, Exceptions are just unexpected situations that can be handled and the system can recover from it. We usually catch & handle exceptions while we dont handle Errors.
27. How will you handle the checked exceptions
You can provide a try/catch block to handle it or throw the exception from the method and have the calling method handle it.
28. When you extend a class and override a method, can this new method throw exceptions other than those that were declared by the original method?
No it cannot throw, except for the subclasses of the exceptions thrown by the parent class's method.
29. Is it legal for the extending class which overrides a method which throws an exception, not to throw in the overridden class?
Yes, it is perfectly legal
If you have any questions that you want answer for - please leave a comment on this page and I will answer them.
If you have any more questions on Exception Handling that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.
More Java & J2EE Interview Questions with Answers - Click Here
Servlet Interview Questions
The following are some questions you might encounter with respect to Java Servlets in any Interview. Servlets are the back-bone of almost all J2EE Web Applications and any interviewer who is selecting people for his J2EE project would want a person who is confident & comfortable using them.
Apart from the questions below, there are a few articles that I have put up (as part of the SCWCD Certification series) on Servlets that you might find useful. You can use them to revise/review your understanding of Servlets.
They are:
Servlet History
Servlet Handling of Http Requests
Servlet Request Types
Obtaining a Servlets Initialization Parameters
Servlet Context
Servlet Life-cycle
Servlet Exception Handling
Servlet API
Questions:
1. What is a Servlet?
Java Servlets are server side components that provides a powerful mechanism for developing server side of web application. Earlier CGI was used to provide server side capabilities for web applications. Although CGI played a major role in the explosion of the Internet, its performance, scalability and reusability issues made it less and less desirable among people who wanted enterprise class scalable applications. Java Servlets was the solution to all of CGIs problems. Built from ground up using Sun's java technology, servlets provide excellent framework for server side processing. They are an integral part of almost all J2EE applications
2. What are the types of Servlet?
There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides http protocl specific functionality.
3. What are the differences between HttpServlet and Generic Servlets?
GenericServlet defines a generic, protocol-independent servlet whereas HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site that uses the Http Protocol.
4. What are the differences between a Servlet and an Applet?
* Servlets are server side components that executes on the server whereas applets are client side components and executes on the web browser.
* Applets have GUI interface but there is no GUI interface in case of Servlets.
* Applets have limited capabilities whereas Servlets are very poweful and can support a wide variety of operations
* Servlets can perform operations like interacting with other servlets, JSP Pages, connect to databases etc while Applets cannot do all this.
5. What are the differences between the doGet and doPost methods?
* Get sends information from the browser to the Servlet as contents appended to the query string in the URL while Post uses hidden variables
* Because of the above point, post is a lot safer than get
* Get has a size limitation - i.e., we can send only approximately 1 Kb of data while Post can send a singnificantly higher amount of data
* Get is the most common type of sending data from a browser to a servlet, while Post is gaining popularity because of its size and safety which is better than the get.
6. What are the different methods present in a HttpServlet?
The methods of HttpServlet class are :
* doGet() - To handle the GET, conditional GET, and HEAD requests
* doPost() - To handle POST requests
* doPut() - To handle PUT requests
* doDelete() - To handle DELETE requests
* doOptions() - To handle the OPTIONS requests and
* doTrace() - To handle the TRACE requests
Apart from these, a Servlet also contains init() and destroy() methods that are used to initialize and destroy the servlet respectively. They are not any operation specific and are available in all Servlets for use during their active life-cycle.
7. What are the advantages of Servlets over CGI programs?
Java Servlets have a number of advantages over CGI and other API's. Some are:
1. Platform Independence - Java Servlets are 100% pure Java, so it is platform independent. It can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server. You can easily run the same on apache web server without modification code. Platform independency of servlets provide a great advantages over alternatives of servlets.
2. Performance - Anyone who has used CGI would agree that Servlets are much more powerful and quicker than CGI. Because the underlying technology is Java, it is fast and can handle multiple request simultaneously. Also, a servlet gets initialized only once in its lifetime and then continues to serve requests without having to be re-initialized again, hence the performance is much higher than CGIs.
3. Extensibility - Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets takes all these advantages and can be extended from existing class the provide the ideal solutions.
Also, in terms of Safety & Security Servlets are superior when compared to CGI.
8. What are the lifecycle methods of Servlet?
The interface javax.servlet.Servlet, defines the three life-cycle methods. These are:
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
The container manages the lifecycle of the Servlet. When a new request come to a Servlet, the container performs the following steps:
1. If an instance of the servlet does not exist, the web container
* Loads the servlet class.
* Creates an instance of the servlet class.
* Initializes the servlet instance by calling the init method.
2. The container invokes the service method, passing request and response objects.
3. To remove the servlet, container finalizes the servlet by calling the servlet's destroy method.
9. What are the type of protocols supported by HttpServlet?
It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.
10. What is ServletContext?
ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine.
11. What is meant by Pre-initialization of Servlet?
When servlet container is loaded, all the servlets defined in the web.xml file do not get initialized by default. When the container receives a request to hit a particular servlet, it loads that servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called pre-initialization of Servlet. In this case, the servlet is loaded when context is loaded. You can specify1 in between the tag in the Web.xml file in order to pre-initialize your servlet
12. What mechanisms are used by a Servlet Container to maintain session information?
Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information to maintain the session.
13. What do you understand by servlet mapping?
Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url patterns. For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.
14. What interface must be implemented by all Servlets?
The Servlet Interface must be implemented by all servlets (either the GenericServlet or the HttpServlet)
15. What are the uses of Servlets?
* Servlets are used to process the client requests.
* A Servlet can handle multiple request concurrently and be used to develop high performance system
* A Servlet can be used to load balance among serveral servers, as Servlet can easily forward request.
16. What are the objects that are received when a servlets accepts call from client?
The objects are:
ServeltRequest and
ServletResponse
The ServeltRequest encapsulates the communication from the client to the
server. While ServletResponse encapsulates the communication from the Servlet back to the client. All the passage of data between the client and server happens by means of these request and response objects.
Some more questions on Servlets - Servlet Interview Questions - Part II
If you have any questions that you want answer for - please leave a comment on this page and I will answer them.
If you have any more questions on Servlets that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.
More Java & J2EE Interview Questions with Answers - Click Here
Apart from the questions below, there are a few articles that I have put up (as part of the SCWCD Certification series) on Servlets that you might find useful. You can use them to revise/review your understanding of Servlets.
They are:
Servlet History
Servlet Handling of Http Requests
Servlet Request Types
Obtaining a Servlets Initialization Parameters
Servlet Context
Servlet Life-cycle
Servlet Exception Handling
Servlet API
Questions:
1. What is a Servlet?
Java Servlets are server side components that provides a powerful mechanism for developing server side of web application. Earlier CGI was used to provide server side capabilities for web applications. Although CGI played a major role in the explosion of the Internet, its performance, scalability and reusability issues made it less and less desirable among people who wanted enterprise class scalable applications. Java Servlets was the solution to all of CGIs problems. Built from ground up using Sun's java technology, servlets provide excellent framework for server side processing. They are an integral part of almost all J2EE applications
2. What are the types of Servlet?
There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides http protocl specific functionality.
3. What are the differences between HttpServlet and Generic Servlets?
GenericServlet defines a generic, protocol-independent servlet whereas HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site that uses the Http Protocol.
4. What are the differences between a Servlet and an Applet?
* Servlets are server side components that executes on the server whereas applets are client side components and executes on the web browser.
* Applets have GUI interface but there is no GUI interface in case of Servlets.
* Applets have limited capabilities whereas Servlets are very poweful and can support a wide variety of operations
* Servlets can perform operations like interacting with other servlets, JSP Pages, connect to databases etc while Applets cannot do all this.
5. What are the differences between the doGet and doPost methods?
* Get sends information from the browser to the Servlet as contents appended to the query string in the URL while Post uses hidden variables
* Because of the above point, post is a lot safer than get
* Get has a size limitation - i.e., we can send only approximately 1 Kb of data while Post can send a singnificantly higher amount of data
* Get is the most common type of sending data from a browser to a servlet, while Post is gaining popularity because of its size and safety which is better than the get.
6. What are the different methods present in a HttpServlet?
The methods of HttpServlet class are :
* doGet() - To handle the GET, conditional GET, and HEAD requests
* doPost() - To handle POST requests
* doPut() - To handle PUT requests
* doDelete() - To handle DELETE requests
* doOptions() - To handle the OPTIONS requests and
* doTrace() - To handle the TRACE requests
Apart from these, a Servlet also contains init() and destroy() methods that are used to initialize and destroy the servlet respectively. They are not any operation specific and are available in all Servlets for use during their active life-cycle.
7. What are the advantages of Servlets over CGI programs?
Java Servlets have a number of advantages over CGI and other API's. Some are:
1. Platform Independence - Java Servlets are 100% pure Java, so it is platform independent. It can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server. You can easily run the same on apache web server without modification code. Platform independency of servlets provide a great advantages over alternatives of servlets.
2. Performance - Anyone who has used CGI would agree that Servlets are much more powerful and quicker than CGI. Because the underlying technology is Java, it is fast and can handle multiple request simultaneously. Also, a servlet gets initialized only once in its lifetime and then continues to serve requests without having to be re-initialized again, hence the performance is much higher than CGIs.
3. Extensibility - Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets takes all these advantages and can be extended from existing class the provide the ideal solutions.
Also, in terms of Safety & Security Servlets are superior when compared to CGI.
8. What are the lifecycle methods of Servlet?
The interface javax.servlet.Servlet, defines the three life-cycle methods. These are:
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
The container manages the lifecycle of the Servlet. When a new request come to a Servlet, the container performs the following steps:
1. If an instance of the servlet does not exist, the web container
* Loads the servlet class.
* Creates an instance of the servlet class.
* Initializes the servlet instance by calling the init method.
2. The container invokes the service method, passing request and response objects.
3. To remove the servlet, container finalizes the servlet by calling the servlet's destroy method.
9. What are the type of protocols supported by HttpServlet?
It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.
10. What is ServletContext?
ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine.
11. What is meant by Pre-initialization of Servlet?
When servlet container is loaded, all the servlets defined in the web.xml file do not get initialized by default. When the container receives a request to hit a particular servlet, it loads that servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called pre-initialization of Servlet. In this case, the servlet is loaded when context is loaded. You can specify
12. What mechanisms are used by a Servlet Container to maintain session information?
Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information to maintain the session.
13. What do you understand by servlet mapping?
Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url patterns. For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.
14. What interface must be implemented by all Servlets?
The Servlet Interface must be implemented by all servlets (either the GenericServlet or the HttpServlet)
15. What are the uses of Servlets?
* Servlets are used to process the client requests.
* A Servlet can handle multiple request concurrently and be used to develop high performance system
* A Servlet can be used to load balance among serveral servers, as Servlet can easily forward request.
16. What are the objects that are received when a servlets accepts call from client?
The objects are:
ServeltRequest and
ServletResponse
The ServeltRequest encapsulates the communication from the client to the
server. While ServletResponse encapsulates the communication from the Servlet back to the client. All the passage of data between the client and server happens by means of these request and response objects.
Some more questions on Servlets - Servlet Interview Questions - Part II
If you have any questions that you want answer for - please leave a comment on this page and I will answer them.
If you have any more questions on Servlets that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.
More Java & J2EE Interview Questions with Answers - Click Here
JSP Interview Questions
The following are some questions you might encounter with respect to Java Server Pages or JSPs in any Interview. JSPs are an integral part of almost all J2EE Web Applications and any interviewer who is selecting people for his J2EE project would want a person who is confident & comfortable using them.
Apart from the questions below, there are a few articles that I have put up (as part of the SCWCD Certification series) on JSPs that you might find useful. You can use them to revise/review your understanding of Servlets.
They are:
Introduction to JSPs
JSP Life Cycle
JSP Implicit Objects
Questions:
1. What is JSP?
JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web applications in a portable, secure and well-defined way. The JSP Technology allows us to use HTML, Java, JavaScript and XML in a single file to create high quality and fully functionaly User Interface components for Web Applications.
2. What do you understand by JSP Actions?
JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters.
There are six JSP Actions:
< jsp : include / >
< jsp : forward / >
< jsp : plugin / >
< jsp : usebean / >
< jsp : setProperty / >
< jsp : getProperty / >
3. What is the difference between < jsp : include page = ... > and < % @ include file = ... >?
Both the tags include information from one JSP page in another. The differences are:
< jsp : include page = ... >
This is like a function call from one jsp to another jsp. It is executed ( the included page is executed and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful while modularizing a web application. If the included file changes then the new content will be included in the output automatically.
< % @ include file = ... >
In this case the content of the included file is textually embedded in the page that have < % @ include file=".."> directive. In this case when the included file changes, the changed content will not get included automatically in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.
4. What is the difference between < jsp : forward page = ... > and response.sendRedirect(url)?
The element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The response.sendRedirect also kills the session variables.
5. Name one advantage of JSP over Servlets?
Can contain HTML, JavaScript, XML and Java Code whereas Servlets can contain only Java Code, making JSPs more flexible and powerful than Servlets.
However, Servlets have their own place in a J2EE application and cannot be ignored altogether. They have their strengths too which cannot be overseen.
6. What are implicit Objects available to the JSP Page?
Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application. The JSP implicit objects are:
application
config
exception
out
page
pageContext
request
response and
session
7. What are all the different scope values for the < jsp : useBean > tag?
< jsp : useBean > tag is used to use any java object in the jsp page. Here are the scope values for < jsp : useBean > tag:
a) page
b) request
c) session and
d) application
8. What is JSP Output Comments?
JSP Output Comments are the comments that can be viewed in the HTML source file. They are comments that are enclosed within the < ! - - Your Comments Here - - >
9. What is expression in JSP?
Expression tag is used to insert Java values directly into the output.
Syntax for the Expression tag is: < %= expression % >
An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. The most commonly used language is regular Java.
10. What types of comments are available in the JSP?
There are two types of comments that are allowed in the JSP. They are hidden and output comments.
A hidden comment does not appear in the generated HTML output, while output comments appear in the generated output.
Example of hidden comment:
< % - - This is a hidden comment - - % >
Example of output comment:
< ! - - This is an output comment - - >
11. What is a JSP Scriptlet?
JSP Scriptlets is a term used to refer to pieces of Java code that can be embedded in a JSP PAge. Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet executes every time the JSP is invoked.
12. What are the life-cycle methods of JSP?
Life-cycle methods of the JSP are:
a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.
b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann't be overridden.
c) jspDestroy(): The container calls this when its instance is about to destroyed.
The jspInit() and jspDestroy() methods can be overridden within a JSP page.
13. What are JSP Custom tags?
JSP Custom tags are user defined JSP language elements. JSP custom tags are user defined tags that can encapsulate common functionality. For example you can write your own tag to access the database and performing database operations. You can also write custom tags to encapsulate both simple and complex behaviors in an easy to use syntax. The use of custom tags greatly enhances the functionality and simplifies the readability of JSP pages.
14. What is the role of JSP in MVC Model?
JSP is mostly used to develop the user interface, It plays are role of View in the MVC Model.
15. What do you understand by context initialization parameters?
The context-param element contains the declaration of a web application's servlet context initialization parameters.
< context - param >
< param - name > name < / param - name > < param - value > value < / param - value >
< / context-param >
The Context Parameters page lets you manage parameters that are accessed through the ServletContext.getInitParameterNames and ServletContext.getInitParameter methods.
16. Can you extend JSP technology?
Yes. JSP technology lets the programmer to extend the jsp to make the programming more easier. JSP can be extended and custom actions & tag libraries can be developed to enhance/extend its features.
17. What do you understand by JSP translation?
JSP translation is an action that refers to the convertion of the JSP Page into a Java Servlet. This class is essentially a servlet class wrapped with features for JSP functionality.
18. How can you prevent the Browser from Caching data of the Pages you visit?
By setting properties that prevent caching in your JSP Page. They are:
19. How will you handle the runtime exception in your jsp page?
The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and then forwarded to an error processing page. You can define the error page to which you want the request forwarded to, in case of an exception, in each JSP Page. Also, there should be another JSP that plays the role of the error page which has the flag isErrorPage set to True.
20. What is JavaServer Pages Standard Tag Library (JSTL) ?
A tag library that encapsulates core functionality common to many JSP applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization and locale-specific formatting tags, SQL tags, and functions.
21. What is JSP container ?
A container that provides the same services as a servlet container and an engine that interprets and processes JSP pages into a servlet.
22. What is JSP custom action ?
A user-defined action described in a portable manner by a tag library descriptor and imported into a JSP page by a taglib directive. Custom actions are used to encapsulate recurring tasks in writing JSP pages.
23. What is JSP custom tag ?
A tag that references a JSP custom action.
24. What is JSP declaration ?
A JSP scripting element that declares methods, variables, or both in a JSP page.
25. What is JSP directive ?
A JSP element that gives an instruction to the JSP container and is interpreted at translation time.
26. What is JSP document ?
A JSP page written in XML syntax and subject to the constraints of XML documents.
27. What is JSP element ?
A portion of a JSP page that is recognized by a JSP translator. An element can be a directive, an action, or a scripting element.
28. What is JSP expression ?
A scripting element that contains a valid scripting language expression that is evaluated, converted to a String, and placed into the implicit out object.
29. What is JSP expression language ?
A language used to write expressions that access the properties of JavaBeans components. EL expressions can be used in static text and in any standard or custom tag attribute that can accept an expression.
30. What is JSP page ?
A text-based document containing static text and JSP elements that describes how to process a request to create a response. A JSP page is translated into and handles requests as a servlet.
31. What is JSP scripting element ?
A JSP declaration, scriptlet, or expression whose syntax is defined by the JSP specification and whose content is written according to the scripting language used in the JSP page. The JSP specification describes the syntax and semantics for the case where the language page attribute is "java".
32. What is JSP scriptlet ?
A JSP scripting element containing any code fragment that is valid in the scripting language used in the JSP page. The JSP specification describes what is a valid scriptlet for the case where the language page attribute is "java".
33. What is JSP tag file ?
A source file containing a reusable fragment of JSP code that is translated into a tag handler when a JSP page is translated into a servlet.
34. What is JSP tag handler ?
A Java programming language object that implements the behavior of a custom tag.
If you have any questions that you want answer for - please leave a comment on this page and I will answer them.
If you have any more questions on JSPs that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.
More Java & J2EE Interview Questions with Answers - Click Here
Apart from the questions below, there are a few articles that I have put up (as part of the SCWCD Certification series) on JSPs that you might find useful. You can use them to revise/review your understanding of Servlets.
They are:
Introduction to JSPs
JSP Life Cycle
JSP Implicit Objects
Questions:
1. What is JSP?
JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web applications in a portable, secure and well-defined way. The JSP Technology allows us to use HTML, Java, JavaScript and XML in a single file to create high quality and fully functionaly User Interface components for Web Applications.
2. What do you understand by JSP Actions?
JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters.
There are six JSP Actions:
< jsp : include / >
< jsp : forward / >
< jsp : plugin / >
< jsp : usebean / >
< jsp : setProperty / >
< jsp : getProperty / >
3. What is the difference between < jsp : include page = ... > and < % @ include file = ... >?
Both the tags include information from one JSP page in another. The differences are:
< jsp : include page = ... >
This is like a function call from one jsp to another jsp. It is executed ( the included page is executed and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful while modularizing a web application. If the included file changes then the new content will be included in the output automatically.
< % @ include file = ... >
In this case the content of the included file is textually embedded in the page that have < % @ include file=".."> directive. In this case when the included file changes, the changed content will not get included automatically in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.
4. What is the difference between < jsp : forward page = ... > and response.sendRedirect(url)?
The
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The response.sendRedirect also kills the session variables.
5. Name one advantage of JSP over Servlets?
Can contain HTML, JavaScript, XML and Java Code whereas Servlets can contain only Java Code, making JSPs more flexible and powerful than Servlets.
However, Servlets have their own place in a J2EE application and cannot be ignored altogether. They have their strengths too which cannot be overseen.
6. What are implicit Objects available to the JSP Page?
Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application. The JSP implicit objects are:
application
config
exception
out
page
pageContext
request
response and
session
7. What are all the different scope values for the < jsp : useBean > tag?
< jsp : useBean > tag is used to use any java object in the jsp page. Here are the scope values for < jsp : useBean > tag:
a) page
b) request
c) session and
d) application
8. What is JSP Output Comments?
JSP Output Comments are the comments that can be viewed in the HTML source file. They are comments that are enclosed within the < ! - - Your Comments Here - - >
9. What is expression in JSP?
Expression tag is used to insert Java values directly into the output.
Syntax for the Expression tag is: < %= expression % >
An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. The most commonly used language is regular Java.
10. What types of comments are available in the JSP?
There are two types of comments that are allowed in the JSP. They are hidden and output comments.
A hidden comment does not appear in the generated HTML output, while output comments appear in the generated output.
Example of hidden comment:
< % - - This is a hidden comment - - % >
Example of output comment:
< ! - - This is an output comment - - >
11. What is a JSP Scriptlet?
JSP Scriptlets is a term used to refer to pieces of Java code that can be embedded in a JSP PAge. Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet executes every time the JSP is invoked.
12. What are the life-cycle methods of JSP?
Life-cycle methods of the JSP are:
a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.
b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann't be overridden.
c) jspDestroy(): The container calls this when its instance is about to destroyed.
The jspInit() and jspDestroy() methods can be overridden within a JSP page.
13. What are JSP Custom tags?
JSP Custom tags are user defined JSP language elements. JSP custom tags are user defined tags that can encapsulate common functionality. For example you can write your own tag to access the database and performing database operations. You can also write custom tags to encapsulate both simple and complex behaviors in an easy to use syntax. The use of custom tags greatly enhances the functionality and simplifies the readability of JSP pages.
14. What is the role of JSP in MVC Model?
JSP is mostly used to develop the user interface, It plays are role of View in the MVC Model.
15. What do you understand by context initialization parameters?
The context-param element contains the declaration of a web application's servlet context initialization parameters.
< context - param >
< param - name > name < / param - name > < param - value > value < / param - value >
< / context-param >
The Context Parameters page lets you manage parameters that are accessed through the ServletContext.getInitParameterNames and ServletContext.getInitParameter methods.
16. Can you extend JSP technology?
Yes. JSP technology lets the programmer to extend the jsp to make the programming more easier. JSP can be extended and custom actions & tag libraries can be developed to enhance/extend its features.
17. What do you understand by JSP translation?
JSP translation is an action that refers to the convertion of the JSP Page into a Java Servlet. This class is essentially a servlet class wrapped with features for JSP functionality.
18. How can you prevent the Browser from Caching data of the Pages you visit?
By setting properties that prevent caching in your JSP Page. They are:
<%
response.setHeader("pragma","no-cache");//HTTP 1.1
response.setHeader("Cache-Control","no-cache");
response.setHeader("Cache-Control","no-store");
response.addDateHeader("Expires", -1);
response.setDateHeader("max-age", 0);
//response.setIntHeader ("Expires", -1); //prevents caching at the proxy server
response.addHeader("cache-Control", "private");
%>
19. How will you handle the runtime exception in your jsp page?
The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and then forwarded to an error processing page. You can define the error page to which you want the request forwarded to, in case of an exception, in each JSP Page. Also, there should be another JSP that plays the role of the error page which has the flag isErrorPage set to True.
20. What is JavaServer Pages Standard Tag Library (JSTL) ?
A tag library that encapsulates core functionality common to many JSP applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization and locale-specific formatting tags, SQL tags, and functions.
21. What is JSP container ?
A container that provides the same services as a servlet container and an engine that interprets and processes JSP pages into a servlet.
22. What is JSP custom action ?
A user-defined action described in a portable manner by a tag library descriptor and imported into a JSP page by a taglib directive. Custom actions are used to encapsulate recurring tasks in writing JSP pages.
23. What is JSP custom tag ?
A tag that references a JSP custom action.
24. What is JSP declaration ?
A JSP scripting element that declares methods, variables, or both in a JSP page.
25. What is JSP directive ?
A JSP element that gives an instruction to the JSP container and is interpreted at translation time.
26. What is JSP document ?
A JSP page written in XML syntax and subject to the constraints of XML documents.
27. What is JSP element ?
A portion of a JSP page that is recognized by a JSP translator. An element can be a directive, an action, or a scripting element.
28. What is JSP expression ?
A scripting element that contains a valid scripting language expression that is evaluated, converted to a String, and placed into the implicit out object.
29. What is JSP expression language ?
A language used to write expressions that access the properties of JavaBeans components. EL expressions can be used in static text and in any standard or custom tag attribute that can accept an expression.
30. What is JSP page ?
A text-based document containing static text and JSP elements that describes how to process a request to create a response. A JSP page is translated into and handles requests as a servlet.
31. What is JSP scripting element ?
A JSP declaration, scriptlet, or expression whose syntax is defined by the JSP specification and whose content is written according to the scripting language used in the JSP page. The JSP specification describes the syntax and semantics for the case where the language page attribute is "java".
32. What is JSP scriptlet ?
A JSP scripting element containing any code fragment that is valid in the scripting language used in the JSP page. The JSP specification describes what is a valid scriptlet for the case where the language page attribute is "java".
33. What is JSP tag file ?
A source file containing a reusable fragment of JSP code that is translated into a tag handler when a JSP page is translated into a servlet.
34. What is JSP tag handler ?
A Java programming language object that implements the behavior of a custom tag.
If you have any questions that you want answer for - please leave a comment on this page and I will answer them.
If you have any more questions on JSPs that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.
More Java & J2EE Interview Questions with Answers - Click Here
HttpSession Interview Questions
The following are some questions you might encounter with respect to HttpSessions in any Interview. Sessions are a very powerful feature and any interviewer who is selecting people for his J2EE project would want a person who is confident & comfortable using them.
Apart from the questions below, there are a few articles that I have put up (as part of the SCWCD Certification series) on Sessions that you might find useful. You can use them to revise/review your understanding of Sessions.
They are:
Introduction to Session Management
Storing & Retrieving Session Objects
Session Event Listeners
Invalidating Sessions
Session Tracking Through URL Rewriting
Summary of Session Topics
Questions:
1. What is a Session?
A Session refers to all the request that a single client makes to a server. A session is specific to the user and for each user a new session is created to track all the requests from that particular user. Sessions are not shared among users and each user of the system will have a seperate session and a unique session Id. In most cases, the default value of time-out* is 20 minutes and it can be changed as per the website requirements.
*Time-Out - The Amount of time after which a session becomes invalidated/destroyed if the session has been inactive.
2. What is Session ID?
A session ID is an unique identification string usually a long, random and alpha-numeric string, that is transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in case url rewriting) and hidden fields of Web pages.
3. What is Session Tracking?
HTTP is stateless protocol and it does not maintain the client state. But there exist a mechanism called "Session Tracking" which helps the servers to maintain the state to track the series of requests from the same user across some period of time.
4. What are different types of Session Tracking?
Mechanism for Session Tracking are:
a) Cookies
b) URL rewriting
c) Hidden form fields
d) SSL Sessions
5. What is HTTPSession Class?
HttpSession Class provides a way to identify a user across across multiple request. The servlet container uses HttpSession interface to create a session between an HTTP client and an HTTP server. The session lives only for a specified time period, across more than one connection or page request from the user.
6. Why do we need Session Tracking in a Servlet based Web Application?
In HttpServlet you can use Session Tracking to track the user state. Simply put, it is used to store information like users login credentials, his choices in previous pages (like in a shopping cart website) etc
7. What are the advantage of Cookies over URL rewriting?
Sessions tracking using Cookies are more secure and fast. It keeps the website URL clean and concise instead of a long string appended to the URL everytime you click on any link in the website. Also, when we use url rewriting, it requites large data transfer from and to the server. So, it may lead to significant network traffic and access to the websites may be become slow.
8. What is session hijacking?
If you application is not very secure then it is possible to get the access of system after acquiring or generating the authentication information. Session hijacking refers to the act of taking control of a user session after successfully obtaining or generating an authentication session ID. It involves an attacker using captured, brute forced or reverse-engineered session IDs to get a control of a legitimate user's Web application session while that session is still in progress.
9. What is Session Migration?
Session Migration is a mechanism of moving the session from one server to another in case of server failure. Session Migration can be implemented by:
a) Persisting the session into database
b) Storing the session in-memory on multiple servers.
10. How to track a user session in Servlets?
The interface HttpSession can be used to track the session in the Servlet. Following code can be used to create session object in the Servlet:
HttpSession session = req.getSession(true);
Using this session object, the servlet can gain access to the details of the session.
11. How can you destroy the session in Servlet?
You can call invalidate() method on the session object to destroy the session.
e.g. session.invalidate();
If you have any questions that you want answer for - please leave a comment on this page and I will answer them.
If you have any more questions on Sessions that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.
More Java & J2EE Interview Questions with Answers - Click Here
Apart from the questions below, there are a few articles that I have put up (as part of the SCWCD Certification series) on Sessions that you might find useful. You can use them to revise/review your understanding of Sessions.
They are:
Introduction to Session Management
Storing & Retrieving Session Objects
Session Event Listeners
Invalidating Sessions
Session Tracking Through URL Rewriting
Summary of Session Topics
Questions:
1. What is a Session?
A Session refers to all the request that a single client makes to a server. A session is specific to the user and for each user a new session is created to track all the requests from that particular user. Sessions are not shared among users and each user of the system will have a seperate session and a unique session Id. In most cases, the default value of time-out* is 20 minutes and it can be changed as per the website requirements.
*Time-Out - The Amount of time after which a session becomes invalidated/destroyed if the session has been inactive.
2. What is Session ID?
A session ID is an unique identification string usually a long, random and alpha-numeric string, that is transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in case url rewriting) and hidden fields of Web pages.
3. What is Session Tracking?
HTTP is stateless protocol and it does not maintain the client state. But there exist a mechanism called "Session Tracking" which helps the servers to maintain the state to track the series of requests from the same user across some period of time.
4. What are different types of Session Tracking?
Mechanism for Session Tracking are:
a) Cookies
b) URL rewriting
c) Hidden form fields
d) SSL Sessions
5. What is HTTPSession Class?
HttpSession Class provides a way to identify a user across across multiple request. The servlet container uses HttpSession interface to create a session between an HTTP client and an HTTP server. The session lives only for a specified time period, across more than one connection or page request from the user.
6. Why do we need Session Tracking in a Servlet based Web Application?
In HttpServlet you can use Session Tracking to track the user state. Simply put, it is used to store information like users login credentials, his choices in previous pages (like in a shopping cart website) etc
7. What are the advantage of Cookies over URL rewriting?
Sessions tracking using Cookies are more secure and fast. It keeps the website URL clean and concise instead of a long string appended to the URL everytime you click on any link in the website. Also, when we use url rewriting, it requites large data transfer from and to the server. So, it may lead to significant network traffic and access to the websites may be become slow.
8. What is session hijacking?
If you application is not very secure then it is possible to get the access of system after acquiring or generating the authentication information. Session hijacking refers to the act of taking control of a user session after successfully obtaining or generating an authentication session ID. It involves an attacker using captured, brute forced or reverse-engineered session IDs to get a control of a legitimate user's Web application session while that session is still in progress.
9. What is Session Migration?
Session Migration is a mechanism of moving the session from one server to another in case of server failure. Session Migration can be implemented by:
a) Persisting the session into database
b) Storing the session in-memory on multiple servers.
10. How to track a user session in Servlets?
The interface HttpSession can be used to track the session in the Servlet. Following code can be used to create session object in the Servlet:
HttpSession session = req.getSession(true);
Using this session object, the servlet can gain access to the details of the session.
11. How can you destroy the session in Servlet?
You can call invalidate() method on the session object to destroy the session.
e.g. session.invalidate();
If you have any questions that you want answer for - please leave a comment on this page and I will answer them.
If you have any more questions on Sessions that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.
More Java & J2EE Interview Questions with Answers - Click Here
Subscribe to:
Posts (Atom)
© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.
