You are on page 1of 12

6/26/13

JSP /Servlet(Advanced Java) Interview Questions and Answers Set-2 | searchcrone.com

Home

Arrange Mock interviews

New Interviews This Week

Top Interview Questions OF Week

Mock Interviews

Written Test

Interview

Fresher FAQ'S

Program ing

Online Test

Resum es

Experienced

Job Help

Search Placement Papers ::

Search Your Jobs :: Search

Search By Company

Jobs via Location


All Jobs | IT Jobs | Gov t Jobs | Bank Jobs | BPO Jobs | Interns/Trainings Program

JSP PDF

How to JSP

Java Download PDF

Interview Tips

JSP /Servlet(Advanced Java) Interview Questions and Answers Set-2


Artifactory - Binary Repo
Jfrog.com/ Powerful Continuous Integration Repository! Get a Free 30 Day Trial

JSP /Servlet(Advanced Java) Interview Question Answers Set-1

This is set-2 for Advanced Java Interview Questio better solutions.Read these JSP/Servlet interview questions for your sake in interviews. Q.what is the difference between forward and send Redirect?

Ans: Both requestDispatcher.forward () and response.sendRedirect () is used to redirect to new url.Forward is an internal redirection of

oaded and initialized, with the serv ice m ethod of each instance effectiv ely sy nchronized. You can ty pically control the num ber of instances (N) that are instantiated for all serv lets im plem enting del is not recom m ended for norm al use. Thereis are m any pitfalls, including the exam ple abov e of not to use < %! %> . You should try really hard to m ake themRedirect thread-safe the old fashioned way : intact. send Redirect normally an external redirection of being userable request outside the web container. send sends response

request within the web container to a new URL without the knowledge of the user (browser). The request object and the http headers re

header

the browser with the new URL. The browser sends the request to the new URL with fresh http headers. send Redirect is slower than forw because it involves extra server call. Q.Can I create XML pages using JSP technology? Ans: Yes, the JSP specification does support creation of XML documents. For simple XML generation, the XML tags may be included a

m plicit object. Note: You m ust alway s use a relativ e URL as the v alue for the errorPage attribute.

browser v ersions.

template portions of the JSP page. Dynamic generation of XML tags occurs through bean components or custom tags that generate XM Q.what are Directives?

Ans: Directives are instructions that are processed by the JSP engine when the page is compiled to a servlet. Directives are used to set p instructions, insert data from external files, and specify custom tag libraries. Q.what are the different types of directives available in JSP? Ans: The following are the different types of directives: a. include directive : used to include a file and merges the content of the file with the current page b. page directive : used to define page specific attributes like scripting language, error page, buffer, thread safety, etc c. taglib : used to declare a custom tag library which is used in the page. Q.what are JSP actions?

Ans: JSP actions are executed when a JSP page is requested. Actions are inserted in the jsp page using XML syntax to control the behav Java plugin. Some of the available actions are as follows: <jsp: include> include a file at the time the page is requested. <jsp: useBean> find or instantiate a JavaBean.
www.searchcrone.com/2011/08/jsp-servletadvanced-java-interview-questions-and-answers-set-2 1/12

servlet engine. Using action, we can dynamically insert a file, reuse bean components, forward the user to another page, or generate HTM

6/26/13

JSP /Servlet(Advanced Java) Interview Questions and Answers Set-2 | searchcrone.com

<jsp: setProperty> set the property of a JavaBean. <jsp: getProperty> insert the property of a JavaBean into the output. <jsp: forward> forward the requester to a new page.
e Headers> < Body > som e output (like testing y our v ariables.) Before y ou indicate that the file is ov er (and before the size of the page can be setted up in the header), y ou try to send a redirect status. It s

ntent-ty pe= text/htm l or text/xm l or plain-text or im age/jpg, etc.) When y ou try to send a redirect status (Num ber is line_status_4 02 ), y our HTTP serv er cannot send it right now if it hasnt

<jsp: plugin> generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin. Q.what are Script lets?

Ans: Script lets are blocks of programming language code (usually java) embedded within a JSP page. Scriptlet code is inserted into the generated from the page. Scriptlet code is defined between <% and %> Q.what are Decalarations? Ans: Declarations are similar to variable declarations in Java. Variables are defined for subsequent use in expressions or script lets. Q.How to declare instance or global variables in jsp?

Ans: Instance variables should be declared inside the declaration part. The variables declared with JSP declaration element will be shar

his to be effectiv e, y ou need to to append the session ID for each and ev ery link that is part of y our serv let response. Adding the session ID to a link is greatly sim plified by m eans of of a couple of m ethods: requests the jsp page. the session ID will be persisted as a cookie. Consider the following exam ple, in which two JSP files, say hello1 .jsp and hello2 .jsp, interact with each other. Basically , we create a new session within 2 .jsp; if cookies are disabled, the session ID is autom atically appended to the URL, allowing hello2 .jsp to still retriev e the session object. Try this exam ple first with cookies enabled. Then disable cookie

Q.what are Expressions? Ans: Expressions are variables or constants that are inserted into the data returned by the web server. Q.what is meant by implicit objects? And what are they?

Ans: Implicit objects are those objects which are available by default. These objects are instances of classes defined by the JSP specifica objects could be used within the jsp page without being declared. The following are the implicit jsp objects: 1. application 2. Page 3. Request 4. Response 5. Session 6. Exception 7. Out 8. Config 9. Page Context Q.How do I use Java Beans components (beans) from a JSP page?

v er, y ou should be able to pass any of the im plicit JSP v ariables as param eters to the m ethods y ou declare. For exam ple:

Ans: The JSP specification includes standard tags for bean use and manipulation. The <jsp: useBean> tag creates an instance of a speci getProperty> tags let you manipulate properties of a specific bean. Q.what is the difference between <jsp: include> and <%@include :> Ans: Both are used to insert files into a JSP page. <%@include :> is a directive which statically inserts the file at the time the JSP page is translated into a servlet. <jsp: include> is an action which dynamically inserts the file at the time the page is requested. Q.How is Java Server Pages different from Active Server Pages? Ans: JSP is a community driven specification whereas ASP is a similar proprietary technology from Microsoft. In JSP, the dynamic par
www.searchcrone.com/2011/08/jsp-servletadvanced-java-interview-questions-and-answers-set-2 2/12

JavaBean class. If the instance already exists, it is retrieved. Otherwise, a new instance of the bean is created. The <jsp: setProperty> an

6/26/13

JSP /Servlet(Advanced Java) Interview Questions and Answers Set-2 | searchcrone.com

in Java, not Visual Basic or other MS-specific language. JSP is portable to other operating systems and non-Microsoft Web servers whe not possible with ASP Q.Cant JavaScript be used to generate dynamic content rather than JSP?

Ans: JavaScript can be used to generate dynamic content on the client browser. But it can handle only handles situations where the dyn information is based on the clients environment. It will not able to harness server side information directly. Q.How can I get to print the stacktrace for an exception occuring within my JSP page? By printing out the exceptions stack trace, you can usually diagonse a problem better when debugging JSP pages. By looking at a stack stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The followi demonstrates how you can print a stacktrace from within a JSP error page: <%@ page isErrorPage=true %> <% out.println( ); PrintWriter pw = response.getWriter(); exception.printStackTrace(pw); after the session has been created. For exam ple: out.println( ); %> Q.How do you pass an InitParameter to a JSP?

programmer should be able to discern which method threw the exception and which method called that method. However, you cannot p

The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in mu the console. <%@ page import=java.util.* %> <%! ServletConfig cfg =null; public void jspInit(){ ServletConfig cfg=getServletConfig(); for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) { String name=(String)e.nextElement(); String value = cfg.getInitParameter(name); System.out.println(name+=+value); } }
www.searchcrone.com/2011/08/jsp-servletadvanced-java-interview-questions-and-answers-set-2 3/12

same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and print

6/26/13

JSP /Servlet(Advanced Java) Interview Questions and Answers Set-2 | searchcrone.com

%> Q.How can my JSP page communicate with an EJB Session Bean? The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean: <%@ page import=javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account %> <%! //declare a global reference to an instance of the home interface of the session bean AccountHome accHome=null; public void jspInit() { //obtain an instance of the home interface InitialContext cntxt = new InitialContext( ); Object ref= cntxt.lookup(java:comp/env/ejb/AccountEJB); accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class); } %> <% //instantiate the session bean Account acct = accHome.create(); //invoke the remote methods acct.doWhatever(); // etc etc %> Q.Is JSP technology extensible? Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries. Q.How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?

You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive < isThreadSafe=false %> within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin

memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized

, which is of tyyour pe JspWriter. You will hav e to use a PrintWriter object instead. The following snippet dem onstrates%>tag how y ou can a stacktrace within a JSP error tag, page: then JSP engine. More importantly, avoid using the <%! DECLARE forprint variables. Iffrom you do use this

you should set isThr

true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadM

not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try
www.searchcrone.com/2011/08/jsp-servletadvanced-java-interview-questions-and-answers-set-2 4/12

6/26/13

JSP /Servlet(Advanced Java) Interview Questions and Answers Set-2 | searchcrone.com

hard to make them thread-safe the old fashioned way: by making them thread-safe Q.How does JSP handle run-time exceptions?

You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error pro page. For example: <%@ page errorPage=error.jsp %>

redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if y

indicate that it is an error-processing page, via the directive: <%@ page isErrorPage=true %> Throwable object describing the except attribute. Q.How do I prevent the output of my JSP or Servlet pages from being cached by the browser?

be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorP

You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You the statements to take care of some of the older browser versions. <% response.setHeader(Cache-Control,no-store); //HTTP 1.1 response.setHeader(Pragma,no-cache); //HTTP 1.0 response.setDateHeader (Expires, 0); //prevents caching at the proxy server %> Q.How do I use comments within a JSP page? You can use JSP-style comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments a visible at the client. For example: <% the scriptlet is now commented out <% out.println(Hello World); %> %> You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:

Java Jobs for Freshers


www.careerbuilder.co.in/Java_Jobs The Worlds No.1 Speedy Job Portal. Apply to Jobs Faster. Post Now!

<! 2004 >

Of course, you can also use comments supported

JSP scripting language within your scriptlets. Fo

assuming Java is the scripting language, you can <% //some comment /** yet another comments
www.searchcrone.com/2011/08/jsp-servletadvanced-java-interview-questions-and-answers-set-2 5/12

6/26/13

JSP /Servlet(Advanced Java) Interview Questions and Answers Set-2 | searchcrone.com

**/ %>

Response has already been commited error. What does it mean? This error show only when you try to redirect a page after you alread

written something in your page. This happens because HTTP specification force the header to be set up before the lay out of the page ca

shown (to make sure of how it should be displayed, content-type=text/html or text/xml or plain-text or image/jpg, etc.) When y

send a redirect status (Number is line_status_402), your HTTP server cannot send it right now if it hasnt finished to set up the header

starter to set up the header, there are no problems, but if it s already begin to set up the header, then your HTTP server expects these h

be finished setting up and it cannot be the case if the stream of the page is not over In this last case its like you have a file started with be setted up in the header), you try to send a redirect status. It s simply impossible due to the specification of HTTP 1.0 and 1.1 Q.How do I use a scriptlet to initialize a newly instantiated bean?

Tag><Some Headers><Body>some output (like testing your variables.) Before you indicate that the file is over (and before the size of th

A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified b restricted to using those alone. use of a JSP expression within the jsp:setProperty action. <jsp:useBean id=foo > <jsp:setProperty name=foo property=today value=<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>/ > <% scriptlets calling bean setter methods go here %> </jsp:useBean > Q.How can I enable session tracking for JSP pages if the browser has disabled cookies?

instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are

The following example shows the today property of the Foo bean initialized to the current date when it is instantiated. Note that here,

We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not suppo

or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID wi

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 o

servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associat

session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL a

Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is re interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then t

unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and h

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 se

display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled

session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cooki to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting. hello1.jsp <%@ page session=true %> <%
www.searchcrone.com/2011/08/jsp-servletadvanced-java-interview-questions-and-answers-set-2 6/12

Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. D

6/26/13

JSP /Servlet(Advanced Java) Interview Questions and Answers Set-2 | searchcrone.com

Integer num = new Integer(100); session.putValue(num,num); String url =response.encodeURL(hello2.jsp); %> <a href=<%=url%>>hello2.jsp</a> hello2.jsp <%@ page session=true %> <% Integer i= (Integer )session.getValue(num); out.println(Num value in session is +i.intValue()); Q.How can I declare methods within my JSP page?

You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you

within JSP scriptlets and expressions. Do note that you do not have direct access to any of the JSP implicit objects like request, respons declare. For example: <%! public String whereFrom(HttpServletRequest req) { HttpSession ses = req.getSession(); return req.getRemoteHost(); } %> <% out.print(Hi there, I see that you are coming in from ); %> <%= whereFrom(request) %> Another Example file1.jsp: <%@page contentType=text/html%>
www.searchcrone.com/2011/08/jsp-servletadvanced-java-interview-questions-and-answers-set-2 7/12

and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the meth

6/26/13

JSP /Servlet(Advanced Java) Interview Questions and Answers Set-2 | searchcrone.com

<%! public void test(JspWriter writer) throws IOException{ writer.println(Hello!); } %> file2.jsp <%@include file=file1.jsp%> <html> <body> <%test(out);% > </body> </html> Q.Is there a way I can set the inactivity lease period on a per-session basis?

Typically, a default inactivity lease period for all sessions is set within your JSP engine admin screen or associated properties file. Howe JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis. This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created. For example: <% session.setMaxInactiveInterval(300); %> would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds. Q.How can I set a cookie and delete a cookie from within a JSP page? A cookie, mycookie, can be deleted using the following scriptlet: <% //creating a cookie Cookie mycookie = new Cookie(aName,aValue); response.addCookie(mycookie); //delete a cookie Cookie killMyCookie = new Cookie(mycookie, null); killMyCookie.setMaxAge(0);
www.searchcrone.com/2011/08/jsp-servletadvanced-java-interview-questions-and-answers-set-2 8/12

6/26/13

JSP /Servlet(Advanced Java) Interview Questions and Answers Set-2 | searchcrone.com

killMyCookie.setPath(/); response.addCookie(killMyCookie); %> Q.How does a servlet communicate with a JSP page?

The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is t

into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing public void doPost (HttpServletRequest request, HttpServletResponse response) { try { govi.FormBean f = new govi.FormBean(); String id = request.getParameter(id); f.setName(request.getParameter(name));; f.setAddr(request.getParameter(addr));; f.setAge(request.getParameter(age));; //use the id to compute //additional bean properties like info //maybe perform a db query, etc. // . . . f.setPersonalizationInfo(info); request.setAttribute(fBean,f); getServletConfig().getServletContext().getRequestDispatcher (/jsp/Bean1.jsp).forward(request, response); } catch (Exception ex) { ... } } The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action. jsp:useBean id=fBean scope=request / jsp:getProperty name=fBean property=name
www.searchcrone.com/2011/08/jsp-servletadvanced-java-interview-questions-and-answers-set-2 9/12

6/26/13

JSP /Servlet(Advanced Java) Interview Questions and Answers Set-2 | searchcrone.com

/ jsp:getProperty name=fBean property=addr / jsp:getProperty name=fBean property=age / jsp:getProperty name=fBean property=personalizationInfo / Q.How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default?

One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP eng doing so, you may lose out on any advanced optimization that may be provided by the JSP engine. In any case, your new superclass has the contract with the JSP engine by: Servlet interface are declared final Additionally, your servlet superclass also needs to do the following: The service() method has to invoke the _jspService() method The init() method has to invoke the jspInit() method The destroy() method has to invoke jspDestroy() If any of the above conditions are not satisfied, the JSP engine may throw a translation error. Once the superclass has been developed, you can have your JSP extend it as follows: <%@ page extends=packageName.ServletName %>

Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the metho

Q.How can I prevent the word null from appearing in my HTML input text fields when I populate them with a resu that has null values? You could make a simple wrapper function, like <%! String blanknull(String s) { return (s == null) ? : s; } %> then use it inside your JSP form, like <input type=text name=shoesize value=<%=blanknull(shoesize)% > > Q.How can I get to print the stacktrace for an exception occuring within my JSP page? By printing out the exceptions stack trace, you can usually diagonse a problem better when debugging JSP pages. By looking at a stack stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The followi demonstrates how you can print a stacktrace from within a JSP error page: <%@ page isErrorPage=true %> <%
www.searchcrone.com/2011/08/jsp-servletadvanced-java-interview-questions-and-answers-set-2 10/12

programmer should be able to discern which method threw the exception and which method called that method. However, you cannot p

6/26/13

JSP /Servlet(Advanced Java) Interview Questions and Answers Set-2 | searchcrone.com

out.println( ); PrintWriter pw = response.getWriter(); exception.printStackTrace(pw); out.println( ); %> Q.How do you pass an InitParameter to a JSP?

The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in mu the console. <%@ page import=java.util.* %> <%! ServletConfig cfg =null; public void jspInit(){ ServletConfig cfg=getServletConfig(); for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements()) { String name=(String)e.nextElement(); String value = cfg.getInitParameter(name); System.out.println(name+=+value); } } %> Q.How can my JSP page communicate with an EJB Session Bean? The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean: <%@ page import=javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account %> <%! //declare a global reference to an instance of the home interface of the session bean AccountHome accHome=null; public void jspInit() { //obtain an instance of the home interface
www.searchcrone.com/2011/08/jsp-servletadvanced-java-interview-questions-and-answers-set-2 11/12

same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and print

6/26/13

JSP /Servlet(Advanced Java) Interview Questions and Answers Set-2 | searchcrone.com

InitialContext cntxt = new InitialContext( ); Object ref= cntxt.lookup(java:comp/env/ejb/AccountEJB); accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class); } %> <% //instantiate the session bean Account acct = accHome.create(); //invoke the remote methods acct.doWhatever(); // etc etc %>
3 0 0 1168

This entry was posted in Freshers, Java Programing, Java Questions & Answers, Technical Interviews Questions and tagged JSP /Servlet(Advanced Java) Interview Questions and Answers Set-2. Bookmark the

Job Vacancies.
Quikr.com/Jobs Find 1000's of Jobs in your City. Connect with Employers. Apply Now!

2011 by SearchC rone Info Solutions. All Rights Reserved | About us | C ontact us

www.searchcrone.com/2011/08/jsp-servletadvanced-java-interview-questions-and-answers-set-2

12/12

You might also like