JSP Servlet Interview Questions and Answers

 

JSP Servlet Interview Questions and Answers

Servlets are very important topic of Java EE and all of the web applications framework such as Spring and Struts are built on top of it. This makes servlet interview questions a hot topic in interviews.

Here a list of 50 servlet interview questions and answers to help you tackle most of the interview questions related to servlets and web applications in java.

1. In web.xml file   <load-on-startup>1</load-on-startup> is defined between <servlet></servlet> tag what does it means.

whenever we request for any servlet the servlet container will initialize the servlet and load it which is defined in our config file called web.xml by default it will not initialize when our context is loaded .defining like this <load-on-startup>1</load-on-startup> is also known as pre initialization of servlet means now the servlet for which we have define this tag has been initialized in starting when context is loaded before getting any request.When this servlet question was asked to me in an interview few years back , I was not even aware of this element but this questions pointed me to look DTD of web.xml and understand other elements as well..

2. How can we create deadlock condition on our servlet?

one simple way to call doPost() method inside doGet() and doGet()method inside doPost() it will create deadlock situation for a servlet.

3. For initializing a servlet can we use constructor in place of init ().

No, we can not use constructor for initializing a servlet because for initialization we need an object of servletConfig using this object we get all the parameter which are defined in deployment descriptor for initializing a servlet and in servlet class we have only default constructor according to older version of java so if we want to pass a

Config object we don’t have parametrized constructor and apart from this servlet is loaded and initialized by container so ots a job of container to call the method according to servlet specification they have lifecycle method so init() method is called firstly.

More important Java doesn’t allow interfaces to declare constructors. These kinds of servlet interview questions are quite popular on service based companies who just want to dig one level more.

4. Why super.init (config) wiil be the first statement inside init(config) method.

This will be the first statement if we are overriding the init(config ) method by this way we will store the config object for future reference and we can use by getServletConfig () to get information about config object if will not do this config object will be lost and we have only one way to get config object because servlet pass config object only in init method . Without doing this if we call the servletConfig method will get NullPointerException.

5. Can we call destroy() method inside the init() method is yes what will happen?

Yes we can call like this but  if we have not override this method container will call the default method and nothing will happen.after calling this if any we have override the method then the code written inside is executed.

6. How can we refresh servlet on client and server side automatically?

On client side we can use Meta http refresh and server side we can use server push.

7. How can you get the information about one servlet context in another servlet?

In context object we can set the attribute which we want on another servlet and we can get that attribute using their name on another servlet.

Context.setAttribute (“name”,” value”)

Context.getAttribute (“name”)

8. Why we need to implement Single Thread model in case of Servlet.

In J2EE we can implement our servlet on two different ways either by using:

  1. Single Thread Model
  2. Multithread Model

Depending upon our scenario, if we have implemented single thread means only one instance is going handle one request at a time no two thread will concurrently execute service method of servlet.

Example in banking account where sensitive data is handle mostly this scenario was used this interface is deprecated in Servlet API version 2.4.

As the name signifies multi thread means a servlet is capable to handle multiple requests at same time. This servlet interview question was quite popular few years back on entry level but now its loosing its shine.

9. what is servlet collaboration?

communication between two servlet is called servlet collaboration which is achieved by 3 ways.

  1. RequestDispatchers include () and forward() method .
  2. Using send Redirect()method of Response object.
  3. Using servlet Context methods

10. What is the difference between ServletConfig and ServletContext?

ServletConfig as the name implies provide the information about configuration of a servlet which is defined inside the web.xml file or we can say deployment descriptor.its a specific object for each servlet.

ServletContext is application specific object which is shared by all the servlet belongs to one application in one JVM .this is single object which represent our application and all the servlet access application specific data using this object.servlet also use their method to communicate with container.

11. What is the Servlet?

A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request- response programming model.

12. What are the uses of Servlet?

Typical uses for HTTP Servlets include:

Processing and/or storing data submitted by an HTML form.

Providing dynamic content, e.g. returning the results of a database query to the client.

A Servlet can handle multiple request concurrently and be used to develop high performance system

Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.

13. What are the phases of the servlet life cycle?

The life cycle of a servlet consists of the following phases:

  • Servlet class loading : For each servlet defined in the deployment descriptor of the Web application, the servlet container locates and loads a class of the type of the servlet. This can happen when the servlet engine itself is started, or later when a client request is actually delegated to the servlet.
  • Servlet instantiation : After loading, it instantiates one or more object instances of the servlet class to service the client requests.
  • Initialization (call the init method) : After instantiation, the container initializes a servlet before it is ready to handle client requests. The container initializes the servlet by invoking its init() method, passing an object implementing the ServletConfig interface. In the init() method, the servlet can read configuration parameters from the deployment descriptor or perform any other one-time activities, so the init() method is invoked once and only once by the servlet container.
  • Request handling (call the service method) : After the servlet is initialized, the container may keep it ready for handling client requests. When client requests arrive, they are delegated to the servlet through the service() method, passing the request and response objects as parameters. In the case of HTTP requests, the request and response objects are implementations of HttpServletRequest and HttpServletResponse respectively. In the HttpServlet class, the service() method invokes a different handler method for each type of HTTP request, doGet() method for GET requests, doPost() method for POST requests, and so on.
  • Removal from service (call the destroy method) : A servlet container may decide to remove a servlet from service for various reasons, such as to conserve memory resources. To do this, the servlet container calls the destroy() method on the servlet. Once the destroy() method has been called, the servlet may not service any more client requests. Now the servlet instance is eligible for garbage collection

The life cycle of a servlet is controlled by the container in which the servlet has been deployed.

14. Why do we need a constructor in a servlet if we use the init method?

Even though there is an init method in a servlet which gets called to initialize it, a constructor is still required to instantiate the servlet. Even though you as the developer would never need to explicitly call the servlet’s constructor, it is still being used by the container (the container still uses the constructor to create an instance of the servlet). Just like a normal POJO (plain old java object) that might have an init method, it is no use calling the init method if you haven’t constructed an object to call it on yet.

15. How the servlet is loaded?

A servlet can be loaded when:

  • First request is made.
  • Server starts up (auto-load).
  • There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
  • Administrator manually loads.

16. How a Servlet is unloaded?

A servlet is unloaded when:

  • Server shuts down.
  • Administrator manually unloads.

17. What is 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.

Note: Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet.

18. What is the GenericServlet class?

GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface. 10.What is the GenericServlet class?

Note: This class is known as generic servlet, since it is not specific to any protocol.

19. What’s the difference between GenericServlet and HttpServlet?

GenericServlet HttpServlet
The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP protocol-specific methods. An abstract class that simplifies writing HTTP servlets. It extends the GenericServlet base class and provides an framework for handling the HTTP protocol.
The GenericServlet does not include protocol-specific methods for handling request parameters, cookies, sessions and setting response headers. The HttpServlet subclass passes generic service method requests to the relevant doGet() or doPost() method.
GenericServlet is not specific to any protocol. HttpServlet only supports HTTP and HTTPS protocol.

20. Why is HttpServlet declared abstract?

The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. This is a convenience implementation of the Servlet interface, which means that developers do not need to implement all service methods. If your servlet is required to handle doGet() requests for example, there is no need to write a doPost() method too.12.Why is HttpServlet declared abstract?

21. Can servlet have a constructor ?

One can definitely have constructor in servlet.Even you can use the constrctor in servlet for initialization purpose,but this type of approch is not so common. You can perform common operations with the constructor as you normally do.The only thing is that you cannot call that constructor explicitly by the new keyword as we normally do.In the case of servlet, servlet container is responsible for instantiating the servlet, so the constructor is also called by servlet container only.

22. What are the types of protocols supported by HttpServlet ?

It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.

23. What is the difference between doGet() and doPost()?

# doGet() doPost()
1 In doGet() the parameters are appended to the URL and sent along with header information. In doPost(), on the other hand will (typically) send the information through a socket back to the webserver and it won’t show up in the URL bar.
2 The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters. You can send much more information to the server this way – and it’s not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
3 doGet() is a request for information; it does not (or should not) change anything on the server. (doGet() should be idempotent) doPost() provides information (such as placing an order for merchandise) that the server is expected to remember
4 Parameters are not encrypted Parameters are encrypted
5 doGet() is faster if we set the response content length since the same connection is used. Thus increasing the performance doPost() is generally used to update or post some information to the server.doPost is slower compared to doGet since doPost does not write the content length
6 doGet() should be idempotent. i.e. doget should be able to be repeated safely many times This method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable.
7 doGet() should be safe without any side effects for which user is held responsible This method does not need to be either safe
8 It allows bookmarks. It disallows bookmarks.

24. Explain include Directive and include Action of JSP

This is a very popular interview question on JSP, which has been asked from long time and still asked in various interview. This question is good to test some fundamental concept like translation of JSP and difference between translation time and run time kind of concept.

Syntax for include Directive is <%@ include file=”fileName” %> which means we are including some file to our JSP Page when we use include directive contents of included file will be added to calling JSP page at translation time means when the calling JSP is converted to servlet ,all the contents are added to that page .one important thing is that any JSP page is complied if we make any changes to that particular page but if we have changed the included file or JSP page the main calling JSP page will not execute again so the output will not be according to our expectation, this one is the main disadvantage of using the include directive that why it is mostly use to add static  resources, like Header and footer .

Syntax for include action is <jsp:include page=”relativeURL” /> it’s a runtime procedure means the result of the JSP page which is mentioned in relative URL is appended  to calling JSP at runtime on their response object at the location where we have used this tag

So any changes made to included page is being effected every time, this is the main advantage of this action but only relative URL we can use here ,because request and response object is passed between calling JSP and included JSP.

25. Difference Between include Directive and include Action of JSP

This JSP interview question is a continuation of earlier question I just made it a separate one to write answer in clear tabular format.

Include Directive Include Action
include directive is processed at the translation time Include action is processed at the run time.
include directive can use relative or absolute path Include action always use relative path
Include directive can only include contents of resource it will not process the dynamic resource Include action process the dynamic resource and result will be added to calling JSP
We can not pass any other parameter Here we can pass other parameter also using JSP:param
We cannot  pass any request or response object to calling jsp to included file or JSP or vice versa In this case it’s possible.

26. Is it possible for one JSP to extend another java class if yes how?

Yes it is possible we can extends another JSP using this <%@ include page extends=”classname” %> it’s a perfectly correct because when JSP is converted to servlet its implements javax.servlet.jsp.HttpJspPage interface, so for jsp page its possible to extend another java class . This question can be tricky if you don’t know some basic fact J, though its not advisable to write java code in jsp instead its better to use expression language and tag library.

27. What is < jsp:usebean >tag why it is used.

JSP Syntax

<jsp:useBean
id=”beanInstName”
scope=”page | request | session | application”
class=”package.class”    type=”package.class”

</jsp:useBean>

This tag is used to create a instance of java bean first of all it tries to find out the bean if bean instance already exist assign stores a reference to it in the variable. If we specified type, gives the Bean that type.otherwise instantiates it from the class we specify, storing a reference to it in the new variable.so jsp:usebean is simple way to create a java bean.

Example:      

<jsp:useBean id=”stock” scope=”request” class=”market.Stock” />

<jsp:setProperty name=”bid” property=”price” value=”0.0″ />

a <jsp:useBean> element contains a <jsp:setProperty> element that sets property values in the Bean,we have <jsp:getProperty>element also to get the value from the bean.

Explanation of Attribute

 id=”beanInstanceName”

A variable that identifies the Bean in the scope we specify. If the Bean has already been created by another <jsp:useBean> element, the value of id must match the value of id used in the original <jsp:useBean> element.

scope=”page | request | session | application”

The scope in which the Bean exists and the variable named in id is available. The default value is page. The meanings of the different scopes are shown below:

  • page – we can use the Bean within the JSP page with the <jsp:useBean> element
  • request – we can use the Bean from any JSP page processing the same request, until a JSP page sends a response to the client or forwards the request to another file.
  • session – we can use the Bean from any JSP page in the same session as the JSP page that created the Bean. The Bean exists across the entire session, and any page that participates in the session can use it..
  • application – we can use the Bean from any JSP page in the same application as the JSP page that created the Bean. The Bean exists across an entire JSP application, and any page in the application can use the Bean.

class=”package.class

Instantiates a Bean from a class, using the new keyword and the class constructor. The class must not be abstract and must have a public, no-argument constructor.

type=”package.class

If the Bean already exists in the scope, gives the Bean a data type other than the class from which it was instantiated. If you use type without class or beanName, no Bean is instantiated.

28. How can one Jsp Communicate with Java file.

we have import tag <%@ page import=”market.stock.*” %> like this we can import all the java file to our jsp and use them as a regular class another way is  servlet can send  the instance of the java class to our  jsp and we can retrieve that object from the request obj and use it in our page.

29. what are the implicit Object?

This is a fact based interview question what it checks is how much coding you do in JSP if you are doing it frequently you definitely know them. Implicit object are the object that are created by web container provides to a developer to access them in their program using JavaBeans and Servlets. These objects are called implicit objects because they are automatically instantiated.they are bydefault available in JSP page.

They are: request, response, pageContext, session, and application, out, config, page, and exception.

30. In JSP page how can we handle runtime exception?

This is another popular JSP interview question which has asked to check how candidate used to handle Error and Exception in JSP. We can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page.

Example: <%@ page errorPage=”error.jsp” %>

It will redirect the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, will have to indicate that it is an error-processing page, using the directive: <%@ page isErrorPage=”true” %>

31. Why is _jspService() method starting with an ‘_’ while other life cycle methods do not?

main JSP life cycle method are jspInit() jspDestroy() and _jspService() ,bydefault whatever content we write in our jsp page will go inside the _jspService() method by the container if again will try to override this method JSP compiler will give error but we can override other two life cycle method as we have implementing this two in jsp so making this difference container use _ in jspService() method and shows that we cant override this method.

32. How can you pass information form one jsp to included jsp:

This JSP interview question is little tricky and fact based. Using < Jsp: param> tag we can pass parameter from main jsp to included jsp page

Example:

<jsp:include page=”newbid.jsp” flush=”true”>
<jsp:param name=”price” value=”123.7″/>
<jsp:param name=”quantity” value=”4″/>

33. what is the need of tag library?

tag library is a collection of custom tags. Custom actions helps recurring tasks will be handled more easily they can be reused across more than one application and increase productivity. JSP tag libraries are used by Web application designers who can focus on presentation issues rather than being concerned with how to access databases and other enterprise services. Some of the popular tag libraries are Apache display tag library and String tag library

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

35. Is JSP technology extensible?

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

36. 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 <%@ page isThreadSafe=”false” %> within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe

37. 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 processing 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 you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage=”true” %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.

38. How do I prevent the output of my JSP or Servlet pages from being cached by the browser?

You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both 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
%>

39. 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 are not visible at the client. For example:<%– the scriptlet is now commented 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:

<!– (c) 2004 –>

Of course, you can also use comments supported by your JSP scripting language within your scriptlets. For example, assuming Java is the scripting language, you can have:

<%

//some comment

/**

yet another comment

**/

%>

40. Response has already been commited error. What does it mean?

This error show only when you try to redirect a page after you already have written something in your page. This happens because HTTP specification force the header to be set up before the lay out of the page can be 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 you try to send a redirect status (Number is line_status_402), your HTTP server cannot send it right now if it hasn’t finished to set up the header. If not 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 headers to be finished setting up and it cannot be the case if the stream of the page is not over… In this last case it’s like you have a file started with <HTML Tag><Some Headers><Body>some output (like testing your variables.) Before you indicate that the file is over (and before the size of the page can 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

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

The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.

<jsp:useBean id=”foo” class=”com.Bar.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

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

jsp

<%@ page session=”true” %>

<%

Integer num = new Integer(100);

putValue(“num”,num);

String url =response.encodeURL(“hello2.jsp”);

%>

<a href='<%=url%>’>hello2.jsp</a>

jsp

<%@ page session=”true” %>

<%

Integer i= (Integer )session.getValue(“num”);

println(“Num value in session is “+i.intValue());

43. 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 declare, or within JSP scriptlets and expressions. Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare. For example:

<%!

public String whereFrom(HttpServletRequest req) {

HttpSession ses = req.getSession();

return req.getRemoteHost();

}

%>

<%

print(“Hi there, I see that you are coming in from “);

%>

<%= whereFrom(request) %>

Another Example

jsp:

<%@page contentType=”text/html”%>

<%!

public void test(JspWriter writer) throws IOException{

println(“Hello!”);

}

%>

jsp

<%@include file=”file1.jsp”%>

<html>

<body>

<%test(out);% >

</body>

</html>

44. 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. However, if your 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:

<%setMaxInactiveInterval(300);

%>

would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.

45. 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”);

addCookie(mycookie);

//delete a cookie

Cookie killMyCookie = new Cookie(“mycookie”, null);

setMaxAge(0);

setPath(“/”);

addCookie(killMyCookie);

%>

46. 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 then placed 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 {

FormBean f = new govi.FormBean();

String id = request.getParameter(“id”);

setName(request.getParameter(“name”));

setAddr(request.getParameter(“addr”));

setAge(request.getParameter(“age”));

//use the id to compute

//additional bean properties like info

//maybe perform a db query, etc.

// . . .

setPersonalizationInfo(info);

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” class=”govi.FormBean” scope=”request”

/ jsp:getProperty name=”fBean” property=”name”

/ jsp:getProperty name=”fBean” property=”addr”

/ jsp:getProperty name=”fBean” property=”age”

/ jsp:getProperty name=”fBean” property=”personalizationInfo” /

47. 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 engine. In 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 to fulfill the contract with the JSP engine by:
Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the 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” %>

48. How can I prevent the word “null” from appearing in my HTML input text fields when I populate them with a resultset 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)% >” >

49. How can I get to print the stacktrace for an exception occuring within my JSP page?

By printing out the exception’s stack trace, you can usually diagonse a problem better when debugging JSP pages. By looking at a stack trace, a programmer should be able to discern which method threw the exception and which method called that method. However, you cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The following snippet demonstrates how you can print a stacktrace from within a JSP error page:

<%@ page isErrorPage=”true” %>

<%

println(”    “);

PrintWriter pw = response.getWriter();

printStackTrace(pw);

println(” “);

%>

50. How do you pass an InitParameter to a JSP?

<%@ 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);

out.println(name+”=”+value);

}

}

%>

3 thoughts on “JSP Servlet Interview Questions and Answers”

Leave a Reply

Your email address will not be published. Required fields are marked *


CAPTCHA Image
Reload Image