Вы находитесь на странице: 1из 29

Java clone method example

Java clone method is used to present the duplication of object in the Java programming language. The Java objects are manipulated through reference variables, we don't have any way to copy an object in java. The clone ( ) is a constructor that call the clone method of super class in order to get the copy of object.
Understand with Example

In this Tutorial we want to describe you a code that help you in understanding a ClonemethodExample.For this we have a primitive class int,The int constructor return you the object of this class by passing the int value a assigned to i. The increase method ( ) return you increment value of i. The String toString ( ) return you the string representation of integer. The ClonemethodExample class include main method that create array list object 'list'. The for loop run the loop and the list object call the add method ( ) and add integer variable to it. Finally the println print the list. 1)Clone ( ) method - This method return you the typecasting that needed to assign the generic object to a reference of my class object type. The for loop include the list object that call the iterator method and return the Iterator object. The Iterator object e iterate the value from the list and call the next method( ). 2)next ( )method - This method return you the next element in the list if it is present in list Finally the println print the list of clone value. ClonemethodExample.java
import java.util.*; class Int { private int i; public Int(int a) { i = a; } public void increase() { i++;

} public String toString() { return Integer.toString(i); } } public class ClonemethodExample { public static void main(String[] args) { ArrayList list = new ArrayList(); for (int i = 0; i < 5; i++) { list.add(new Int(i)); } System.out.println("List is : " + list); ArrayList list1 = (ArrayList) list.clone(); for (Iterator e = list1.iterator(); e.hasNext();) { ((Int) e.next()).increase(); } System.out.println("List after cloning is: " + list);

} }

Output of the program


List is : [0, 1, 2, 3, 4] List after cloning is: [1, 2, 3, 4, 5]

A Cloning Example

public class MainClass { public static void main(String[] args) { Employee emp1 = new Employee("M", "A"); emp1.setSalary(40000.0); Employee emp2 = (Employee) emp1.clone(); emp1.setLastName("Smith"); System.out.println(emp1); System.out.println(emp2); } } class Employee { private String lastName; private String firstName; private Double salary;

public Employee(String lastName, String firstName) { this.lastName = lastName; this.firstName = firstName; } public String getLastName() { return this.lastName; } public void setLastName(String lastName) { } this.lastName = lastName;

public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public Double getSalary() { return this.salary; } public void setSalary(Double salary) { this.salary = salary; } public Object clone() { Employee emp; emp = new Employee(this.lastName, this.firstName); emp.setSalary(this.salary); return emp; } public String toString() { return this.getClass().getName() + "[" + this.firstName + " " + this.last Name + ", " + this.salary + "]"; } }

JDBC and JSP interview questions and answers


By admin | October 9, 2004

1.
2.

What is the query used to display all tables names in SQL Server (Query analyzer)?
select * from information_schema.tables

3. How many types of JDBC Drivers are present and what are they?- There are 4 types of JDBC
Drivers

4. 5.

JDBC-ODBC Bridge Driver Native API Partly Java Driver Network protocol Driver JDBC Net pure Java Driver Can we implement an interface in a JSP?- No What is the difference between ServletContext and PageContext?- ServletContext: Gives the

information about the container. PageContext: Gives the information about the Request

6. What is the difference in using request.getRequestDispatcher() and


context.getRequestDispatcher()?- request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource, context.getRequestDispatcher(path): In order to create it we need to give the absolutepath of the resource. How to pass information from JSP to included JSP?- Using <%jsp:param> tag. What is the difference between directive include and jsp include?- <%@ include>: Used to include static resources during translation time. JSP include: Used to include dynamic content or static content during runtime. What is the difference between RequestDispatcher and sendRedirect?- RequestDispatcher:

7. 8.

9.

server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects. 10. How does JSP handle runtime exceptions?- Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP. 11. How do you delete a Cookie within a JSP?
12. 13. 14. 15. 16. 17. Cookie mycook = new Cookie("name","value"); response.addCookie(mycook); Cookie killmycook = new Cookie("mycook","value"); killmycook.setMaxAge(0); killmycook.setPath("/"); killmycook.addCookie(killmycook);

18. How do I mix JSP and SSI #include?- If youre just including raw HTML, use the #include directive as
usual inside your .jsp file.
19. <!--#include file="data.inc"-->

But its a little trickier if you want the server to evaluate any JSP code thats inside the included file. If your data.inc file contains jsp code you will have to use
<%@ vinclude="data.inc" %>

The <!#include file="data.inc"> is used for including non-JSP files.

20. I made my class Cloneable but I still get Cant access protected method clone. Why?- Some of
the Java books imply that all you have to do in order to have your class support clone() is implement the Cloneable interface. Not so. Perhaps that was the intent at some point, but thats not the way it works

currently. As it stands, you have to implement your own public clone() method, even if it doesnt do anything special and just calls super.clone(). 21. Why is XML such an important development?- It removes two constraints which were holding back Web developments: dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for; the complexity of full SGML, whose syntax allows many powerful but hard-to-program options. XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for. 22. What is the fastest type of JDBC driver?- JDBC driver performance will depend on a number of issues: the quality of the driver code, the size of the driver code, the database server and its load, network topology, the number of times your request is translated to a different API. In general, all things being equal, you can assume that the more your request and response change hands, the slower it will be. This means that Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at least three translations versus two), and Type 4 drivers are the fastest (only one translation).

23. How do I find whether a parameter exists in the request object?


24. boolean hasFoo = !(request.getParameter("foo") == null 25. || request.getParameter("foo").equals(""));

or
boolean hasParameter = request.getParameterMap().contains(theParameter); //(which works in Servlet 2.3+)

26. How can I send user authentication information while makingURLConnection?- Youll want to
use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.

Object Cloning in Java


By pradeep

On 23rd July, 2007

Object Cloning in Java

ADVERTISEMENT

Author Recent Articles Similar Articles ( Team Leader )

pradeep

Yet to provide details about himself

All articles By pradeep Objects in Java are referred using reference types, and there is no direct way to copy the contents of an object into a new object. The assignment of one reference to another merely creates another reference to the same object. Therefore, a special clone() method exists for all reference types in order to provide a standard mechanism for an object to make a copy of itself. Here are the details you need to know about cloning Java objects.

Why create a local copy?


The most probable reason for creating a local copy of an object is because you plan to modify the object, and you don't want to modify the method caller's object. If you decide that you need a local copy, you can perform the operation by using the clone() method of the Object class. The clone() method is defined as protected, but you must redefine it as public in all subclasses that you might want to clone. For example, the standard library class ArrayList overrides clone(), so you can call clone() for ArrayList, like this:
Code: Java

import java.util.*; class MyInt { private int i; public MyInt(int ii) { i = ii; } public void increment() { i++; }

public String toString() { return Integer.toString(i); }

public class Test { public static void { ArrayList al = for(int i = 0; al.add(new

main(String[] args) new ArrayList(); i < 10; i++ ) MyInt(i));

ArrayList al1 = (ArrayList)al.clone(); // Increment all al1's elements: for(Iterator e = al1.iterator(); e.hasNext(); ) ((MyInt)e.next()).increment(); } }

The clone() method produces an Object, which must be recast to the proper type. This example shows how ArrayList's clone() method does not automatically try to clone each of the objects that the ArrayList contains -- the old ArrayList and the cloned ArrayList are aliased to the same objects. This is often called a shallow copy, since it's only copying the "surface" portion of an object. The actual object consists of this "surface," plus all the objects that the references are pointing to and all the objects those objects are pointing to, etc. This is often referred to as the "Web of objects." When you copy the entire mess, it is called a deep copy.

The Cloneable interface and deep copies


By default, classes in Java do not support cloning; the default implementation of the clone() method throws a CloneNotSupportedException. You should override implementation of the clone() method. Remember that you must make it public and, inside the method, your first action must be super.clone(). Classes that want to allow cloning must implement the marker interface Cloneable. Since the default implementation of Object.clone only performs a shallow copy, classes must also override clone to provide a custom implementation when a deep copy is desired. Basically, if you want to make objects of your class publicly cloneable, you need code like this:
Code: Java

class Test implements Cloneable { ... public Object clone() {

try

... }

return super.clone(); } catch( CloneNotSupportedException e ) { return null; } }

If you are happy with a protected clone, which just blindly copied the raw bits of the object, you don't need to redefine your own version. However, you will usually want a public one. (Note: You can't create a private or default scope clone; you can only increase the visibility when you override.)

Possible problems and a solution


Since the clone() method is protected, subclasses have to explicitly agree to be cloneable by overriding this protected method with a public method. All of the Collections classes do this. The subclass also has to implement Cloneable for the default cloning mechanism in Object.clone() to work. If you have an object that you know has a public clone() method, but you don't know the type of the object at compile time, you have problems. For instance, say x is declared as an Object. You can't just call x.clone() because Object.clone() is protected. If Cloneable defined a public clone() method, you could use ((Cloneable) x).clone(), but it doesn't. You either have to enumerate all the classes that you think x could be, or you have to resort to reflection. Another problem arises when you try deep copying of a complex object. You're assuming that the clone() method of all member object variables also does deep copy; this is too risky of an assumption. You must control the code in all classes, or you must know that all classes involved in deep copy operation do such a copy in the right way. One solution to these problems is to clone using serialization. Serialization is usually used to send objects off somewhere (such as into a file or over the network) so that somebody else can reconstruct them later. You can abuse serialization to immediately reconstruct the object yourself. If the object is serializable at all, the reconstruction should be a faithful copy. In normal uses of serialisation, the original object is nowhere near a faithful copy; it could be on the other side of the world at the far end of a network connection. You can be sure that changing the copy will have no effect on the original.

Servlet concepts

Q: What's the difference between applets and servlets? A: There are many fundamental
differences between Applet and Servlet classes, the Java API documentation for the two types will show you they have little in common. Applets are essentially graphical user interface (GUI) applications that run on the client side in a network environment, typically embedded in an HTML page. Applets are normally based on Abstract Windowing Toolkit components to maintain backward-compatibility with the widest range of browsers' Java implementations. The application classes are downloaded to the client and run in a Java Virtual Machine provided by the browser, in a restrictive security environment called a "sandbox". Servlets are used to dynamically generate HTTP responses and return HTML content to Web browsers on the server side. Servlets are often used to validate and process HTML form submissions and control a series of user interactions in what is known as a Web application. Servlets can be used to control all aspects of the request and response exchange between a Web browser and the server, called a servlet container.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Do we open servlet classes directly instead of HTML? A: Servlets are used to deliver HTML to
Web browsers, but they are not like static HTML documents. When you set up a servlet in a Web application it has a URL like a static HTML document, so you can link to it, bookmark it or send the URL by email, just as you would with an standard Web page. The main difference is that the HTML sent to the Web browser is composed dynamically by the servlet and its contents can be customised based on the details of the request sent by the Web browser. When you open a servlet URL the browser does not display content of the servlet class, but a dynamic HTML document created by the servlet. The servlet class is written as a standard Java class that extends the HttpServlet class. In its most basic form, the HTML output can be created by a series of print() statements on aPrintWriter. The method that handles simple Web requests is called doGet(), as below. public final void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter output = response.getWriter();

output.println("<html>"); output.println(" <head>"); output.println(" <title>"); // Other HTML output output.flush(); output.close(); }
Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: What part of the Java platform do servlets and JSP belong to? A: The servlet and JSP APIs are a standard
extension to the core Java API and runtime system. Their package names are prefixed javax to indicate they are standard extensions, but that means that they rely upon a code implementation provided by a specific vendor. For example, the Apache Tomcat project supplies its own implementation of the servlet and JSP API that is integrated with the servlet container. Developers must compile their code using the vendor's servlet package implementation by including it in the compiler's classpath. The servlet container includes the same package classes in its runtime system and feeds concrete instances of the servlet interface types to the servlet's lifecycle methods.
Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How does the JVM execute a servlet compared with a


regular Java class?

A: Servlets are standard Java classes and


are executed by the Java Virtual Machine in exactly the same way as any other. However, the environment or context in which servlets are executed is different. A servlet is not invoked directly through a main()method, the class is loaded and run by a servlet container. When you run a servlet container, it reads its configuration, identifies the servlet classes to make available, and uses the Java classloader system to load and run the servlets. When the servlets are first brought into service, the servlet container calls the servlet's init() method and passes the ServletConfig object as an argument. Whenever a request is made to the servlet, the container creates a new thread in which to handle it.
Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How can I tell when a servlet is instantiated? A: A servlet must be instantiated before it
is brought into service by the servlet container, so one way to check is to make a request to the servlet and check the response. If you need to check indirectly, you can override theinit(ServletConfig) method and add log(String) statements to it. This

method is called after the servlet container has instantiated the servlet before it is brought into service.
Actions: Follow-up, clarify or correct this answer. Submit a new question.

Servlet programming

Q: How can I write a servlet using Javascript? A: Java servlets is a server side technology
that delivers dynamic content to Web browsers and other clients. Javascript is also delivered by a Web server, but the code is only interpreted and executed after it has been downloaded by the Web browser. This means that it is not possible to write servlet code in Javascript. It is possible to include Javascript in the output of servlets and Java Server Pages, just like standard Web pages. It is also possible to dynamically generate Javascript using a servlet and use it as the source for a script tag, though this is only advisable in rare cases.
Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Can I use a normal class to handle my requests? A: Servlets are normal Java classes, they
compile and run just like any other class. All that is required is that servlets implement the javax.servlet.Servlet interface. Usually,

they extend a protocol-specific class such asjavax.servlet.http.HttpServlet.


premium content omitted

Access all premium content for $50: sign-up now. Can I use a normal class to handle my requests?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Can I include normal Java classes in servlets? A: Any Java class can be used in a Web
application, provided you make the classes available to the servlet container at runtime. The Java API classes can be used directly by adding import statements to your servlet class. Other supporting classes can also be imported, but these classes must be added to the classes or lib directory of your application. If you need to configure the supporting classes, this can be done with standard servlet configuration features using the ServletConfig and ServletContext object s available to the init(ServletConfig) method.
Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Can I use a constructor in my servlet? A: A servlet is a normal Java class, so


when there are no custom constructors, there is an implicit default constructor with

no arguments. Servlet containers typically use the Class.newInstance() method to load servlets, so you must be careful to add an explicit default constructor if you add nondefault constructors.
premium content omitted

Access all premium content for $50: sign-up now. Can I use a constructor in my servlet?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

A: It is possible to write a main method for


a servlet, but it will not be called by the

Q: What happens if I add a main method to my servlet?

servlet container, it is not part of the servlet lifecycle process. If you invoke your servlet through the main method using the java command it will behave exactly like a standard Java class, it cannot operate as a Web application in its own right and cannot be addressed using HTTP requests. Servlets must run in a servlet container to deliver Web applications as intended.
Actions: Follow-up, clarify or correct this answer. Submit a new question.

Servlet start up

Q: Can one JSP or Servlet extend another Servlet or JSP A: It is possible and necessary for servlets
to extend other classes, they are standard

Java classes in most respects. Most servlets extend the abstract HttpServlet class included in a servlet container's API implementation. This abstract class implements the generic Servlet interface with HTTP-specific methods and provides a minimal basis to extend and create your own servlet classes. If you need to develop complex behaviour across a set of servlets you can extend this hierarchy to create numerous servlet subclasses. The automatic source code generation and compilation scheme used to create JSP servlets means that extension of the JSP servlet class is more complex and should generally be avoided.
Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How do I compile a servlet? A: To compile a servlet, you will need to


have the Java Servlet API classes in your classpath. Most Java servlet containers come with a copy, it may be calledservlet.jar or something similar. The basic classes are in the packagesjavax.servlet and javax.servlet.htt p.
premium content omitted

Access all premium content for $50: sign-up now. How do I compile a servlet?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Why won't my servlet compile? A: All those "cannot find symbol" error
messages mean that you do not have the Java servlet JAR file on your compiler's classpath, so it cannot find the servlet class files. The servlet JAR file is normally distributed with your servlet container. For Apache Tomcat it is a file named {CATALINA_HOME}/common/lib/serv let-api.jar. Add this to your compiler classpath as follows.
premium content omitted

Access all premium content for $50: sign-up now. Why won't my servlet compile?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: Where is the servlet stored and where does it run? A: When you create a servlet, the code
must be installed in a servlet container which operates as an HTTP server application. In the a development environment the servlet container is often installed on a developer's own workstation, or a hardware server in the local network where it can be accessed privately for testing. In a production environment the servlet container is usually installed on a server that is accessible from the Internet,

but the Java software arrangement is basically the same. Servlet code is compiled to Java class byte code which is physically located on the server hardware with the servlet container. The servlet operates as an extension of the servlet container and its code is executed on the server. Web browsers operate as clients which connect to the servlet container, issue HTTP requests and receive HTTP responses from the servlet container, mostly in the form of HTML pages and other Web content. The servlet code is not downloaded or executed by the Web browser at all, it only receives standard Web content and renders it accordingly.
Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: What are the basic steps to run a servlet? A: The key steps in creating and running a
servlet are outlined below in the simplest form. There are different techniques that can be used to complete these stages, described in other FAQ answers.

1. 2.

Write and compile your servlet,

e.g. ExampleServlet.class Create a Web application directory

structure under the webapp directory of your servlet container (or use an existing one), e.g. 3. {w ebapps-

dir}/exa mple 4. {w ebappsdir}/exa mple/WE B-INF 5. {w ebappsdir}/exa mple/WE BINF/class es

6.

Place your servlet class file in

the WEB-INF/classes directory for your application, e.g. 7. {w ebappsdir}/exa mple/WE BINF/class es/Exam pleServl et.class

8.

Create a WEB-INF/web.xml file for

your application (or edit an existing one) and add servlet and servlet-mapping elements for your servlet, e.g. 9. {w ebappsdir}/exa mple/WE B-

INF/web. xml

10.

Start the servlet container.

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: What is the difference between JAR and WAR files? A: There is no difference between the
binary form of JAR and WAR files, they both use zip compression provided by the jar tool. You can create a WAR file by navigating to the root directory of your Web application and typing the jar command, as below.
premium content omitted

Access all premium content for $50: sign-up now. What is the difference between JAR and WAR files?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Servlet techniques

Q: Can I access a servlet from a stand alone client? A: It is certainly possible to access a
servlet that is hosted in a servlet container. AnyHTTP client should be able to connect to a properly configured servlet container and make requests to a servlet. However,

servlets do not run in their own right, they are not server applications.
Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How can I write a servlet client for testing? A: Marty Hall provides the source code for
a basic HTTP client in his book Core Servlets and Java Server Pages. The source code for chapter 3 is available online. Look for WebClient.java and supporting classes. This application allows you to manually input the host, request path, HTTP header values and view the headers returned by a Web application.
Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: What is URL-rewriting? A: URL-rewriting is a way of maintaining a


session between an HTTP client and a servlet container which does not use cookies. Rather than exchange a session ID in a cookie, the servlet container includes it in the hyperlink URLs it generates for servlets and JSP.
premium content omitted

Access all premium content for $50: sign-up now. What is URL-rewriting?

Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: How can I redirect a request to another URL?

A: The standard servlet method to redirect


one HTTP request to another is theHttpServletResponse sendRedirect(Strin g) method. The String argument is the URL for the address you want to direct people to. String otherURL = "http://example.com/otherPage.jsp"; response.sendRedirect(otherURL);

When you call this method it will issue an HTTP redirect request to the browser, commit the servlet response and end the HTTP exchange. The browser should automatically create a new HTTP request for the given URL that will be entirely separate from the original request. HTTP redirection is different from the RequestDispatcher forward() method, which sends the forwarded content in the original HTTP response stream.
Actions: Follow-up, clarify or correct this answer. Submit a new question.

Q: What's the difference between forward, include and A: The RequestDispatcher forward() and in
clude() methods are mechanisms that are internal to a servlet container and do not affect the public URL of a Web resource. When you call the forward() method on a RequestDispatcher with a JSPpath, the servlet container returns the JSP content on

redirection?

the original servlet's URL; this effectively becomes the response of the servlet itself.

Collection of large number of Servlet Interview Questions. These questions are frequently asked in the Java Interviews. Question: What is a Servlet? Answer: Java Servlets are server side components that provides a powerful mechanism for developing server side of web application. Earlier CGI was developed to provide server side capabilities to the web applications. Although CGI played a major role in the explosion of the Internet, its performance, scalability and reusability issues make it less than optimal solutions. Java Servlets changes all that. Built from ground up using Sun'swrite once run anywhere technology java servlets provide excellent framework for server side processing. Question: What are the types of Servlet? Answer: There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides some http specific functionality linke doGet and doPost methods. Question: What are the differences between HttpServlet and Generic Servlets? Answer: HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:
doGet,

if the servlet supports HTTP GET requests doPost, for HTTP POST requests doPut, for HTTP PUT requests doDelete, for HTTP DELETE requests init and destroy, to manage resources that are held for the life of the servlet getServletInfo, which the servlet uses to provide information about itself

There's almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above). Likewise, there's almost no reason to override the doOptions and doTrace methods. GenericServlet defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extendHttpServlet instead.
GenericServlet

implements

the Servlet and ServletConfig interfaces. GenericServlet may be directly extended

by a servlet, although it's more common to extend a protocol-specific subclass such as HttpServlet. makes writing servlets easier. It provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet also implements the log method, declared in the ServletContextinterface.
GenericServlet

To write a generic servlet, you need only override the abstract service method. Question: Differentiate between Servlet and Applet. Answer: 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 not GUI interface in case of Servlets. Question: Differentiate between doGet and doPost method? Answer: doGet is used when there is are requirement of sending data appended to a query string in the URL. The doGet models the GET method of Http and it is used to retrieve the info on the client from some server as a request to it. The doGet cannot be used to send too much info appended as a query stream. GET puts the form values into the URL string. GET is limited to about 256 characters (usually a browser limitation) and creates really ugly URLs. POST allows you to have extremely dense forms and pass that to the server without clutter or limitation in size. e.g. you obviously can't send a file from the client to the server via GET. POST has no limit on the amount of data you can send and because the data does not show up on the URL you can send passwords. But this does not mean that POST is truly secure. For real security you have to look into encryption which is an entirely different topic Question: What are methods of HttpServlet? Answer: The methods of HttpServlet class are : * doGet() is used to handle the GET, conditional GET, and HEAD requests * doPost() is used to handle POST requests * doPut() is used to handle PUT requests * doDelete() is used to handle DELETE requests * doOptions() is used to handle the OPTIONS requests and * doTrace() is used to handle the TRACE requests Question: What are the advantages of Servlets over CGI programs? Answer: Question: What are methods of HttpServlet? Answer: Java Servlets have a number of advantages over CGI and other API's. They are:
1.

Platform Independence Java Servlets are 100% pure Java, so it is platform independence. It can run on

2.

3.

4.

5.

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 webserver (if Apache Serve is installed) without modification or compilation of code. Platform independency of servlets provide a great advantages over alternatives of servlets. Performance Due to interpreted nature of java, programs written in java are slow. But the java servlets runs very fast. These are due to the way servlets run on web server. For any program initialization takes significant amount of time. But in case of servlets initialization takes place very first time it receives a request and remains in memory till times out or server shut downs. After servlet is loaded, to handle a new request it simply creates a new thread and runs service method of servlet. In comparison to traditional CGI scripts which creates a new process to serve the request. This intuitive method of servlets could be use to develop high speed data driven web sites. 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. Safety Java provides a very good safety features like memory management, exception handling etc. Servlets inherits all these features and emerged as a very powerful web server extension. Secure Servlets are server side components, so it inherits the security provided by the web server. Servlets are also benefited with JavaSecurity Manager. 6. Question: What are the lifecycle methods of Servlet? Answer: 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. Initialization is covered in Initializing a Servlet.

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. 7. Question: What are the type of protocols supported by HttpServlet? Answer: It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol. Question: What are the directory Structure of Web Application? Answer: Web component follows the standard directory structure defined in the J2EE
8.

specification.

Directory Structure of Web Component /


index.htm, JSP, Images etc.. Web-inf
web.xml

classes
servlet classes

lib
jar files

Question: What is ServletContext? Answer: ServletContext is an Interface that defines a set of methods that a servlet uses
9.

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. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)

Question: What is meant by Pre-initialization of Servlet? Answer: When servlet container is loaded, all the servlets defined in the web.xml file
10.

does not initialized by default. But the container receives the request it loads the 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 case of Pre-initialization, the servlet is loaded when context is loaded. You can specify <load-on-startup>1</load-

on-startup> in between the <servlet></servlet> tag. Question: What mechanisms are used by a Servlet Container to maintain session information?
11.

Answer: Servlet Container uses Cookies, URL rewriting, and HTTPS protocol
information to maintain the session.

Question: What do you understand by servlet mapping? Answer: Servlet mapping defines an association between a URL pattern and a servlet.
12.

You can use one servlet to process a number of url pattern (request pattern). For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.

Question: What must be implemented by all Servlets? Answer: The Servlet Interface must be implemented by all servlets.
13. 14.

Question: What are the differences between Servlet and Applet? Answer: Servlets are server side components that runs on the Servlet container.
Applets are client side components and runs on the web browsers. Servlets have no GUI interface.

Question: What are the uses of Servlets? Answer: * Servlets are used to process the client request.
15.

* 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.

Question: What are the objects that are received when a servlets accepts call from client? Answer: 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.
16.

Question: What is a Session? Answer: 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 request from that user. Every user has a separate session and separate session variable is associated with that session. In case of web applications the default timeout value for session variable is 20 minutes, which can be changed as per the requirement.
17.

Question: What is Session ID? Answer: 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.
18.

Question: What is Session Tracking? Answer: 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
19.

maintain the state to track the series of requests from the same user across some period of time. Question: What are different types of Session Tracking? Answer: Mechanism for Session Tracking are: a) Cookies b) URL rewriting c) Hidden form fields d) SSL Sessions
20.

Question: What is HTTPSession Class? Answer: 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. 22. Question: Why do u use Session Tracking in HttpServlet? Answer: In HttpServlet you can use Session Tracking to track the user state. Session is required if you are developing shoppingcart application or in any e-commerce application.
21.

Question: What are the advantage of Cookies over URL rewriting? Answer: Sessions tracking using Cookies are more secure and fast. Session tracking using Cookies can also be used with other mechanism of Session Tracking like url rewriting.
23.

24. Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies may work or not. In url rewriting requites large data transfer from and to the server. So, it leads to network traffic and access may be become slow. Question: What is session hijacking? Answer: 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.
25.

Question: What is Session Migration? Answer: 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.
26.

Question: How to track a user session in Servlets? Answer: 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);
27.

Question: How you can destroy the session in Servlet? Answer: You can call invalidate() method on the session object to destroy the session. e.g. session.invalidate();
28.

Вам также может понравиться