Today's Jobs :


Showing posts with label java interview questions. Show all posts
Showing posts with label java interview questions. Show all posts

JAVA JSP FREQUENTLY ASKED QUESTIONS AND ANSWERS-3


     JAVA JSP FREQUENTLY ASKED QUESTIONS AND ANSWERS-3


Question: What is the difference between RequestDispatcher and sendRedirect?  
Answer:   RequestDispatcher: server-side redirect with request and response objects.
sendRedirect : Client-side redirect with new request and response objects. 

Question: How does JSP handle runtime exceptions?  
Answer:   Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP. 

Question: How do you delete a Cookie within a JSP?  
Answer:  
 Cookie mycook = new Cookie("name","value"); response.addCookie(mycook); Cookie killmycook = new Cookie("mycook","value"); killmycook.setMaxAge(0);
killmycook.setPath("/"); killmycook.addCookie(killmycook);

Question: How do I mix JSP and SSI #include?  
Answer:   If you're just including raw HTML, use the #include directive as usual inside your .jsp file.
<!--#include file="data.inc"-->
But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. Ronel Sumibcay (ronel@LIVESOFTWARE.COM) says: If your data.inc file contains jsp code you will have to use
<%@ vinclude="data.inc" %>
The <!--#include file="data.inc"--> is used for including non-JSP files. 

Question: How can you store international / Unicode characters into a cookie?  
Answer:   One way is, before storing the cookie URLEncode it.
URLEnocder.encoder(str);
And use URLDecoder.decode(str) when you get the stored cookie.
Question: What are the implicit objects?  
Answer:   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


Question: Is JSP technology extensible?  
Answer:   YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries 


Question: How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?  
Answer:   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 

Question: How does JSP handle run-time exceptions?  
Answer:   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" %>
the 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. 

Question: How do I prevent the output of my JSP or Servlet pages from being cached by the browser?  
Answer:   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
%> 

JAVA JSP FREQUENTLY ASKED QUESTIONS AND ANSWERS-2

    

      JAVA JSP FREQUENTLY ASKED QUESTIONS AND ANSWERS-2


Question:   Can I stop JSP execution while in the midst of processing a request?  
Answer:   Yes. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick (asuming Java is your scripting language) is to use the return statement when you want to terminate further processing. For example, consider:
<% if (request.getParameter("foo") != null) {
// generate some html or update bean property
} else {
/* output some error message or provide redirection back to the input form after creating a memento bean updated with the 'valid' form elements that were input. this bean can now be used by the previous form to initialize the input elements that were valid then, return from the body of the _jspService() method to terminate further processing */
return;
}
%> 

Question:   How can I get to view any compilation/parsing errors at the client while developing JSP pages?  
Answer:   With JSWDK 1.0, set the following servlet initialization property within the \WEB-INF\servlets.properties file for your application:
jsp.initparams=sendErrToClient=true
This will cause any compilation/parsing errors to be sent as part of the response to the client. 

Question:   Is there a way to reference the "this" variable within a JSP page?  
Answer:   Yes, there is. Under JSP 1.0, the page implicit object is equivalent to "this", and returns a reference to the servlet generated by the JSP page. 

Question:   How do I instantiate a bean whose constructor accepts parameters using the useBean tag?  
Answer:   Consider the following bean: package bar;
public class FooBean {
public FooBean(SomeObj arg) {
...
}
//getters and setters here
}
The only way you can instantiate this bean within your JSP page is to use a scriptlet. For example, the following snippet creates the bean with session scope:
&l;% SomeObj x = new SomeObj(...);
bar.FooBean foobar = new FooBean(x);
session.putValue("foobar",foobar);
%> You can now access this bean within any other page that is part of the same session as: &l;%
bar.FooBean foobar = session.getValue("foobar");
%>
To give the bean "application scope", you will have to place it within the ServletContext as:
&l;%
application.setAttribute("foobar",foobar);
%>
To give the bean "request scope", you will have to place it within the request object as:
&l;%
request.setAttribute("foobar",foobar);
%>
If you do not place the bean within the request, session or application scope, the bean can be accessed only within the current JSP page (page scope).
Once the bean is instantiated, it can be accessed in the usual way:
jsp:getProperty name="foobar" property="someProperty"/ jsp:setProperty name="foobar" property="someProperty" value="someValue"/ 

Question:   Can I invoke a JSP error page from a servlet?  
Answer:   Yes, you can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute. However, note that you can do this from only within controller servlets. If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following translation error:
java.lang.IllegalStateException: Cannot forward as OutputStream or Writer has already been obtained
The following code snippet demonstrates the invocation of a JSP error page from within a controller servlet:
protected void sendErrorRedirect(HttpServletRequest request, HttpServletResponse response, String errorPageURL, Throwable e) throws ServletException, IOException {
request.setAttribute ("javax.servlet.jsp.jspException", e);
getServletConfig().getServletContext(). getRequestDispatcher(errorPageURL).forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
// do something
} catch (Exception ex) {
try {
sendErrorRedirect(request,response,"/jsp/MyErrorPage.jsp",ex);
} catch (Exception e) {
e.printStackTrace();
}
}
} 

Question: Can we implement an interface in a JSP?  
Answer:   No 

Question: What is the difference between ServletContext and PageContext?  
Answer:   ServletContext: Gives the information about the container
PageContext: Gives the information about the Request 

Question: What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?  
Answer:   request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource
context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource. 

Question: How to pass information from JSP to included JSP?  
Answer:   Using <%jsp:param> tag. 

Question: What is the difference between directive include and jsp include?  
Answer:   <%@ include> : Used to include static resources during translation time.
: Used to include dynamic content or static content during runtime. 

JAVA JSP FREQUENTLY ASKED QUESTIONS AND ANSWERS-1


       JAVA JSP FREQUENTLY ASKED QUESTIONS AND ANSWERS-1


 Question:   How do I mix JSP and SSI #include?  
Answer:   If you're just including raw HTML, use the #include directive as usual inside your .jsp file.
<!--#include file="data.inc"-->
But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. If your data.inc file contains jsp code you will have to use
<%@ vinclude="data.inc" %>
The <!--#include file="data.inc"--> is used for including non-JSP files. 

Question:   Can a JSP page process HTML FORM data?  
Answer:   Yes. However, unlike servlets, you are not required to implement HTTP-protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression as:
<%
String item = request.getParameter("item");
int howMany = new Integer(request.getParameter("units")).intValue();
%>
or
<%= request.getParameter("item") %>


Question:   What JSP lifecycle methods can I override?  
Answer:   You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().
The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:
<%!
public void jspInit() {
. . .
}
%>

<%!
public void jspDestroy() {
. . .
}
%>


Question:   How do I include static files within a JSP page?  
Answer:   Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. The following example shows the syntax:
<%@ include file="copyright.html" %>
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. 

Question:   How do I perform browser redirection from a JSP page?  
Answer:   You can use the response implicit object to redirect the browser to a different resource, as:
response.sendRedirect("http://www.foo.com/path/error.html");
You can also physically alter the Location HTTP header attribute, as shown below:
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn = "/newpath/index.html";
response.setHeader("Location",newLocn);
%>
You can also use the: <jsp:forward page="/newpage.jsp" /> Also note that you can only use this before any output has been sent to the client. I beleve this is the case with the response.sendRedirect() method as well.
If you want to pass any paramateres then you can pass using <jsp:forward page="/servlet/login"> <jsp:param name="username" value="jsmith" /> </jsp:forward>> 

Question:   Can a JSP page instantiate a serialized bean?  
Answer:   No problem! The useBean action specifies the beanName attribute, which can be used for indicating a serialized bean. For example:
<jsp:useBean id="shop" type="shopping.CD" beanName="CD" /> <jsp:getProperty name="shop" property="album" />
A couple of important points to note. Although you would have to name your serialized file "filename.ser", you only indicate "filename" as the value for the beanName attribute. Also, you will have to place your serialized file within the WEB-INF\jsp\beans directory for it to be located by the JSP engine. 

Question:   Can you make use of a ServletOutputStream object from within a JSP page?  
Answer:   No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients. A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not. A page author can always disable the default buffering for any page using a page directive as:
<%@ page buffer="none" %> 

Question:   What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?  
Answer:   Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

JAVA DESIGN PATTERNS FREQUENTLY ASKED QUESTIONS AND ANSWERS


JAVA DESIGN PATTERNS FREQUENTLY ASKED QUESTIONS AND ANSWERS


DESIGN PATTERN

Question: Describe the visitor design pattern  
Answer:   Represents an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. The root of a class hierarchy defines an abstract method to accept a visitor. Subclasses implement this method with visitor.visit(this). The Visitor interface has visit methods for all subclasses of the baseclass in the hierarchy. 

Question: What is a design pattern?  
Answer:   A design pattern systematically names, motivates, and explains a general design that addresses a recurring design problem. 

Question: Describe the visitor design pattern  
Answer:   Represents an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

The root of a class hierarchy defines an abstract method to accept a visitor. Subclasses implement this method with visitor.visit(this). The Visitor interface has visit methods for all subclasses of the baseclass in the hierarchy.