Sunteți pe pagina 1din 20

JSP Interview Questions and Answers :

1. What is a JSP and what is it used for? Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page. 2. What is difference between custom JSP tags and beans? Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components: 1. The tag handler class that defines the tag\'s behavior 2. The tag library descriptor file that maps the XML element names to the tag implementations 3. the JSP file that uses the tag library When the first two components are done, you can use the tag by using taglib directive: Then you are ready to use the tags you defined. Let's say the tag prefix is test: MyJSPTag or JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags to declare a bean and use to set value of the bean class and use to get value of the bean class. Custom tags and beans accomplish the same goals encapsulating complex behavior into simple and accessible forms. There are several differences: Custom tags can manipulate JSP content; beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans. Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page. Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions. 3. What are the two kinds of comments in JSP and what's the difference between them. <% JSP Comment %> <! HTML Comment > 4. What is JSP technology?

Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a serverside scripting language. 5. What is JSP page? A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content. 6. What are the implicit objects? Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: request response pageContext session application out config page exception 7. How many JSP scripting elements and what are they? There are three scripting language elements: declarations scriptlets expressions 8. Why are JSP pages the preferred API for creating a web-based client program? Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs. 9. Is JSP technology extensible? YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries. 10. Can we use the constructor, instead of init(), to initialize servlet?

Yes , of course you can use the constructor instead of init(). Theres nothing to stop you. But you shouldnt. The original reason for init() was that ancient versions of Java couldnt dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you wont have access to a ServletConfig or ServletContext. 11. How can a servlet refresh automatically if some new data has entered the database? You can use a client-side Refresh or Server Push. 12. The code in a finally clause will never fail to execute, right? Using System.exit(1); in try block will not allow finally code to execute. 13. How many messaging models do JMS provide for and what are they? JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing. 14. What information is needed to create a TCP Socket? The Local Systems IP Address and Port Number. And the Remote Systems IPAddress and Port Number. 15. What Class.forName will do while loading drivers? It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS. 16. How to Retrieve Warnings? SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object SQLWarning warning = stmt.getWarnings(); if (warning != null) { while (warning != null) { System.out.println("Message: " + warning.getMessage());

System.out.println("SQLState: " + warning.getSQLState()); System.out.print("Vendor error code: "); System.out.println(warning.getErrorCode()); warning = warning.getNextWarning(); } } 17. How many JSP scripting elements are there and what are they? There are three scripting language elements: declarations, scriptlets, expressions. 18. In the Servlet 2.4 specification SingleThreadModel has been deprecated, why? Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level. 19. What are stored procedures? How is it useful? A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements everytime a query is run. Each database has its own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of dbs support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases. 20. How do I include static files within a JSP page? Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request. 21. Why does JComponent have add() and remove() methods but Component does not? because JComponent is a subclass of Container, and can contain other components and jcomponents. How can I implement a thread-safe JSP page? - You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" % > within your JSP page.

22. How can I enable session tracking for JSP pages if the browser has disabled cookies? We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting. hello1.jsp hello2.jsp hello2.jsp <% Integer i= (Integer )session.getValue("num"); out.println("Num value in session is "+i.intValue());

JSP AND SERVLETS


1. What is the difference between JSP and Servlets ? JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc.

2. What is difference between custom JSP tags and beans? Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components: the tag handler class that defines the tags behavior ,the tag library descriptor file that maps the XML element names to the tag implementations and the JSP file that uses the tag library JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags Custom tags and beans accomplish the same goals encapsulating complex behavior into simple and accessible forms. There are several differences: Custom tags can manipulate JSP content; beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans. Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page. Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions. 3. What are the different ways for session tracking? Cookies, URL rewriting, HttpSession, Hidden form fields 4. What mechanisms are used by a Servlet Container to maintain session information? Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information 5. Difference between GET and POST In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL. In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is more secure. 6. What is session? The session is an object used by a servlet to track a users interaction with a Web application across multiple HTTP requests. The session is stored on the server. 7. What is servlet mapping? The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets.

8. What is servlet context ? The servlet context is an object that contains a information about the Web application and container. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. 9. What is a servlet ? servlet is a java program that runs inside a web container. 10. Can we use the constructor, instead of init(), to initialize servlet? Yes. But you will not get the servlet specific things from constructor. The original reason for init() was that ancient versions of Java couldnt dynamically invoke constructors with arguments, so there was no way to give the constructor a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you wont have access to a ServletConfig or ServletContext. 12. How many JSP scripting elements are there and what are they? There are three scripting language elements: declarations, scriptlets, expressions. 13. How do I include static files within a JSP page? Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. 14. How can I implement a thread-safe JSP page? You can make your JSPs thread-safe adding the directive <%@ page isThreadSafe="false" % > within your JSP page. 15. What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()? In request.getRequestDispatcher(path) in order to create it we need to give the relative path of the resource. But in resourcecontext.getRequestDispatcher(path) in order to create it we need to give the absolute path of the resource. 16. What are the lifecycle of JSP? When presented with JSP page the JSP engine does the following 7 phases. Page translation: -page is parsed, and a java file which is a servlet is created. Page compilation: page is compiled into a class file Page loading : This class file is loaded. Create an instance :- Instance of servlet is created jspInit() method is called _jspService is called to handle service calls

_jspDestroy is called to destroy it when the servlet is not required. 17. What are context initialization parameters? Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application. 18. What is a Expression? Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed. This will be included in the service method of the generated servlet. 19. What is a Declaration? It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language used in the JSP file. This will be included in the declaration section of the generated servlet. 20. What is a Scriptlet? A scriptlet can contain any number of language statements, variable or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a . Generally a scriptlet can contain any java code that are valid inside a normal java method. This will become the part of generated servlets service method.

JAVA
JAVA Interview Questions & Answers :
1. What is the difference between Abstract class and Interface? A class implementing an interface must implement all of the methods defined in the interface while a class extending an abstract class need not implement any of the methods defined in the abstract class. Additionally a class extending an abstract class can implement an infinite number of it's own methods. 2. what is a transient variable? A variable that won't be allowed for object serialisation. so that the state of the value will always be defaulted after the deserialisation. For example a variable x's value is set to 9, it's default value is '0' say, when the object has been serialized having x's value 9, after deserialisation will be defaulted to '0' . 3. WHAT IS THE DIFFERENCE BETWEEN MULTI-THREADING AND MULTI-

PROCESSING? Multitasking is running several processes at a time. Multi threading runs several threads of a single process at a time.The priority levels of threads are from 1-10.Normal priority comes to 5. Multi threading is normal in any window environment otherwise the screen would stuck everytime you clicked on something until that execution was accomplished. 4. Does Java has pointer?. Java do have pointers; but not similar to the one that C has. In Java Pointers are in the form of Objects/references. Also the pointers in Java are not explicit like C. probably JVM internally uses pointers. Every object is a reference to a location making it a pointer...these pointers cannot be directly manipulated. Differences between the C & Java pointers: 1) A pointer is a variable that holds the memory address of data. In Java there are only references which do not hold any memory address but which are indices in a table and this table has then the real pointer to the data. 2) Pointer Arithmetic is not possible with Java pointers. 5. Can we make construtor STATIC? You cannot make a constructor as STATIC because if you use any access modifier in constructor compiler interprets it to be a method and expects a return type this class will not compile until you specify a return type since compiler thinks it to be a normal method not a constructor. 6. what is the differance between equals() method and ==? The operator checks to see if two objects are exactly the same object. Two strings may be different objects but have the same value.The .equals() method to compare strings for equality(content). 7. Is it true the JAVA is realy a plateform indepandent? No java is not platform independent it looses platform-independeny in 3 cases 1. while using threads 2. while using AWT components 3. while using native methods also one more question we know java looses platform independency while running as threads but we also knew that in java every application run as a thread then how can we consider java as a platform-independent language? 8. when does JIT plays its role. Does JIT come along with jdk? If so then what is role

of nterpreter? JIT - Just In Time compiler is embedded in the web browser like the internet explorer! The interpreter for Java which executes the Byte Codes is the JVM - Java Virtual Machine. JIT is also a part of the JVM and it compiles bytecodes into real-time code when needed as on demand. The entire Java program is not compiled into an executable code at once coz there need to performed various run-time checks. However JIT compiles code as and when needed during execution. To put it simply the JIT compiler is faster than the JVM. JIT comes into play when you execute applications written in JavaScript. 9. Does a class inherit the constructors of its superclass ? A super default constructor is automatically available to the subclass when the subclass object is created. but if you want to access super class parameterized constructors we must use super keyword. 10. Advantage of servlets over JSP ? Both the technologies are server side technologies each of them has its own advantages.The basic advantages of Servlet over JSP are 1) The execution time required in the servlet is lesser than because jsp is derived from the servlet so when client makes a request first time to the specific jsp file the container will perfom three steps a)Translation b)Compilation c)construction where as in the servlet these steps are not required except construction. 2) A servlet can handle different dynamic pages where as the jsp can handle only on dynamic page. 11. can we use final keyword before constructor? generally final keyword is used when we want not to override the class or not to over ride the subclass methods but Constructor have the methods or datamembers to activated when we instantiaed so final keyword should not use before constructor.... and also it does not take final k'word before constructor . 12. What is final class ? A class which cannot be inherited by any other class is called a final class. 13. What is the difference between static variable and instance variable? Static variable the field is allocated when the class is created. It belongs to the class and not any object of the class. It is class variable Instace variable the field is allocated when the class is instanciated to the class is called instance variable or non-static variable 14. Does garbage collection guarantee that a program will not run out of memory? Garbage collection does not guarantee that a program will not run out of memory. It

ispossible for programs to use up memory resources faster than they are garbage collected.It is also possible for programs to create objects that are not subject to garbage collection. 15. What is the significance of null interface in Java? we say this as an mark up interface we use this interface because it shouid be recognized by Java Virtual Machine in order to make the objects selected for network enable and serialized and select particular objects to be participated in Client/server Communication. 16. Why is the main() method declared public and static? Main is declared public because JVM accesses this method. it is declared static because it is instance independent. 17. How does multithreading take place on a computer with a single CPU . The operating system's task scheduler allocates execution time to multiple tasks. Byquickly switching between executing tasks, it creates the impression that tasks executesequentially. 18. What is the Advantage of using sendRedirect than RequestDispatcher ? sendRedirect used with response object where Requestdiapacther used with request object. 19. What are some alternatives to inheritance? Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass). 20. What is the difference between Java and J2EE? Is J2EE advanced version of Java? Java is a object-oriented programming language which is platform neutral. That is unlike C or C++ java programs, Java can be run on any operating system with its JVM. J2EE is just a specification for server side programs. That is to support internet applications, distributed and uses component model. So that Enterprises use this server side technology in their distributed business. Since J2EE is just a server side specification, anybody can implement the specification but again using Java. Hence today we have Custom implemented J2EE servers from Oracle, SUN, IBM and so on.. 21. What is the difference between Classpath and Import? Difference b/w the Classpath and Import:

Classpath: Class path is a system variable. It is a collection of files in the directories.Normally classpath will be used by Java interpreter to exucute the class files(.class). Import :Import is a keyword. It is used to getting the required files into the program without writing the hard code. eg. import java.io.*; 22. Why Java is not 100 % pure OOPS? A pure Object Orientad Language is which implements All the OOP concepts. Java doesn't support Multiple Inheritance & Operator loading thats why "Java is not 100% pure Object Language". 23. What is Anonymous class,Singleton Class and Assertions? Anonymous: instantiating the class without object name. Singleton: it can instantiated by only one time. Assertions: to show warning to the user.

JSP SERVLETS
Question: What do you understand by JSP Actions? Answer: JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters. There are six JSP Actions:
<jsp:include/> <jsp:forward/> <jsp:plugin/> <jsp:usebean/> <jsp:setProperty/> <jsp:getProperty/>

Question: What is the difference between <jsp:include page = ... > and <%@ include file = ... >?. Answer: Both the tag includes the information from one page in another. The differences are as follows:
<jsp:include page = ... >: This is like a function call from one jsp to another jsp. It is executed ( the included page is executed and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful to for modularizing the web application. If the included file changed then the new content will be included in the output. <%@ include file = ... >: In this case the content of the included file is textually embedded in the page that have <%@ include file=".."> directive. In this case in the included file changes, the changed content will not included in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.

Question: What is the difference between <jsp:forward page = ... > and response.sendRedirect(url),?. Answer: The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file. sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The response.sendRedirect kills the session variables. Question: Identify the advantages of JSP over Servlet. a) Embedding of Java code in HTML pages b) Platform independence c) Creation of database-driven Web applications d) Server-side programming capabilities Answer :- Embedding of Java code in HTML pages Write the following code for a JSP page: <%@ page language = "java" %> <HTML> <HEAD><TITLE>RESULT PAGE</TITLE></HEAD> <BODY> <%

PrintWriter print = request.getWriter(); print.println("Welcome"); %> </BODY> </HTML> Suppose you access this JSP file, Find out your answer. a) A blank page will be displayed. b) A page with the text Welcome is displayed c) An exception will be thrown because the implicit out object is not used d) An exception will be thrown because PrintWriter can be used in servlets only Answer :- A page with the text Welcome is displayed Question: What are implicit Objects available to the JSP Page? Answer: Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application. The JSP implicit objects are: Description The context for the JSP page's servlet and any Web application javax.servlet.ServletContext components contained in the same application. config javax.servlet.ServletConfig Initialization information for the JSP page's servlet. exception java.lang.Throwable Accessible only from an error page. out javax.servlet.jsp.JspWriter The output stream. The instance of the JSP page's servlet processing the current page java.lang.Object request. Not typically used by JSP page authors. The context for the JSP page. Provides a single API to pageContext javax.servlet.jsp.PageContext manage the various scoped attributes. Subtype of request The request triggering the execution of the JSP page. javax.servlet.ServletRequest Subtype of The response to be returned to the client. Not typically used response javax.servlet.ServletResponse by JSP page authors. session javax.servlet.http.HttpSession The session object for the client. Variable Class

Question: What are all the different scope values for the <jsp:useBean> tag? Answer:<jsp:useBean> tag is used to use any java object in the jsp page. Here are the scope values for <jsp:useBean> tag: a) page b) request c) session and

d) application Question: What is JSP Output Comments? Answer: JSP Output Comments are the comments that can be viewed in the HTML source file. Example: <!-- This file displays the user login screen --> and <!-- This page was loaded on <%= (new java.util.Date()).toLocaleString() %> --> Question: What is expression in JSP? Answer: Expression tag is used to insert Java values directly into the output. Syntax for the Expression tag is: <%= expression %> An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. The following expression tag displays time on the output: <%=new java.util.Date()%> Question: What types of comments are available in the JSP? Answer: There are two types of comments are allowed in the JSP. These are hidden and output comments. A hidden comments does not appear in the generated output in the html, while output comments appear in the generated output. Example of hidden comment: <%-- This is hidden comment --%> Example of output comment: <!-- This is output comment --> Question: What is JSP declaration? Answer: JSP Decleratives are the JSP tag used to declare variables. Declaratives are enclosed in the <%! %> tag and ends in semi-colon. You declare variables and functions in the declaration tag and can use anywhere in the JSP. Here is the example of declaratives:
<%@page contentType="text/html" %> <html> <body> <%! int cnt=0; private int getCount(){

//increment cnt and return the value cnt++; return cnt; } %> <p>Values of Cnt are:</p> <p><%=getCount()%></p> </body> </html>

Question: What is JSP Scriptlet? Answer: JSP Scriptlet is jsp tag which is used to enclose java code in the JSP pages. Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet executes every time the JSP is invoked. Example: <% //java codes String userName=null; userName=request.getParameter("userName"); %> Question: What are the life-cycle methods of JSP? Answer: Life-cycle methods of the JSP are: a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance. b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann't be overridden. c) jspDestroy(): The container calls this when its instance is about to destroyed. The jspInit() and jspDestroy() methods can be overridden within a JSP page.

Question: What is the difference between JSP and Servlets ? JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc. Question: What are the different ways for session tracking?

Cookies, URL rewriting, HttpSession, Hidden form fields Question: What mechanisms are used by a Servlet Container to maintain session information? Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information Question: Difference between GET and POST In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL. In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is more secure. Question: What is session? The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests. The session is stored on the server. Question: What is servlet mapping? The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets. Question: What is servlet context ? The servlet context is an object that contains a information about the Web application and container. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. Question: What is a servlet ? servlet is a java program that runs inside a web container. Question: Can we use the constructor, instead of init(), to initialize servlet? Yes. But you will not get the servlet specific things from constructor. The original reason for init() was that ancient versions of Java couldnt dynamically invoke constructors with arguments, so there was no way to give the constructor a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you wont have access to a ServletConfig or ServletContext. Question: What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()? In request.getRequestDispatcher(path) in order to create it we need to give the relative path of the resource. But in resourcecontext.getRequestDispatcher(path) in order to create it we need to give the absolute path of the resource. Question: What are context initialization parameters?

Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application. Question: What is a Expression? Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed. This will be included in the service method of the generated servlet. Question: What is a Declaration? It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language used in the JSP file. This will be included in the declaration section of the generated servlet. Question: What is a Scriptlet? A scriptlet can contain any number of language statements, variable or expressions that are valid in the page scripting language. Within scriptlet tags, you can declare variables to use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects or any object declared with a . Generally a scriptlet can contain any java code that are valid inside a normal java method. This will become the part of generated servlet's service method. Question: What are the implicit objects? Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects are: request, response, pageContext, session, application, out, config, page, exception Question: What's the difference between forward and sendRedirect? forward is server side redirect and sendRedirect is client side redirect. When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container And then returns to the calling method. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward. Client can disable sendRedirect. Question: What's the Servlet Interface? The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.

Question: What are two different types of Servlets ? GenericServlet and HttpServlet. HttpServlet is used to implement HTTP protocol, where as Generic servlet can implement any protocol. Question: What is the life cycle of servlet? Each servlet has the same life cycle: first, the server loads and initializes the servlet by calling the init method. This init() method will be executed only once during the life time of a servlet. Then when a client makes a request, it executes the service method. finally it executes the destroy() method when server removes the servlet. Question: Can we call destroy() method on servlets from service method ? Yes. Question: What is the need of super.init (config) in servlets ? Then only we will be able to access the ServletConfig from our servlet. If there is no ServletConfig our servlet will not have any servlet nature. Question: What is the difference between GenericServlet and HttpServlet? GenericServlet supports any protocol. HttpServlet supports only HTTP protocol. By extending GenericServlet we can write a servlet that supports our own custom protocol or any other protocol. Question: Can we write a constructor for servlet ? Yes. But the container will always call the default constructor only. If default constructor is not present , the container will throw an exception. Question: What are the parameters for service method ? ServletRequest and ServletResponse Question: What are cookies ? Cookies are small textual information that are stored on client computer. Cookies are used for session tracking. Question: What is the meaning of response has already been committed error? You will get this error only when you try to redirect a page after you already have flushed the output buffer. This happens because HTTP specification force the header to be set up before the lay out of the page can be shown. When you try to send a redirect status, your HTTP server cannot send it right now if it hasn't finished to set up the header. Simply it is giving the error due to the specification of HTTP 1.0 and 1.1 Question: How do I use a scriptlet to initialize a newly instantiated bean? A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated (Only at the time of instantiation.) Typically, the body will contain scriptlets or jsp:setProperty tags to initialize

the newly instantiated bean, although you are not restricted to using those alone. Question: What is the difference between ServletContext and ServletConfig? The ServletConfig gives the information about the servlet initialization parameters. The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method. The ServletContext gives information about the container. The ServletContext interface provides information to servlets regarding the environment in which they are running. It also provides standard way for servlets to write events to a log file. Question: How can a servlet refresh automatically? We can use a client-side Refresh or Server Push Question: What is Server side push? Server Side push is useful when data needs to change regularly on the clients application or browser, without intervention from client. The mechanism used is, when client first connects to Server, then Server keeps the TCP/IP connection open. Question: What is client side refresh? The standard HTTP protocols ways of refreshing the page, which is normally supported by all browsers.
<META HTTP-EQuestion:UIV="Refresh" CONTENT="5; URL=/servlet/MyServlet">

This will refresh the page in the browser automatically and loads the new data every 5 seconds. Servlet Interview Questions & Answers Part 2 Servlet Interview Questions & Answers Part 3 JSP Interview Questions & Answers

S-ar putea să vă placă și