Wednesday, June 2, 2010

java faqs


http://www.javabeat.net/tutorials/53-developing-application-with-struts-tiles.html

74) What are the different cases for using sendRedirect() vs. getRequestDispatcher()?


When you want to preserve the current request/response objects and transfer them to another resource WITHIN the context, you must use getRequestDispatcher or getNamedDispatcher.

If you want to dispatch to resources OUTSIDE the context, then you must use sendRedirect. In this case you won't be sending the original request/response objects, but you will be sending a header asking to the browser to issue a request to the new URL.

If you don't need to preserve the request/response objects, you can use either.

94) What is the difference between ServletContext and ServletConfig?

A ServletContext represents the context in a servlet container of a servlet instance operates. A servlet container can have several contexts (or web applications) at one time. Each servlet instance is running in one of these contexts. All servlets instances running in the same context are part of the same web application and, therefore, share common resources. A servlet accesses these shared resource (such as a RequestDispatcher and application properties) through the ServletContext object.

This notion of a web application became very significant upon the Servlet 2.1 API, where you could deploy an entire web application in a WAR file. Notice that I always said "servlet instance", not servlet. That is because the same servlet can be used in several web applications at one time. In fact, this may be common if there is a generic controller servlet that can be configured at run time for a specific application. Then, you would have several instances of the same servlet running, each possibly having different configurations.

This is where the ServletConfig comes in. This object defines how a servlet is to be configured is passed to a servlet in its init method. Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters. The container, in turn, passes these parameters to the servlet via the ServetConfig.

98) How can I return a readily available (static) HTML page to the user instead of generating it in the servlet?

To solve your problem, you can either send a "Redirect" back to the client or use a RequestDispatcher and forward your request to another page:

   1. Redirect:

      A redirection is made using the HttpServletResponse object:


          if(condition) {
             response.sendRedirect("page1.html");
          } else {
                 response.sendRedirect("page2.html");
          }

   2. RequestDispatcher:

      A request dispatcher can be obtained through the ServletContext. It can be used to include another page or to forward to it.


          if(condition) {
             this.getServletContext()
                   .getRequestDispatcher("page1.html").forward();
          } else {
            this.getServletContext()
                   .getRequestDispatcher("page2.html").forward();
          }

Both solutions require, that the pages are available in you document root. If they are located somewhere else on your filesystem, you have to open the file manually and copy their content to the output writer.

If your application server is set up in combination with a normal web server like Apache, you should use solution (1), because the the web server usually serves static files much faster than the application server.



EXCEPTIONS IN JAVA



) What is an Exception?

An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error.
2) What is a Java Exception?

A Java exception is an object that describes an exceptional condition i.e., an error condition that has occurred in a piece of code. When this type of condition arises, an object representing that exception is created and thrown in the method that caused the error by the Java Runtime. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed.
3) What are the different ways to generate and Exception?

There are two different ways to generate an Exception.

   1. Exceptions can be generated by the Java run-time system.

      Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment.
   2. Exceptions can be manually generated by your code.

      Manually generated exceptions are typically used to report some error condition to the caller of a method.

4) Where does Exception stand in the Java tree hierarchy?

    * java.lang.Object
    * java.lang.Throwable
    * java.lang.Exception
    * java.lang.Error

5) Is it compulsory to use the finally block?

It is always a good practice to use the finally block. The reason for using the finally block is, any unreleased resources can be released and the memory can be freed. For example while closing a connection object an exception has occurred. In finally block we can close that object. Coming to the question, you can omit the finally block when there is a catch block associated with that try block. A try block should have at least a catch or a finally block.
6) How are try, catch and finally block organized?

A try block should associate with at least a catch or a finally block. The sequence of try, catch and finally matters a lot. If you modify the order of these then the code won’t compile. Adding to this there can be multiple catch blocks associated with a try block. The final concept is there should be a single try, multiple catch blocks and a single finally block in a try-catch-finally block.
7) What is a throw in an Exception block?

“throw” is used to manually throw an exception (object) of type Throwable class or a subclass of Throwable. Simple types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.


          throw ThrowableInstance;

          ThrowableInstance must be an object of type Throwable or a subclass of Throwable.

          throw new NullPointerException("thrownException");

8) What is the use of throws keyword?

If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw.


          type method-name(parameter-list) throws exception-list
          {
             // body of method
          }
          Warning: main(http://www.javabeat.net/javabeat/templates/faqs/faqs_middle.html):
          failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in
          /home/content/k/k/s/kkskrishna/html/faqs/exception/exception-faqs-1.html on line 195

          Warning: main(http://www.javabeat.net/javabeat/templates/faqs/faqs_middle.html):
          failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in
          /home/content/k/k/s/kkskrishna/html/faqs/exception/exception-faqs-1.html on line 195

          Warning: main(): Failed opening 'http://www.javabeat.net/javabeat/templates/faqs/faqs_middle.html' for inclusion
          (include_path='.:/usr/local/lib/php') in /home/content/k/k/s/kkskrishna/html/faqs/exception/exception-faqs-1.html
           on line 195


          Here, exception-list is a comma-separated list of the exceptions that a method can throw.


          static void throwOne() throws IllegalAccessException {

          System.out.println("Inside throwOne.");

9) What are Checked Exceptions and Unchecked Exceptions?

The types of exceptions that need not be included in a methods throws list are called Unchecked Exceptions.

    * ArithmeticException
    * ArrayIndexOutOfBoundsException
    * ClassCastException
    * IndexOutOfBoundsException
    * IllegalStateException
    * NullPointerException
    * SecurityException

The types of exceptions that must be included in a methods throws list if that method can generate one of these exceptions and does not handle it itself are called Checked Exceptions.

    * ClassNotFoundException
    * CloneNotSupportedException
    * IllegalAccessException
    * InstantiationException
    * InterruptedException
    * NoSuchFieldException
    * NoSuchMethodException

10) What are Chained Exceptions?

The chained exception feature allows you to associate another exception with an exception. This second exception describes the cause of the first exception. Lets take a simple example. You are trying to read a number from the disk and using it to divide a number. Think the method throws an ArithmeticException because of an attempt to divide by zero (number we got). However, the problem was that an I/O error occurred, which caused the divisor to be set improperly (set to zero). Although the method must certainly throw an ArithmeticException, since that is the error that occurred, you might also want to let the calling code know that the underlying cause was an I/O error. This is the place where chained exceptions come in to picture.


          Throwable getCause( )
         
          Throwable initCause(Throwable causeExc)

No comments:

Post a Comment