Tuesday, April 23, 2013

Servlet Question Answers


                    Certain Servlets interview Q/As

Q1. What is a servlet ?
Servlets are modules that extend request/response-oriented servers,such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database. Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

Q2. Whats the advantages using servlets over using CGI?
Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension.

Q3. What are the general advantages and selling points of Servlets?
A servlet can handle multiple requests concurrently, and synchronize requests. This allows servlets to support systems such as online real-time conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

Q4. Which package provides interfaces and classes for writing servlets? 
javax

Q5. What’s the Servlet Interface?
The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.Servlets > Generic Servlet > HttpServlet > MyServlet. The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

Q6. When a servlet accepts a call from a client, it receives two objects. What are they?
ServletRequest (which encapsulates the communication from the client to the server) and ServletResponse (which encapsulates the communication from the servlet back to the client). ServletRequest and ServletResponse are interfaces defined inside javax.servlet package.

Q7. What information does ServletRequest allow access to?
Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. Also the input stream, as ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and GET methods.

Q8. What type of constraints can ServletResponse interface set on the client?
It can set the content length and MIME type of the reply. It also provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

Q9. Explain servlet lifecycle?
Each servlet has the same life cycle: first, the server loads and initializes the servlet (init()), then the servlet handles zero or more client requests (service()), after that the server removes the servlet (destroy()). Worth noting that the last step on some servers is done when they shut down.

Q10. How does HTTP Servlet handle client requests?
An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

Monday, April 22, 2013

JSP Interview Questions


Certain JSP interview question answers...


Q1. What is a JSP and what is it used for?

Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page.



Q2. What is difference between custom JSP tags and beans? 

Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files.


To use custom JSP tags, you need to define three separate components:

1. the tag handler class that defines the tag\'s behavior
2. the tag library descriptor file that maps the XML element names to the tag implementations 
3. the JSP file that uses the tag library 


When the first two components are done, you can use the tag by using taglib directive: 


<%@ taglib uri="xxx.tld" prefix="..." %>


Then you are ready to use the tags you defined.

Let's say the tag prefix is test: 
MyJSPTag or JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags to declare a bean and use to set value of the bean class and use to get value of the bean class. 
<%=identifier.getclassField() %>
Custom tags and beans accomplish the same goals, encapsulating complex behavior into simple and accessible forms.

There are several differences:
a) Custom tags can manipulate JSP content; beans cannot.
b) Complex operations can be reduced to a significantly simpler form with custom tags than with beans. c) Custom tags require quite a bit more work to set up than do beans. 
d) Custom tags usually define relatively self-contained behavior, whereas beans are often defined in   one servlet and used in a different servlet or JSP page.
e) Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.



Q3. What are the two kinds of comments in JSP and what's the difference between them ?

1. JSP Comment

    Example:     <%-- JSP Comment --%>
2. HTML Comment
    Example:     <!-- HTML Comment -->

Q4. What is JSP technology?

Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language.

Q5. How can a servlet refresh automatically if some new data has entered the database? 

You can use a client-side Refresh or Server Push.



Q6. How many JSP scripting elements and what are they? 

There are three scripting language elements:
1. declarations 
2. scriptlets 
3. expressions


Q7. Why are JSP pages the preferred API for creating a web-based client program? 

Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.


Q8. Is JSP technology extensible? 

YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.


Q9. What are the implicit objects? 

Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. 

They are:
1. request 
2. response 

3. exception
4. pageContext

5. out  
6. session 
7. application

8. config 
9. page



Q10. Can we use the constructor, instead of init(), to initialize servlet? 

Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.


Q11. What is JSP page? 

A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.




Sunday, January 20, 2013

Java Today: Servlets

Java Today: Servlets:                 Basic Information about Servlets in Java: 1. Servlets are server side components that provide a powerful mechanism...

Interview Questions - Servlets and latest version







Hi Friends...!!..

Check out the new version of Java7. You may click the link below

http://www.java.com/en/download/index.jsp

Some brief information about Java:


1. Java is a general-purpose, concurrent, class-based, object-oriented computer programming language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" meaning that code that runs on one platform does not need to be recompiled to run on another.

2.  Java applications are typically compiled to bytecode (class file) that can run on any JVM regardless of computer architecture. Java is, as of 2012, one of the most popular programming languages in use, particularly for client-server web applications, with a reported 15 million users. Java was originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C++, but it has fewer low-level facilities than either of them.

Some questions about Servlets:
Technical Interviewers ask mostly from this topic just to check your basic skills.

Q:
What is the difference between HttpServlet and GenericServlet?
A:
A GenericServlet has a service() method aimed to handle requests. 
HttpServlet extends GenericServlet and adds support for doGet(), 
doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), 
doDelete(), doTrace() methods (HTTP). 
Both these classes are abstract.




Q:
What is the difference between ServletContext and ServletConfig?
A:
ServletContext: 
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.
The ServletContext object is contained within the ServletConfig object,
 which the Web server provides the servlet when the servlet is initialized 

ServletConfig: 
The object created after a servlet is instantiated and 
its default constructor is read. It is created to pass initialization information
 to the servlet.



Monday, July 16, 2012

sleep() method in Java...


                               sleep() method in Java...


1. see which exception it throws
2. see how it works..


Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. The sleep method can also be used for pacing, as shown in the example that follows, and waiting for another thread with duties that are understood to have time requirements, as with the SimpleThreads example in a later section.
Two overloaded versions of sleep are provided: one that specifies the sleep time to the millisecond and one that specifies the sleep time to the nanosecond. However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS. Also, the sleep period can be terminated by interrupts, as we'll see in a later section. In any case, you cannot assume that invoking sleep will suspend the thread for precisely the time period specified.
The SleepMessages example uses sleep to print messages at four-second intervals:


public class SleepMessages {
    public static void main(String args[])
        throws InterruptedException {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };

        for (int i = 0;
             i < importantInfo.length;
             i++) {
            //Pause for 4 seconds
            Thread.sleep(4000);
            //Print a message
            System.out.println(importantInfo[i]);
        }
    }
}

Notice that main declares that it throws InterruptedException. This is an exception that sleep throws when another thread interrupts the current thread while sleep is active. Since this application has not defined another thread to cause the interrupt, it doesn't bother to catch InterruptedException.

Saturday, July 14, 2012

Exceptions in java with an example


Overview

Java has a powerful concept for exception and error handling. An exception is an error that occurs at runtime. It is either generated by the Java Virtual Machine (VM) in response to an unexpected condition or it is generated by your code as a result of executing a throw statement.

Understanding Exceptions

Exceptions generated from runtime are called unchecked exceptions, since it is not possible for the compiler to determine that your code will handle the exception. Exception classes that descend from RuntimeException and Error classes are unchecked exceptions. Examples for RuntimeException are illegal cast operation, inappropriate use of a null pointer, referencing an out of bounds array element. Errorexception classes signal critical problems that typically cannot be handled by your application. Examples are out of memory error, stack overflow, failure of the Java VM.

Thrown exceptions are referred to as checked exceptions. The compiler will confirm at compile time that the method includes code that might throw an exception. Moreover the compiler requires the code that calls such a method to include this call within atry block, and provide an appropriate catch block to catch the exception.

java.lang.Object
   |
   +--java.lang.Throwable
         |
         +--java.lang.Exception
         |     |
         |     +--java.lang.ClassNotFoundException
         |     |
         |     +--java.io.IOException
         |     |     |
         |     |     +--java.io.FileNotFoundException
         |     |
         |     +--java.lang.RuntimeException
         |           |
         |           +--java.lang.NullPointerException
         |           |
         |           +--java.lang.IndexOutOfBoundsException
         |                 |
         |                 +--java.lang.ArrayIndexOutOfBoundsException
         |
         +--java.lang.Error
               |
               +--java.lang.VirtualMachineError
                     |
                     +--java.lang.OutOfMemoryError

When an (either checked or unchecked) exception is thrown, execution will attempt to immediately branch to the first catch block whose associated exception class matches the class or a superclass of the thrown exception. If the exception does not occur within a try block or the thrown exception is not caught in a matching catchblock, execution of the method immediately terminates and control returns to the invoker of the method, where this process is repeated. The result is that the exception chain is escalated until a matching catch block is found. If not, the thread containing the thrown exception is terminated.

Example

The following Demo1 class demonstrates the behaviour of exceptions and applications.

import java.io.*;
class Demo1 {
  public static FileInputStream f1(String fileName)
    throws FileNotFoundException
  {
    FileInputStream fis = new FileInputStream(fileName);
    System.out.println("f1: File input stream created");
    return fis;
  }
  public static FileInputStream f2(String fileName)
  {
    FileInputStream fis = null;
    try
    {
      fis = new FileInputStream(fileName);
    }
    catch (FileNotFoundException ex)
    {
      System.out.println("f2: Oops, FileNotFoundException caught");
    }
    finally
    {
      System.out.println("f2: finally block");
    }
    System.out.println("f2: Returning from f2");
    return fis;
  }
  public static void main(String args[])
  {
    FileInputStream fis1 = null;
    FileInputStream fis2 = null;
    String fileName = "foo.bar";
    // String fileName = null;
    System.out.println(  "main: Starting " + Demo1.class.getName()
                       + " with file name = " + fileName);
    // get file input stream 1
    try {
      fis1 = f1(fileName);
    }
    catch (FileNotFoundException ex)
    {
      System.out.println("main: Oops, FileNotFoundException caught");
    }
    catch (Exception ex)
    {
      System.out.println("main: Oops, genreal exception caught");
    }
    // get file input stream 2
    fis2 = f2(fileName);
    System.out.println("main: " + Demo1.class.getName() + " ended");
  }
}

Compile and run the Demo1 class will generate output as follows (assuming that the file foo.bar does not exist):
main: Starting Demo1 with file name = foo.bar
main: Oops, FileNotFoundException caught
f2: Oops, FileNotFoundException caught
f2: finally block
f2: Returning from f2
main: Demo1 ended
The example program tries to create two file input streams. Therefore two methods f1and f2 are implemented. First, the main program calls f1 method. Because the constructor of the FileInputStream throws a FileNotFoundException the method f1must be defined with the throws FileNotFoundException in the method definition. The thrown exception is not handled in the method but forwarded to the invoker. Note, that the system output before the return statement is never executed.

So the invoker, in our example the main program, must catch this exception. The method f1 is called in a try block. The following catch blocks catch either aFileNotFoundException or a general Exception. In our example, the exception is caught in the first catch block and the system output is generated. Since the exception in f1 is caught and handled, the execution of the program is not terminated.

Second, the example program creates another FileInputStream invoking the f2method. This method catches the FileNotFoundException, so this exception must not be forwarded to the invoker. The try ... catch statement is followed by a finallyblock. This block is always executed, regardless whether or not an exception occurs within the try block. This generates the system output in our example. Again, the exception is caught and the program executes, this generates the system output inf2 and main.

This was a straight forward example with caught exceptions. What happens with uncaught exceptions? Change the fileName assignment in the main method: Comment out the first assignment and activate the second String fileName = null; then compile and execute Demo1 again. The generated output is:
main: Starting Demo1 with file name = null
main: Oops, genreal exception caught
f2: finally block
java.lang.NullPointerException
java.io.FileInputStream Demo1.f2(java.lang.String)
void Demo1.main(java.lang.String[])
Exception in thread main
This time, we try to create two FileInputStream objects using null instead of a file name. Invoking f1 will generate a NullPointerException which is caught in the main program. Next f2 is called which could handle only the FileNotFoundException but not a NullPointerException. Nevertheless the finally block is executed and then the control returns to the main program. Because there is no try ... catch statement around the call to f2 and no matching catch block is found, the thread is terminated. Note, that f2 and main can not execute the system output statements any more.

Thursday, April 19, 2012

How to Track Changes in a Word 2007 Document For Dummies


                         How to Track Changes in a Word 2007 Document For Dummies




Hey People..!!.. this feature will help you when you are preparing for requirements for your project in a team of 3 or 4 as it will track the changes made by the particular user.