Direct your cloning future. Cloning · PDF fileDirect your cloning future. TOPO
Java FAQ and Cloning
Transcript of Java FAQ and Cloning
-
8/6/2019 Java FAQ and Cloning
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 referencevariables, 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 voidincrease() { i++;
http://www.roseindia.net/java/java-get-example/java-binary-tree-insert.shtmlhttp://www.roseindia.net/java/java-get-example/index.shtmlhttp://www.roseindia.net/java/java-get-example/javascript-array-map.shtml -
8/6/2019 Java FAQ and Cloning
2/29
}
public String toString() { return Integer.toString(i); }}
public class ClonemethodExample {
public static voidmain(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 voidmain(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;
-
8/6/2019 Java FAQ and Cloning
3/29
public Employee(String lastName, String firstName) { this.lastName = lastName; this.firstName = firstName; }
public String getLastName() { return this.lastName; }
public voidsetLastName(String lastName) {
this.lastName = lastName; }
public String getFirstName() { return this.firstName; }
public voidsetFirstName(String firstName) {
this.firstName = firstName; }
public Double getSalary() { return this.salary; }
public voidsetSalary(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.lastName + ", " + this.salary + "]"; }}
JDBC and JSP interview questions and answersByadmin| October 9, 2004
1. What is the query used to display all tables names in SQL Server (Query analyzer)?
2. 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
http://www.techinterviews.com/author/admin/http://www.techinterviews.com/author/admin/http://www.techinterviews.com/author/admin/ -
8/6/2019 Java FAQ and Cloning
4/29
JDBC-ODBC Bridge Driver
Native API Partly Java Driver
Network protocol Driver
JDBC Net pure Java Driver
4. Can we implement an interface in a JSP?- No
5.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.
7. How to pass information from JSP to included JSP?- Using tag.8. What is the difference between directive include and jsp include?- : Used to include
static resources during translation time. JSP include: Used to include dynamic content or static content
during runtime.
9. What is the difference between RequestDispatcher and sendRedirect?- RequestDispatcher:
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. Cookie mycook = new Cookie("name","value");
13. response.addCookie(mycook);
14. Cookie killmycook = new Cookie("mycook","value");
15. killmycook.setMaxAge(0);
16. killmycook.setPath("/");
17. 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.
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
The 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
-
8/6/2019 Java FAQ and Cloning
5/29
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. Itprovides 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
http://www.go4expert.com/forums/member.php?u=146http://www.go4expert.com/forums/member.php?u=146 -
8/6/2019 Java FAQ and Cloning
6/29
Author
Recent Articles
Similar Articles
pradeep( Team Leader )
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 thatyou 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{
privateint i;
public MyInt(int ii){ i = ii; }
publicvoid increment(){ i++; }
http://my.go4expert.com/pradeep/http://%20copytoclipboard%28%27%3Ca%20href%3Dhttp//www.go4expert.com/forums/showthread.php?t=5424%3EObject%20Cloning%20in%20Java%3C/A%3E%27)http://%20addtofavorites%28%29/http://www.go4expert.com/forums/subscription.php?do=addsubscription&t=5424http://www.go4expert.com/forums/sendmessage.php?do=sendtofriend&t=5424http://www.go4expert.com/forums/printthread.php?t=5424http://my.go4expert.com/pradeep/ -
8/6/2019 Java FAQ and Cloning
7/29
publicString toString(){
returnInteger.toString(i); } }
publicclass Test{
publicstaticvoid main(String[] args){
ArrayList al = newArrayList();for(int i = 0; i < 10; i++ )
al.add(new 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 implementsCloneable {
... publicObject clone() {
http://www.google.com/search?q=allinurl%3AString+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3AInteger+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3AArrayList+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3AArrayList+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3AArrayList+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3AArrayList+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3AIterator+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3ACloneable+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3AObject+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3AString+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3AInteger+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3AArrayList+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3AArrayList+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3AArrayList+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3AArrayList+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3AIterator+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3ACloneable+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3AObject+java.sun.com&bntl=1 -
8/6/2019 Java FAQ and Cloning
8/29
try { return super.clone(); } catch(CloneNotSupportedException e ) { returnnull; } }...
}
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.
http://www.google.com/search?q=allinurl%3ACloneNotSupportedException+java.sun.com&bntl=1http://www.google.com/search?q=allinurl%3ACloneNotSupportedException+java.sun.com&bntl=1 -
8/6/2019 Java FAQ and Cloning
9/29
Servlet concepts
Q:What's the difference between applets and servlets?
A: There are many fundamentaldifferences
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.
-
8/6/2019 Java FAQ and Cloning
10/29
Actions:Follow-up,clarify orcorrect this
answer. Submit anew question.
Q:Do we open servlet classes directly instead of HTML?
A: Servlets are used to deliver HTML toWeb 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 ofprint() statements on
aPrintWriter. The method that handles
simple Web requests is called doGet(), as
below.
publicfinalvoid doGet(HttpServletRequest
request,HttpServletResponse
response) throws IOException {
PrintWriter output =response.getWriter();
http://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=appletservlethttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=appletservlethttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=appletservlethttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=appletservlethttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=appletservlethttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=appletservlethttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=appletservlethttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=appletservlethttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=appletservlethttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=appletservlethttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=appletservlet -
8/6/2019 Java FAQ and Cloning
11/29
output.println("");output.println(" ");output.println(" ");
// Other HTML output
output.flush();output.close();
}
Actions:Follow-up,clarify orcorrect this
answer. Submit anew 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 runtimesystem. Their package names are
prefixedjavax 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 orcorrect this
answer. Submit anew question.
http://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servlethtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servlethtmlhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servlethtmlhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servlethtmlhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servlethtmlhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servlethtmlhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servlethtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=javaxservlethttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=javaxservlethttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=javaxservlethttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=javaxservlethttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=javaxservlethttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=javaxservlethttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=javaxservlethttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servlethtmlhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servlethtmlhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servlethtmlhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servlethtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=javaxservlethttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=javaxservlethttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=javaxservlethttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=javaxservlet -
8/6/2019 Java FAQ and Cloning
12/29
Q:How does the JVM execute a servlet compared with aregular Java class?
A: Servlets are standard Java classes andare 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 servletclasses 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 whichto handle it.
Actions:Follow-up,clarify orcorrect this
answer. Submit anew question.
Q:How can I tell when a servlet is instantiated?A: A servlet must be instantiated before itis 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
http://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletexecutionhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletexecutionhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletexecutionhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletexecutionhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletexecutionhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletexecutionhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletexecutionhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletexecutionhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletexecutionhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletexecutionhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletexecution -
8/6/2019 Java FAQ and Cloning
13/29
method is called after the servlet container
has instantiated the servlet before it is
brought into service.
Actions:Follow-up,clarify orcorrect thisanswer. Submit anew question.
Servlet programming
Q:How can I write a servlet using Javascript?A: Java servlets is a server side technologythat 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 orcorrect this
answer. Submit anew question.
Q:Can I use a normal class to handle my requests?A: Servlets are normal Java classes, theycompile and run just like any other class. All
that is required is that servlets implement
thejavax.servlet.Servlet interface. Usually,
http://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletinstantiatedhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletinstantiatedhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletinstantiatedhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletinstantiatedhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletinstantiatedhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletinstantiatedhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletinstantiatedhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=javascriptservlethttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=javascriptservlethttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=javascriptservlethttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=javascriptservlethttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=javascriptservlethttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=javascriptservlethttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=javascriptservlethttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletinstantiatedhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletinstantiatedhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletinstantiatedhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletinstantiatedhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=javascriptservlethttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=javascriptservlethttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=javascriptservlethttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=javascriptservlet -
8/6/2019 Java FAQ and Cloning
14/29
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 orcorrect this
answer. Submit anew 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 classesavailable 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 orcorrect this
answer. Submit anew question.
Q:Can I use a constructor in my servlet?A: A servlet is a normal Java class, sowhen there are no custom constructors,
there is an implicit default constructor with
http://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/java/servlets/faq/AlternateHandler.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=alternatehandlerhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=alternatehandlerhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=alternatehandlerhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=alternatehandlerhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=alternatehandlerhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=alternatehandlerhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=alternatehandlerhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletcompositionhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletcompositionhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletcompositionhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletcompositionhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletcompositionhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletcompositionhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletcompositionhttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/java/servlets/faq/AlternateHandler.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=alternatehandlerhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=alternatehandlerhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=alternatehandlerhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=alternatehandlerhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletcompositionhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletcompositionhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletcompositionhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletcomposition -
8/6/2019 Java FAQ and Cloning
15/29
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 non-
default 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 orcorrect this
answer. Submit anew question.
Q:What happens if I add a main method to my servlet?A: It is possible to write a main method fora servlet, but it will not be called by the
servlet container, it is not part of the servlet
lifecycle process. If you invoke your servlet
through the main method using
thejava command it will behave exactly like
a standard Java class, it cannot operate as aWeb 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 orcorrect this
answer. Submit anew question.
Servlet start up
Q:Can one JSP or Servlet extend another Servlet or JSPA: It is possible and necessary for servletsto extend other classes, they are standard
http://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/java/servlets/faq/ServletConstructor.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletconstructorhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletconstructorhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletconstructorhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletconstructorhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletconstructorhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletconstructorhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletconstructorhttp://www.codestyle.org/java/servlets/faq-Lifecycle.shtmlhttp://www.codestyle.org/java/servlets/faq-Lifecycle.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletmainhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletmainhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletmainhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletmainhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletmainhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletmainhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletmainhttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/java/servlets/faq/ServletConstructor.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletconstructorhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletconstructorhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletconstructorhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletconstructorhttp://www.codestyle.org/java/servlets/faq-Lifecycle.shtmlhttp://www.codestyle.org/java/servlets/faq-Lifecycle.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletmainhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletmainhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletmainhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletmain -
8/6/2019 Java FAQ and Cloning
16/29
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 orcorrect this
answer. Submit anew question.
Q:How do I compile a servlet?A: To compile a servlet, you will need tohave 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 andjavax.servlet.htt
p.
premium content omitted
Access all premium content
for $50: sign-up now.
How do I compile a servlet?
http://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletextendshttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletextendshttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletextendshttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletextendshttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletextendshttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletextendshttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletextendshttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/java/servlets/faq/ServletCompile.shtmlhttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletextendshttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletextendshttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletextendshttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletextendshttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/java/servlets/faq/ServletCompile.shtml -
8/6/2019 Java FAQ and Cloning
17/29
Actions:Follow-up,clarify or correct this
answer. Submit anew question.
Q:Why won't my servlet compile?
A: All those "cannot find symbol" errormessages mean that you do not have the
Java servletJAR file on your compiler's
classpath, so it cannot find the servlet class
files. The servletJAR 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 orcorrect this
answer. Submit anew question.
Q:Where is the servlet stored and where does it run?A: When you create a servlet, the codemust 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,
http://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletcompilehttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletcompilehttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletcompilehttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletcompilehttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletcompilehttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletcompilehttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/java/servlets/faq/ServletClasspath.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletclasspathhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletclasspathhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletclasspathhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletclasspathhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletclasspathhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletclasspathhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletclasspathhttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletcompilehttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletcompilehttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletcompilehttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletcompilehttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/java/servlets/faq/ServletClasspath.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletclasspathhttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletclasspathhttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletclasspathhttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletclasspath -
8/6/2019 Java FAQ and Cloning
18/29
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 orcorrect this
answer. Submit anew question.
Q:What are the basic steps to run a servlet?A: The key steps in creating and running aservlet 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. Write and compile your servlet,
e.g. ExampleServlet.class
2. Create a Web application directory
structure under the webapp directory of your
servlet container (or use an existing one),
e.g.
3. {webapps-
http://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletresidehttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletresidehttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletresidehttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletresidehttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletresidehttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletresidehttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletresidehttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletresidehttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletresidehttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletresidehttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletreside -
8/6/2019 Java FAQ and Cloning
19/29
dir}/example
4. {webapps-dir}/example/WEB-INF
5. {webapps-dir}/example/WEB-INF/classes
6. Place your servlet class file in
the WEB-INF/classes directory for your
application, e.g.
7. {webapps-dir}/example/WEB-
INF/classes/ExampleServlet.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. {webapps-dir}/example/WEB-
-
8/6/2019 Java FAQ and Cloning
20/29
INF/web.xml
10. Start the servlet container.
Actions:Follow-up,clarify orcorrect this
answer. Submit anew question.
Q:What is the difference between JAR and WAR files?A: There is no difference between thebinary form ofJAR and WAR files, they both
use zip compression provided by
thejar tool. You can create a WAR file by
navigating to the root directory of your Web
application and typing thejar 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 orcorrect this
answer. Submit anew question.
Servlet techniques
Q:Can I access a servlet from a stand alone client?A: It is certainly possible to access aservlet 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,
http://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=stepsservlethttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=stepsservlethttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=stepsservlethttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=stepsservlethttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=stepsservlethttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=stepsservlethttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=stepsservlethttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/java/servlets/faq/JarWarCompare.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=jarwarcomparehttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=jarwarcomparehttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=jarwarcomparehttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=jarwarcomparehttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=jarwarcomparehttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=jarwarcomparehttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=jarwarcomparehttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=stepsservlethttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=stepsservlethttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=stepsservlethttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=stepsservlethttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/java/servlets/faq/JarWarCompare.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=jarwarcomparehttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=jarwarcomparehttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=jarwarcomparehttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=jarwarcompare -
8/6/2019 Java FAQ and Cloning
21/29
servlets do not run in their own right, they
are not server applications.
Actions:Follow-up,clarify orcorrect this
answer. Submit anew question.
Q:How can I write a servlet client for testing?A: Marty Hall provides the source code fora 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 orcorrect this
answer. Submit anew 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 orcorrect this
answer. Submit anew question.
Q:How can I redirect a request to another URL?
http://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletclienthttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletclienthttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletclienthttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletclienthttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletclienthttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletclienthttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletclienthttp://volume1.coreservlets.com/archive/Chapter3.htmlhttp://volume1.coreservlets.com/archive/Chapter3.htmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=webclienthttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=webclienthttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=webclienthttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=webclienthttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=webclienthttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=webclienthttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=webclienthttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/java/servlets/faq/UrlRewriting.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=urlrewritinghttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=urlrewritinghttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=urlrewritinghttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=urlrewritinghttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=urlrewritinghttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=urlrewritinghttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=urlrewritinghttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletclienthttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletclienthttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletclienthttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletclienthttp://volume1.coreservlets.com/archive/Chapter3.htmlhttp://volume1.coreservlets.com/archive/Chapter3.htmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=webclienthttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=webclienthttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=webclienthttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=webclienthttp://www.codestyle.org/codestyle/premium/index.shtmlhttp://www.codestyle.org/java/servlets/faq/UrlRewriting.shtmlhttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=urlrewritinghttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=urlrewritinghttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=urlrewritinghttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=urlrewriting -
8/6/2019 Java FAQ and Cloning
22/29
A: The standard servlet method to redirectone HTTP request to another is
theHttpServletResponsesendRedirect(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 RequestDispatcherforward() method,
which sends the forwarded content in the
original HTTP response stream.
Actions:Follow-up,clarify orcorrect this
answer. Submit anew question.
Q:What's the difference between forward, include andredirection?
A: The RequestDispatcherforward() and include() 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
http://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletredirecthttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletredirecthttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletredirecthttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletredirecthttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletredirecthttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletredirecthttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletredirecthttp://www.codestyle.org/faq/help/index.shtml?action=follow-up&referrer=Java+servlets%20FAQ&id=servletredirecthttp://www.codestyle.org/faq/help/index.shtml?action=clarify&referrer=Java+servlets%20FAQ&id=servletredirecthttp://www.codestyle.org/faq/help/index.shtml?action=correction&referrer=Java+servlets%20FAQ&id=servletredirecthttp://www.codestyle.org/faq/help/index.shtml?action=new&referrer=Java+servlets%20FAQ&id=servletredirect -
8/6/2019 Java FAQ and Cloning
23/29
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 ofservlets, 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 ofHttpServlet 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 doXXXmethods 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
http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/ -
8/6/2019 Java FAQ and Cloning
24/29
by a servlet, although it's more common to extend a protocol-specific subclass such
as HttpServlet.
GenericServlet 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.
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 usedto 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 encryptionwhich 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
-
8/6/2019 Java FAQ and Cloning
25/29
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.
2. 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.
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.
4. 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.
5. SecureServlets 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 ofServlet?
Answer: The interfacejavax.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 cometo 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.
http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/servlet-interview-questions-2.shtmlhttp://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/http://www.roseindia.net/interviewquestions/servlet/servlet-interview-questions-2.shtml -
8/6/2019 Java FAQ and Cloning
26/29
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 classand provides an framework
for handling the HTTP protocol. So, HttpServlet only supports HTTP and
HTTPS protocol.
8. Question: What are the directory Structure of Web Application?Answer:Web component follows the standard directory structure defined in the J2EEspecification.
Directory Structure of Web Component
/
index.htm, JSP, Images etc.. Web-inf
web.xml
classes
servlet classes
lib
jar files
9. Question: What is ServletContext?
Answer:ServletContext is an Interface that defines a set of methods that a servlet usesto 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.)
10. Question: What is meant by Pre-initialization of Servlet?
Answer:When servlet container is loaded, all the servlets defined in the web.xml filedoes 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, theservlet is loaded when context is loaded. You can specify 1
in between the tag.
11. Question: What mechanisms are used by a Servlet Containerto
maintain session information?
http://www.roseindia.net/interviewquestions/servlet/servlet-interview-questions-2.shtmlhttp://www.roseindia.net/interviewquestions/servlet/servlet-interview-questions-2.shtmlhttp://www.roseindia.net/interviewquestions/servlet/servlet-interview-questions-2.shtmlhttp://www.roseindia.net/interviewquestions/servlet/servlet-interview-questions-2.shtml -
8/6/2019 Java FAQ and Cloning
27/29
Answer:Servlet Container uses Cookies, URL rewriting, and HTTPS protocolinformation to maintain the session.
12. Question: What do you understand by servlet mapping?
Answer:Servlet mapping defines an association between a URL pattern and a servlet.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.
13. Question: What must be implemented by all Servlets?
Answer:The Servlet Interface must be implemented by all servlets.
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.
15. Question: What are the uses of Servlets?
Answer: * Servlets are used to process the client request.* 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 caneasily forward request.
16. 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.17. 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 time-
out value for session variable is 20 minutes, which can be changed as per the
requirement.
18. Question: What is Session ID?
Answer: A session ID is an unique identification string usually a long, random andalpha-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.
19. 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
-
8/6/2019 Java FAQ and Cloning
28/29
maintain the state to track the series of requests from the same user across some
period of time.
20. Question: What are different types of Session Tracking?
Answer: Mechanism for Session Tracking are:
a) Cookiesb) URL rewriting
c) Hidden form fields
d) SSL Sessions
21. Question: What is HTTPSession Class?
Answer: HttpSession Class provides a way to identify a user across across multiple
request. The servlet containeruses 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 requestfrom 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. Sessionis required if you are developing shoppingcart application or in any e-commerce
application.
23. 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.
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.
25. 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.26. 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.
http://www.roseindia.net/interviewquestions/servlet/session-tracking.shtmlhttp://www.roseindia.net/interviewquestions/servlet/session-tracking.shtmlhttp://www.roseindia.net/interviewquestions/servlet/session-tracking.shtmlhttp://www.roseindia.net/interviewquestions/servlet/session-tracking.shtmlhttp://www.roseindia.net/interviewquestions/servlet/session-tracking.shtmlhttp://www.roseindia.net/interviewquestions/servlet/session-tracking.shtmlhttp://www.roseindia.net/interviewquestions/servlet/session-tracking.shtmlhttp://www.roseindia.net/interviewquestions/servlet/session-tracking.shtml -
8/6/2019 Java FAQ and Cloning
29/29
27. 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);
28. 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();