Docstoc

Complete Java Interview Question

Document Sample
Complete Java Interview Question Powered By Docstoc
					1) What is servlet? Ans: Servlets are modules that extend request/response-oriented servers, such as javaenabled web servers . For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database. 2) What are the classes and interfaces for servlets? Ans: There are two packages in servlets and they are javax.servlet and javax.servlet.http. Javax.servlet contains: Interfaces Classes Servlet Generic Servlet ServletRequest ServletInputStream ServletResponse ServletOutputStream ServletConfig ServletException ServletContext UnavailableException SingleThreadModel Javax.servlet.http contains: Interfaces Classes HttpServletRequest Cookie HttpServletResponse HttpServlet HttpSession HttpSessionBindingEvent HttpSessionContext HttpUtils HttpSeesionBindingListener 3) What is the difference between an applet and a servlet? Ans: a) Servlets are to servers what applets are to browsers. b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces. 4)what is the lifecycle of a servlet. Ans: Each Servlet has the same life cycle: a) A server loads and initializes the servlet by init () method. b) The servlet handles zero or more client’s requests through service( ) method. c) The server removes the servlet through destroy() method.

5) What is the ServletConfig() and why are using ServletConfig ? Ans:This interface is implemented by services in order to pass configuration information to a servlet when it is first loaded.A service writer implementing this interface must write methods for the servlet to use to get its initialization parameters and the context in which it is running. public interface ServletConfig 6) What is meant by the ServletContext() and use of the method ? Ans: public interface ServletContext The ServletContext interface gives servlets access to information about their environment ,and allows them to log significant events. Servlet writers decide what data to log. The interface is implemented by services, and used by servlets. Different virtual hosts should have different servlet contexts. 7) What is use of parseQueryString ? Ans: Parses a query string and builds a hashtable of key-value pairs, where the values are arrays of strings. The query string should have the form of a string packaged by the GET or POST method. (For example, it should have its key-value pairs delimited by ampersands (&) and its keys separated from its values by equal signs (=).) Note: public static Hashtable parseQueryString(String s) 8)what are the types of servlets. Ans: Genereic Servlets,HttpServlets. 9)what are the different methods in HttpServlet. Ans: doGet(),doPost(),doHead,doDelete(),deTrace() 10)What is the difference between GET and POST. Ans: a) doGet() method is used to get information, while doPost( ) method is used for posting information. b) doGet() requests can’t send large amount of information and is limited to 240-255 characters. However,

doPost( )requests passes all of its data, of unlimited length. c) A doGet( ) request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client. 11) Why do you need both GET and POST method implementations in Servlet? Ans: A single servlet can be called from differenr HTML pages,so Different method calls can be possible.

12)When init() and Distroy() will be called. Ans:init() is called whenever the servlet is loaded for the first time into the webserver.Destroy will be called whenever the servlet is removed from the webserver. 13) Who is loading the init() method of servlet? Ans: Web server 14)If you want to modify the servlet,will the Webserver need to be ShutDown. Ans:No 15)What is the advantage of Servlets over other serverside technologies. Ans:PlatForm independent, so once compiled can be used in any webserver.For different processes different threads will execute inbuilt mutithreaded. 16) What is Server-Side Includes (SSI)? Ans: Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with an .shtml extension.

17)What is Single Threaded Model in Servlets and how is it useful give one practical example. Ans: For every single user a differnt copy of this servlet is executed. Credit card transactions. 18) What is the uses Sessions ? Ans:Its a part of the SessionTracking and it is for mainting the client state at server side. 19)What are the advantage of using Sessions over Cookies and URLReWriting? Ans: Sessions are more secure and fast becasue they are stored at serverside. But Sessions has to be used combindly with Cookies or URLReWriting for mainting the client id that is sessionid at client side. Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies which we are mainting may work or not but in sessions cookies are disable we can maintain our sessionid using URLReWriting . In URLReWriting we can't maintain large data because it leads to network traffic and access may be become slow.Where as in seesions will not maintain the data which we have to maintain instead we will maintain only the session id. 20) What is session tracking and how do you track a user session in servlets? Ans: Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are: a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password b) Hidden form fields - fields are added to an HTML form that are not displayed in the client’s browser. When the form containing the fields is submitted, the fields are sent

back to the server c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change. d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser. e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session.maxresidents property 21)What is Cookies and what is the use of Cookies ? Ans:Cookies are used to get user agents (web browsers etc) to hold small amounts of state associated with a user's web browsing.Later that infromation read by server 22) What are cookies and how will you use them? Ans: Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user. a) Create a cookie with the Cookie constructor: public Cookie(String name, String value) b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse: public void HttpServletResponse.addCookie(Cookie cookie) c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest: public Cookie[ ] HttpServletRequest.getCookie( ).

23) How many Cookies is supported to the host ? Ans: User agents excepted to support twenty per host.And its take four Kilobytes each. 24) What is the use of setComment and getComment methods in Cookies ? Ans: setComment:If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described using this comment. This is not supported by version zero cookies.

public void setComment(String use) { } getComment: Returns the comment describing the purpose of this cookie, or null if no such comment has been defined. 25)Why we are used setMaxAge() and getMaxAge() in Cookies ? Ans:setMaxAge public void setMaxAge(int expiry) Sets the maximum age of the cookie.The cookie will expire after that many seconds have passed.Negative values indicate the default behaviour:the cookie is not stored persistently, and will be deleted when the user agent exits.A zero value causes the cookie to be deleted getMaxAge(): public int getMaxAge() Returns the maximum specified age of the cookie. If none was specified, a negative value is returned, indicating the default behaviour described with setMaxAge. 26)What is the use of setSecure() and getSecure() in Cookies ? Ans: setSecure Indicates to the user agent that the cookie should only be sent using a secure protocol (https). This should only be set when the cookie's originating server used a secure protocol to set the cookie's value. public void setSecure(boolean flag) getSecure: Returns the value of the 'secure' flag. public boolean getSecure() 27)What is meant by Httpsession and what is the use of sessions ? Ans:

The HttpSession interface is implemented by services to provide an association between an HTTP client and HTTP server. This session, persists over multiple connections and/or requests during a given time period. Sessions are used to maintain state and user identity across multiple page requests. HttpSession session = req.getSession(true); 28) What are the methods in HttpSession and use of those methods? Ans: a) getCreationTime() Returns the time at which this session representation was created. b) getId() Returns the identifier assigned to this session. c) getLastAccessedTime() Returns the last time the client sent a request carrying the identifier assigned to the session. d) getSessionContext() Returns the context in which this session is bound. e) getValue(String) Returns the object bound to the given name in the session's application layer data. f) getValueNames() Returns an array of the names of all the application layer data objects bound into the session. g) invalidate() Causes this representation of the session to be invalidated and removed from its context. h) isNew() A session is considered to be "new" if it has been created by the server, but the client has not yet acknowledged joining the session. j) putValue(String, Object)

Binds the specified object into the session's application layer data with the given name. k) removeValue(String) Removes the object bound to the given name in the session's application layer data. 29) How do you communicate between the servlets. Ans: a)servlet chaning b)Servlet context(RequestDespatcher interface) 30)Can you send the mail from a servlet ,if yes tell how? Ans:yes.using mail API 31)How do you access variables across the sessions. Ans:Through ServletContext. 32)where the session data will store? ans: session objects 33)What is Servlet Context? Ans:This object represents resources shared by a group of servlets like servlet's environment, Application attributes shared in the context level. 34)How do you trap the debug the errors in servlets. Ans:error log file 35)How do you debug the Servlet? Ans:through servlet log(); 36)How do u implement threads in servlet?

Ans:Intenally implemented 37)How do you handle DataBase access and in which method of the servlet do you like to create connection. Ans:init() 38)If you want to improve the performance how do you create connections for multiple users? A.Connection Pooling. 39)what is connection pooling? Ans:Class which manages no of user requests for connections to improve the performance.

40) What are the different servers available for developing and deploying Servlets? Ans: a) JRun2.0--Allaire b) Apache --jserv c) jwsdk2.0 --sun d) servletexec e) Tomcat webserver--tomcat f)Weblogic AS--BEA Systems g)NetDynamics5.0--sun h)Iplanet--sun&netscape i)Netscape--netscape g)IBM websphere--IBM h)oracle--oracle i)Proton-Pramati technologies

41) Is it possible to communicate from an applet to servlet and how many ways and how? Ans: Yes, there are three ways to communicate from an applet to servlet and they are:

a) HTTP Communication(Text-based and object-based) b) Socket Communication c) RMI Communication (You can say, by using URL object open the connection to server and get the InputStream from URLConnection object). Steps involved for applet-servlet communication: step: 1 Get the server URL. URL url = new URL(); step: 2 Connect to the host URLConnection Con = url.openConnection(); step: 3 Initialize the connection Con.setUseCatches(false): Con.setDoOutput(true); Con.setDoInput(true); step: 4 Data will be written to a byte array buffer so that we can tell the server the length of the data. ByteArrayOutputStream byteout = new ByteArrayOutputStream(); step: 5 Create the OutputStream to be used to write the data to the buffer. DataOutputStream out = new DataOutputStream(byteout); 42) Why should we go for interservlet communication? Ans: Servlets running together in the same server communicate with each other in several ways. The three major reasons to use interservlet communication are: a) Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object) b) Servlet reuse - allows the servlet to reuse the public methods of another servlet. c) Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation) 43) Is it possible to call servlet with parameters in the URL? Ans: Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy). 44) What is Servlet chaining? Ans: Servlet chaining is a technique in which two or more servlets can cooperate in

servicing a single request. In servlet chaining, one servlet’s output is piped to the next servlet’s input. This process continues until the last servlet is reached. Its output is then sent back to the client. 45) How do servlets handle multiple simultaneous requests? Ans: The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost( ) and service( ) ) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once. 46) How are Servlets and JSP Pages related? Ans: JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed. Servlets: 47).How do servlets handle multiple simultaneous requests? Ans: Using Threads 48).How do I automatically reload servlets? Ans:depends upon the server's servlet reload properites. 48).My servlet, which ran correctly under the Servlet 2.0 APIs (Java Web Server 1.1.3) is not running under the Servlet 2.1 APIs (Java Web Server 2.0). What's wrong? Ans:You might have used servlet to servlet communication by using servletcontext methods like getServlet(),getServlets() which are depricated and returns null from new release that is from servlet2.1 API.

49) What are the types of ServletEngines?

Standalone ServletEngine: A standalone engine is a server that includes built-in support for servlets. Add-on ServletEngine: Its a plug-in to an existing server.It adds servlet support to a server that was not originally designed with servlets in mind. Embedded ServletEngine: it is a lightweight servlet deployment platform that can be embedded in another application.that application become true server. 50)what is httptunneling? ans: it is mechanism of performing both write and read operations using http protocol.it is extending the functionality of htp protocol. 51).How do I use native code in a servlet? Ans: 52)What's with the javax.servlet package naming? Ans: 53). List out Differences between CGI Perl and Servlet? Servlet CGI Platform independent Platform dependent. Language dependent Language independent. 1. What is JSP JavaServer Pages. A server-side technology, JavaServer pages are an extension to the Java servlet technology that was developed by Sun. JSPs have dynamic scripting capability that works in tandem with HTML code, separating the page logic from the static elements -- the actual design and display of the page. Embedded in the HTML page, the Java source code and its extensions help make the HTML more functional, being used in dynamic database queries, for example. JSPs are not restricted to any specific platform or server.

2. What are advantages of JSP

whenever there is a change in the code, we dont have to recompile the jsp. it automatically does the compilation. by using custom tags and tag libraries the length of the java code is reduced. 3. What is the difference between include directive & jsp:include action should use the include directive (): if the file includes static text if the file is rarely changed (the JSP engine may not recompile the JSP if this type of included file is modified) if you have a common code snippet that you can reuse across multiple pages (e.g. headers and footers)

should use the jsp:include for content that changes at runtime to select which content to render at runtime (because the page and src attributes can take runtime expressions) for files that change often

4. What are Custom tags. Why do you need Custom tags. How do you create Custom tag Custom tags are those which are user defined. 2) Inorder to separate the presentation logic in a separate class rather than keeping in jsp page we canuse custom tags. 3) Step 1 : Build a class that implements the javax.servlet.jsp.tagext.Tag interface as follows. Compile it and place it under the web-inf/classes directory (in the appropriate package structure). package examples;

import java.io.*; //// THIS PROGRAM IS EVERY TIME I MEAN WHEN U REFRESH THAT PARTICULAR CURRENT DATE THIS CUSTOM TAG WILL DISPLAY import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class ShowDateTag implements Tag { private PageContext pageContext; private Tag parent; public int doStartTag() throws JspException { return SKIP_BODY; } public int doEndTag() throws JspException { try { pageContext.getOut().write("" + new java.util.Date()); } catch (IOException ioe) { throw new JspException(ioe.getMessage()); } return EVAL_PAGE; } public void release() { }

public void setPageContext(PageContext page) { this.pageContext = page;

} public void setParent(Tag tag) { this.parent = tag; } public Tag getParent() { return this.parent; }} Step 2 : Now we need to describe the tag, so create a file called taglib.tld and place it under the web-inf directory. "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> 1.0 1.1 myTag http://www.mycompany.com/taglib My own tag library showDate examples.ShowDateTag Show the current date Step 3 : Now we need to tell the web application where to find the custom tags, and how they will be referenced from JSP pages. Edit the web.xml file under the web-inf directory and insert the following XML fragement. http://www.mycompany.com/taglib /WEB-INF/taglib.tld

Step 4 : And finally, create a JSP page that uses the custom tag. Now restart the server and call up the JSP page! You should notice that every time the page is requested, the current date is displayed in the browser. Whilst this doesn't explain what all the various parts of the tag are for (e.g. the tag description, page context, etc) it should get you going. If you use the tutorial (above) and this example, you should be able to grasp what's going on! 5. What are the implicit objects in JSP & differences between them There are nine implicit objects in JSP. 1. pageContext 2. session 3. request 4. response 5. exception 6. out 7. application 8. config 9. page These are used for different purposes and actually u no need to create these objects in JSP. JSP container will create these objects automatically. You can directly use these objects. Example: If i want to put my username in the session in JSP.

JSP Page: In the about page, i am using session object. But this session object is not declared in JSP file, because, this is implicit object and it will be created by the jsp container. If u see the java file for this jsp page in the work folder of apache tomcat, u will find these objects are created. 15. 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 JSPengine 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: <% session.setMaxInactiveInterval(300); %> would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.

16. 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);

killMyCookie.setPath("/"); response.addCookie(killMyCookie); %>

17. 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(); } %> <% out.print("Hi there, I see that you are coming in from "); %> <%= whereFrom(request) %>

Another Example: file1.jsp:

<%@page contentType="text/html"%> <%! public void test(JspWriter writer) throws IOException{ writer.println("Hello!"); } %> file2.jsp <%@include file="file1.jsp"%> <html> <body> <%test(out);% > </body> </html>

18. 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 <%@ page session="true" %> <% 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());

19. 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" > <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 >

20. How does JSP handle run-time exceptions? You can use the errorPage attribute of the page directive to have uncaught runtime 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.

21. 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 %>

22. 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 <% 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 javagalaxy.com -->

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 **/ %> 23. Can I stop JSP execution while in the midst of processing a request? 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; } %>

24. Is there a way to reference the "this" variable within a JSP page? 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. 25. How do I perform browser redirection from a JSP page? You can use the response implicit object to redirect the browser to a different resource, as:response.sendRedirect("http://www.exforsys.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>> 26. 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.

27. What JSP lifecycle methods can I override? 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() { ... } %> 28. Can a JSP page process HTML FORM data? Yes. However, unlike servlets, you are not required to implement HTTPprotocol 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") %>

29. How do I mix JSP and SSI #include? 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.

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

31. 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. The following example shows the syntax: 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. 32. How do you prevent the Creation of a Session in a JSP Page and why?By default, a JSP page will automatically create a session for the request if one does not exist. However, sessions consume resources and if it is not necessary to maintain a session, one should not be created. For example, a marketing campaign may suggest the reader visit a web page for more information. If it is anticipated that a lot of traffic will hit that page, you may want to optimize the load on the machine by not creating useless sessions.

33. What is the page directive is used to prevent a JSP page from automatically creating a session: <%@ page session="false"> 34. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB? You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be consider as "passed-byvalue", that means that it's read-only in the EJB. If anything is altered from inside the EJB, it won't be reflected back to the HttpSession of the Servlet Container.The "pass-byreference" can be used between EJBs Remote Interfaces, as they are remote references. While it IS possible to pass an HttpSession as a parameter to an EJB object, it is considered to be "bad practice (1)" in terms of object oriented design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejb's api. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction will be flexible enough to support it. (1) Core J2EE design patterns (2001)

35. Can a JSP page instantiate a serialized bean? 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 WEBINFjspbeans directory for it to be located by the JSP engine.

36. Can you make use of a ServletOutputStream object from within a JSP page? 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" %> 37. Can we implements interface or extends class in JSP? Yes u can do tht using <%@ page extend="package.className"> 39. What are the steps required in adding a JSP Tag Libraries? Create a TLD file and configure the required class Information. Create the Java Implementation Source extending the JSP Tag Lib Class (TagSupport). Compile and package it as loosed class file or as a jar under lib folder in Web Archive File for Class loading.Place the TLD file under the WEB-INF folder.Add reference to the tag library in the web.xml file. 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 application javax.servlet.ServletContext Web components contained in the same application. Initialization information for the JSP page's config javax.servlet.ServletConfig 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 page java.lang.Object the current request. Not typically used by JSP page authors. The context for the JSP page. Provides a single pageContext javax.servlet.jsp.PageContext API to manage the various scoped attributes. Subtype of The request triggering the execution of the JSP request javax.servlet.ServletRequest page. Subtype of The response to be returned to the client. Not response javax.servlet.ServletResponse typically used 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 a Session? Answer: A Session refers to all the request that a single client makes to a server. A session is specific to the user and for each user a new session is created to track all the request from that user. Every user has a separate session and separate session variable is associated with that session. In case of web applications the default time-out value for session variable is 20 minutes, which can be changed as per the requirement. Question: What is Session ID? Answer: A session ID is an unique identification string usually a long, random and alpha-numeric string, that is transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in case url rewriting) and hidden fields of Web pages. Question: What is Session Tracking? Answer: HTTP is stateless protocol and it does not maintain the client state. But there exist a mechanism called "Session Tracking" which helps the servers to maintain the state to track the series of requests from the same user across some period of time. Question: What are different types of Session Tracking? Answer: Mechanism for Session Tracking are: a) Cookies b) URL rewriting c) Hidden form fields d) SSL Sessions Question: What is HTTPSession Class? Answer: HttpSession Class provides a way to identify a user across across multiple request. The servlet container uses HttpSession interface to create a session between an HTTP client and an HTTP server. The session lives only for a specified time period, across more than one connection or page request from the user. Question: Why do u use Session Tracking in HttpServlet? Answer: In HttpServlet you can use Session Tracking to track the user state. Session is required if you are developing shopping cart application or in any e-commerce application. Question: What are the advantage of Cookies over URL rewriting? Answer: Sessions tracking using Cookies are more secure and fast. Session tracking using Cookies can also be used with other mechanism of Session Tracking like url rewriting.Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies may work or not. In url rewriting requites large data transfer from and to the server. So, it leads to network traffic and access may be become slow.

Question: What is session hijacking? Answer: If you application is not very secure then it is possible to get the access of system after acquiring or generating the authentication information. Session hijacking refers to the act of taking control of a user session after successfully obtaining or generating an authentication session ID. It involves an attacker using captured, brute forced or reverse-engineered session IDs to get a control of a legitimate user's Web application session while that session is still in progress. Question: What is Session Migration? Answer: Session Migration is a mechanism of moving the session from one server to another in case of server failure. Session Migration can be implemented by: a) Persisting the session into database b) Storing the session in-memory on multiple servers. Question: How to track a user session in Servlets? Answer: The interface HttpSession can be used to track the session in the Servlet. Following code can be used to create session object in the Servlet: HttpSession session = req.getSession(true); Question: How you can destroy the session in Servlet? Answer: You can call invalidate() method on the session object to destroy the session. e.g. session.invalidate(); Question: What is JSP Custom tags ? Answer: JSP Custom tags are user defined JSP language element. JSP custom tags are user defined tags that can encapsulate common functionality. For example you can write your own tag to access the database and performing database operations. You can also write custom tag for encapsulate both simple and complex behaviors in an easy to use syntax and greatly simplify the readability of JSP pages. Question: What is JSP? Answer: JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web clients in a portable, secure and well-defined way. The JavaServer Pages specification extends the Java Servlet API to provide web application developers Question: What is the role of JSP in MVC Model? Answer: JSP is mostly used to develop the user interface, It plays are role of View in the MVC Model. Question: What do you understand by context initialization parameters? Answer: The context-param element contains the declaration of a web application's

servlet context initialization parameters. <context-param> <param-name>name</param-name> <param-value>value</param-value> </context-param> The Context Parameters page lets you manage parameters that are accessed through the ServletContext.getInitParameterNames and ServletContext.getInitParameter methods. Question: Can you extend JSP technology? Answer: JSP technology lets the programmer to extend the jsp to make the programming more easier. JSP can be extended and custom actions and tag libraries can be developed. Question: What do you understand by JSP translation? Answer: JSP translators generate standard Java code for a JSP page implementation class. This class is essentially a servlet class wrapped with features for JSP functionality. Question: What you can stop the browser to cash your page? Answer: Instead of deleting a cache, you can force the browser not to catch the page. <% response.setHeader("pragma","no-cache");//HTTP 1.1 response.setHeader("Cache-Control","no-cache"); response.setHeader("Cache-Control","no-store"); response.addDateHeader("Expires", -1); response.setDateHeader("max-age", 0); //response.setIntHeader ("Expires", -1); //prevents caching at the proxy server response.addHeader("cache-Control", "private"); %> put the above code in your page. Question: What you will handle the runtime exception in your jsp page? Answer: The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and then forwarded to an error processing page. For example: <%@ page errorPage="customerror.jsp" %> above code forwards the request to "customerror.jsp" page if an uncaught exception is encountered during request processing. Within "customerror.jsp", you must indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true" %>.

STRUTS
Q: What is Jakarta Struts Framework? A: Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications . Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java. Q: What is ActionServlet? A: The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests. Q: How you will make available any Message Resources Definitions file to the Struts Framework Environment? A: Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through <messageresources /> tag. Example: <message-resources parameter="MessageResources" /> Q: What is Action Class? A: The Action is part of the controller. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. There should be no database interactions in the action. The action should receive the request, call business objects (which then handle database, or interface with J2EE, etc) and then determine where to go next. Even better, the business objects could be handed to the action at runtime (IoC style) thus removing any dependencies on the model. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

Q: Write code of any Action Class? A: Here is the code of Action Class that returns the ActionForward object. TestAction.java package roseindia.net; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class TestAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{ return mapping.findForward("testAction"); } } Q: What is ActionForm? A: An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side. Q: What is Struts Validator Framework? A: Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

Q. Give the Details of XML files used in Validator Framework? A: The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean. Q. How you will display validation fail errors on jsp page? A: Following tag displays all the errors: <html:errors/> Q. How you will enable front-end validation based on the xml in validation.xml? A: The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code: <html:javascript formName="logonForm" dynamicJavascript="true" staticJavascript="true" /> generates the client side java script for the form "logonForm" as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script. Question: What is RequestProcessor and RequestDispatcher? Answer: The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations. The Controller receives the request from the browser, invoke a business operation and coordinating the view to return to the client. The controller is implemented by a java servlet, this servlet is centralized point of control for the web application . In struts framework the controller responsibilities are implemented by several different components like The ActionServlet Class The RequestProcessor Class The Action Class The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is not abstract and therefore can be used as a concrete controller by your application. The controller is implemented by the ActionServlet class. All incoming requests are mapped to the central controller in the deployment descriptor as follows. <servlet> <servlet-name>action</servlet-name>

<servlet-class>org.apache.struts.action.ActionServlet</servlet-class> </servlet> All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as follows. <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> <url-pattern>*.do</url-pattern> A request URI that matches this pattern will have the following form. http://www.my_site_name.com/mycontext/actionName.do The preceding mapping is called extension mapping, however, you can also specify path mapping where a pattern ends with /* as shown below. <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>/do/*</url-pattern> <url-pattern>*.do</url-pattern> A request URI that matches this pattern will have the following form. http://www.my_site_name.com/mycontext/do/action_Name The class org.apache.struts.action.requestProcessor process the request from the controller. You can sublass the RequestProcessor with your own version and modify how the request is processed. Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation associated with the requested action. In the Struts framework this helper class is descended of org.apache.struts.action.Action class. It acts as a bridge between a client-side user action and business operation. The Action class decouples the client request from the business model. This decoupling allows for more than one-to-one mapping between the user request and an action. The Action class also can perform other functions such as authorization, logging before invoking business operation. the Struts Action class contains several methods, but most important method is the execute() method. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception; The execute() method is called by the controller when a request is received from a client. The controller creates an instance of the Action class if one doesn’t already exist. The strut framework will create only a single instance of each Action class in your application. Action are mapped in the struts configuration file and this configuration is loaded into

memory at startup and made available to the framework at runtime. Each Action element is represented in memory by an instance of the org.apache.struts.action.ActionMapping class . The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request. <action> path= "/somerequest" type="com.somepackage.someAction" scope="request" name="someForm" validate="true" input="somejsp.jsp" <forward name="Success" path="/action/xys" redirect="true"/> <forward name="Failure" path="/somejsp.jsp" redirect="true"/> </action> Once this is done the controller should determine which view to return to the client. The execute method signature in Action class has a return type org.apache.struts.action.ActionForward class. The ActionForward class represents a destination to which the controller may send control once an action has completed. Instead of specifying an actual JSP page in the code, you can declaratively associate as action forward through out the application. The action forward are specified in the configuration file. <action> path= "/somerequest" type="com.somepackage.someAction" scope="request" name="someForm" validate="true" input="somejsp.jsp" <forward name="Success" path="/action/xys" redirect="true"/> <forward name="Failure" path="/somejsp.jsp" redirect="true"/> </action> The action forward mappings also can be specified in a global section, independent of any specific action mapping. <global-forwards> <forward name="Success" path="/action/somejsp.jsp" /> <forward name="Failure" path="/someotherjsp.jsp" /> </global-forwards> public interface RequestDispatcher Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.

This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource. getRequestDispatcher public RequestDispatcher getRequestDispatcher(java.lang.String path) Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response. The resource can be dynamic or static. The pathname must begin with a "/" and is interpreted as relative to the current context root. Use getContext to obtain a RequestDispatcher for resources in foreign contexts. This method returns null if the ServletContext cannot return a RequestDispatcher. Parameters: path - a String specifying the pathname to the resource Returns: a RequestDispatcher object that acts as a wrapper for the resource at the specified path See Also: RequestDispatcher, getContext(java.lang.String) getNamedDispatcher public RequestDispatcher getNamedDispatcher(java.lang.String name) Returns a RequestDispatcher object that acts as a wrapper for the named servlet. Servlets (and JSP pages also) may be given names via server administration or via a web application deployment descriptor. A servlet instance can determine its name using ServletConfig.getServletName(). This method returns null if the ServletContext cannot return a RequestDispatcher for any reason. Parameters: name - a String specifying the name of a servlet to wrap Returns: a RequestDispatcher object that acts as a wrapper for the named servlet See Also: RequestDispatcher, getContext(java.lang.String), ServletConfig.getServletName()

Question: Why cant we overide create method in StatelessSessionBean? Answer: From the EJB Spec : - A Session bean's home interface defines one or morecreate(...) methods. Each create method must be named create and must match one of the ejbCreate methods defined in the enterprise Bean class. The return type of a create method must be the enterprise Bean's remote interface type. The home interface of a stateless session bean must have one create method that takes no arguments. Question: Is struts threadsafe?Give an example? Answer: Struts is not only thread-safe but thread-dependant. The response to a request is handled by a light-weight Action object, rather than an individual servlet. Struts instantiates each Action class once, and allows other requests to be threaded through the original object. This core strategy conserves resources and provides the best possible throughput. A properly-designed application will exploit this further by routing related operations through a single Action. Question: Can we Serialize static variable? Answer: Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data. Serialization is the mechanism used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. In the first section of this book, There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are 1. Serialization ignores static fields, because they are not part of any particular object's state. 2. Base class fields are only handled if the base class itself is serializable. 3. Transient fields. There are four basic things you must do when you are making a class serializable. They are: 1. 2. 3. 4. Implement the Serializable interface. Make sure that instance-level, locally defined state is serialized properly. Make sure that superclass state is serialized properly. Override equals( )and hashCode( ). it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process .

Question: What are the uses of tiles-def.xml file, resourcebundle.properties file, validation.xml file? Answer: tiles-def.xml is is an xml file used to configure tiles with the struts application. You can define the layout / header / footer / body content for your View.

The resourcebundle.properties file is used to configure the message (error/ other messages) for the struts applications. The file validation.xml is used to declare sets of validations that should be applied to Form Beans. Fpr more information please visit Question: What is the difference between perform() and execute() methods? Answer: Perform method is the method which was deprecated in the Struts Version 1.1. In Struts 1.x, Action.perform() is the method called by the ActionServlet. This is typically where your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle your business logic. As we already mentioned, to support declarative exception handling, the method signature changed in perform. Now execute just throws Exception. Action.perform() is now deprecated; however, the Struts v1.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action, depending on which one is available. Question: What are the various Struts tag libraries? Answer: Struts is very rich framework and it provides very good and user friendly way to develop web application forms. Struts provide many tag libraries to ease the development of web applications. These tag libraries are: * Bean tag library - Tags for accessing JavaBeans and their properties. * HTML tag library - Tags to output standard HTML, including forms, text boxes, checkboxes, radio buttons etc.. * Logic tag library - Tags for generating conditional output, iteration capabilities and flow management * Tiles or Template tag library - For the application using tiles * Nested tag library - For using the nested beans in the application Question: What do you understand by DispatchAction? Answer: DispatchAction is an action that comes with Struts 1.1 or later, that lets you combine Struts actions into one class, each with their own method. The org.apache.struts.action.DispatchAction class allows multiple operation to mapped to the different functions in the same Action class. For example: A package might include separate RegCreate, RegSave, and RegDelete Actions, which just perform different operations on the same RegBean object. Since all of these operations are usually handled by the same JSP page, it would be handy to also have them handled by the same Struts Action. A very simple way to do this is to have the submit button modify a field in the form which indicates which operation to perform.

<html:hidden property="dispatch" value="error"/> <SCRIPT>function set(target) {document.forms[0].dispatch.value=target;}</SCRIPT> <html:submit onclick="set('save');">SAVE</html:submit> <html:submit onclick="set('create');">SAVE AS NEW</html:submitl> <html:submit onclick="set('delete);">DELETE</html:submit> Then, in the Action you can setup different methods to handle the different operations, and branch to one or the other depending on which value is passed in the dispatch field. String dispatch = myForm.getDispatch(); if ("create".equals(dispatch)) { ... if ("save".equals(dispatch)) { ... The Struts Dispatch Action [org.apache.struts.actions] is designed to do exactly the same thing, but without messy branching logic. The base perform method will check a dispatch field for you, and invoke the indicated method. The only catch is that the dispatch methods must use the same signature as perform. This is a very modest requirement, since in practice you usually end up doing that anyway. To convert an Action that was switching on a dispatch field to a DispatchAction, you simply need to create methods like this public ActionForward create( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ... public ActionForward save( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ... Cool. But do you have to use a property named dispatch? No, you don't. The only other step is to specify the name of of the dispatch property as the "parameter" property of the action-mapping. So a mapping for our example might look like this: <action path="/reg/dispatch" type="app.reg.RegDispatch" name="regForm"

scope="request" validate="true" parameter="dispatch"/> If you wanted to use the property "o" instead, as in o=create, you would change the mapping to <action path="/reg/dispatch" type="app.reg.RegDispatch" name="regForm" scope="request" validate="true" parameter="o"/> Again, very cool. But why use a JavaScript button in the first place? Why not use several buttons named "dispatch" and use a different value for each? You can, but the value of the button is also its label. This means if the page designers want to label the button something different, they have to coordinate the Action programmer. Localization becomes virtually impossible. Question: How Struts relates to J2EE? Answer: Struts framework is built on J2EE technologies (JSP, Servlet, Taglibs), but it is itself not part of the J2EE standard. Question: What is Struts actions and action mappings? Answer: A Struts action is an instance of a subclass of an Action class, which implements a portion of a Web application and whose perform or execute method returns a forward. An action can perform tasks such as validating a user name and password. An action mapping is a configuration file entry that, in general, associates an action name with an action. An action mapping can contain a reference to a form bean that the action can use, and can additionally define a list of local forwards that is visible only to this action. An action servlet is a servlet that is started by the servlet container of a Web server to process a request that invokes an action. The servlet receives a forward from the action and asks the servlet container to pass the request to the forward's URL. An action servlet must be an instance of an org.apache.struts.action.ActionServlet class or of a subclass of that class. An action servlet is the primary component of the controller.

Question: Can I setup Apache Struts to use multiple configuration files? Answer: Yes Struts can use multiple configuration files. Here is the configuration example: <servlet> <servlet-name>banking</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet </servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml, /WEB-INF/struts-authentication.xml, /WEB-INF/struts-help.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> Question: What are the disadvantages of Struts? Answer: Struts is very robust framework and is being used extensively in the industry. But there are some disadvantages of the Struts: a) High Learning Curve Struts requires lot of efforts to learn and master it. For any small project less experience developers could spend more time on learning the Struts. b) Harder to learn Struts are harder to learn, benchmark and optimize. Question: What is Struts Flow? Answer: Struts Flow is a port of Cocoon's Control Flow to Struts to allow complex workflow, like multi-form wizards, to be easily implemented using continuations-capable JavaScript. It provides the ability to describe the order of Web pages that have to be sent to the client, at any given point in time in an application. The code is based on a proof-of-concept Dave Johnson put together to show how the Control Flow could be extracted from Cocoon. (Ref: http://struts.sourceforge.net/struts-flow/index.html ) Question: What are the difference between <bean:message> and <bean:write>? Answer: <bean:message>: This tag is used to output locale-specific text (from the properties files) from a MessageResources bundle. <bean:write>: This tag is used to output property values from a bean. <bean:write> is a commonly used tag which enables the programmers to easily present the data.

Question: What is LookupDispatchAction? Answer: An abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping. Question: What are the components of Struts? Answer: Struts is based on the MVC design pattern. Struts components can be categories into Model, View and Controller. Model: Components like business logic / business processes and data are the part of Model. View: JSP, HTML etc. are part of View Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests. Question: What are Tag Libraries provided with Struts? Answer: Struts provides a number of tag libraries that helps to create view components easily. These tag libraries are: a) Bean Tags: Bean Tags are used to access the beans and their properties. b) HTML Tags: HTML Tags provides tags for creating the view components like forms, buttons, etc.. c) Logic Tags: Logic Tags provides presentation logics that eliminate the need for scriptlets. d) Nested Tags: Nested Tags helps to work with the nested context. Question: What are the core classes of the Struts Framework? Answer: Core classes of Struts Framework are ActionForm, Action, ActionMapping, ActionForward, ActionServlet etc. Question: What are difference between ActionErrors and ActionMessage? Answer: ActionMessage: A class that encapsulates messages. Messages can be either global or they are specific to a particular bean property. Each individual message is described by an ActionMessage object, which contains a message key (to be looked up in an appropriate message resources database), and up to four placeholder arguments used for parametric substitution in the resulting message. ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm. Validation errors are either global to the entire ActionForm bean they are associated with, or they are specific to a particular bean property (and, therefore, a particular input field on the corresponding form). Question: How you will handle exceptions in Struts? Answer: In Struts you can handle the exceptions in two ways:

a) Declarative Exception Handling: You can either define global exception handling tags in your struts-config.xml or define the exception handling tags within <action>..</action> tag. Example: <exception key="database.error.duplicate" path="/UserExists.jsp" type="mybank.account.DuplicateUserException"/> b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception.

HIBERNATE Q. How will you configure Hibernate? Answer: The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service. " hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the hibernate.properties file. " Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files.

Q. What is a SessionFactory? Is it a thread-safe object? Answer: SessionFactory is Hibernates concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code. SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory(); Q. What is a Session? Can you share a session object between different theads? Answer: Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession() method. & public class HibernateUtil { & public static final ThreadLocal local = new ThreadLocal(); public static Session currentSession() throws HibernateException { Session session = (Session) local.get(); //open a new session if this thread has no session if(session == null) { session = sessionFactory.openSession(); local.set(session); } return session; } } It is also vital that you close your session after your unit of work completes. Note: Keep your Hibernate Session API handy. Q. What are the benefits of detached objects? Answer: Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session.

Q. What are the pros and cons of detached objects? Answer: Pros: " When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session. Cons " In general, working with detached objects is quite cumbersome, and better to not clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway. " Also from pure rich domain driven design perspective it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers. Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects? Answer " Hibernate uses the version property, if there is one. " If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys. " Write your own strategy with Interceptor.isUnsaved().

Q. What is the difference between the session.get() method and the session.load() method? Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null.

Q. What is the difference between the session.update() method and the session.lock() method? Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction. Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well. Q. How would you reatach detached objects to a session when the same object has already been loaded into the session? You can use the session.merge() method call. Q. What are the general considerations or best practices for defining your Hibernate persistent classes? 1.You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance variables. 2.You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object. 3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster. 4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects. 5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.

1.What is ORM ? ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database. 2.What does ORM consists of ? An ORM solution consists of the followig four pieces:
   

API for performing basic CRUD operations API to express queries refering to classes Facilities to specify metadata Optimization facilities : dirty checking,lazy associations fetching

3.What are the ORM levels ? The ORM levels are:
   

Pure relational (stored procedure.) Light objects mapping (JDBC) Medium object mapping Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

4.What is Hibernate? Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks. 5.Why do you need ORM tools like hibernate? The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:


Improved productivity o High-level object-oriented API o Less Java code to write o No SQL to write



 

Improved performance o Sophisticated caching o Lazy loading o Eager loading Improved maintainability o A lot less code to write Improved portability o ORM framework generates database-specific SQL for you

6.What Does Hibernate Simplify? Hibernate simplifies:
    

Saving and retrieving your domain objects Making database column and table name changes Centralizing pre save and post retrieve logic Complex joins for retrieving related items Schema creation from object model

7.What is the need for Hibernate xml mapping file? Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:

8.What are the most common methods of Hibernate configuration? The most common methods of Hibernate configuration are:


Programmatic configuration



XML configuration (hibernate.cfg.xml)

9.What are the important tags of hibernate.cfg.xml? Following are the important tags of hibernate.cfg.xml:

10.What are the Core interfaces are of Hibernate framework? The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.
    

Session interface SessionFactory interface Configuration interface Transaction interface Query and Criteria interfaces 11.What role does the Session interface

play in Hibernate?

The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent

objects. Session session = sessionFactory.openSession(); Session interface role:
  

Wraps a JDBC connection Factory for Transaction Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

12.What role does the SessionFactory interface play in Hibernate? The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work SessionFactory sessionFactory = configuration.buildSessionFactory(); 13.What is the general flow of Hibernate communication with RDBMS? The general flow of Hibernate communication with RDBMS is :
    

Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files Create session factory from configuration object Get one session from this session factory Create HQL Query Execute query to get list containing Java objects

14.What is Hibernate Query Language (HQL)? Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL. 15.How do you map Java Objects with Database tables?

 

First we need to write Java domain objects (beans with setter and getter). Write hbm.xml, where we map java class to table and database columns to Java class variables.

Example : <hibernate-mapping> <class name="com.test.User" table="user"> <property column="USER_NAME" length="255" name="userName" not-null="true" type="java.lang.String"/> <property column="USER_PASSWORD" length="255" name="userPassword" not-null="true" type="java.lang.String"/> </class> </hibernate-mapping>

16.What’s the difference between load() and get()? load() vs. get() :load() Only use the load() method if you are sure that the object exists. load() method will throw an exception if the unique id is not found in the database. load() just returns a proxy by default and database won’t be hit until the proxy is first invoked. get() If you are not sure that the object exists, then use one of the get() methods. get() method will return null if the unique id is not found in the database. get() will hit the database immediately.

17.What is the difference between and merge and update ? Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session. 18.How do you define sequence generated primary key in hibernate? Using <generator> tag. Example:-

<id column="USER_ID" name="id" type="java.lang.Long"> <generator class="sequence"> <param name="table">SEQUENCE_NAME</param> <generator> </id> 19.Define cascade and inverse option in one-many mapping? cascade - enable operations to cascade to child entities. cascade="all|none|save-update|delete|all-delete-orphan" inverse - mark this collection as the "inverse" end of a bidirectional association. inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are? 20.What do you mean by Named – SQL query? Named SQL queries are defined in the mapping xml document and called wherever required. Example: <sql-query name = "empdetails"> <return alias="emp" class="com.test.Employee"/> SELECT emp.EMP_ID AS {emp.empid}, emp.EMP_ADDRESS AS {emp.address}, emp.EMP_NAME AS {emp.name} FROM Employee EMP WHERE emp.NAME LIKE :name </sql-query> Invoke Named Query : List people = session.getNamedQuery("empdetails") .setString("TomBrady", name) .setMaxResults(50) .list(); 21.How do you invoke Stored Procedures?

<sql-query name="selectAllEmployees_SP" callable="true"> <return alias="emp" class="employee"> <return-property name="empid" column="EMP_ID"/> <return-property name="name" column="EMP_NAME"/> <return-property name="address" column="EMP_ADDRESS"/> { ? = call selectAllEmployees() } </return> </sql-query>

22.Explain Criteria API Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set. Example : List employees = session.createCriteria(Employee.class) .add(Restrictions.like("name", "a%") ) .add(Restrictions.like("address", "Boston")) .addOrder(Order.asc("name") ) .list(); 23.Define HibernateTemplate? org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions. 24.What are the benefits does HibernateTemplate provide? The benefits of HibernateTemplate are :
   

HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session. Common functions are simplified to single method calls. Sessions are automatically closed. Exceptions are automatically caught and converted to runtime exceptions.

code changes? Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.

25.How do you switch betweenrelational databases without

26.If you want to see the Hibernate generated SQL statements on console, what should we do? In Hibernate configuration file set as follows: <property name="show_sql">true</property> 27.What are derived properties? The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element. 28.What is component mapping in Hibernate?
    

A component is an object saved as a value, not as a reference A component can be saved directly without needing to declare interfaces or identifier properties Required to define an empty constructor Shared references not supported

29.What is the difference between sorted and ordered collection in hibernate?

sorted collection vs. order collection :sorted collection order collection

A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The Order collection is sorting a collection by sorting occurs in the memory of JVM which specifying the order-by clause for sorting running Hibernate, after the data being this collection when retrieval. read from database using java comparator. If your collection is not large, it will be more efficient way to sort it. If your collection is very large, it will be more efficient way to sort it .

31.What is the advantage of Hibernate over jdbc? Hibernate Vs. JDBC :JDBC With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema. With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code. Hibernate Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application. Hibernate provides this mapping itself. The actual mapping between tables and

JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task.

Application using JDBC to handle persistent data (database tables) having

database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-totable. With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually.

application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.

Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.

Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves With JDBC, caching is maintained by hand- performance if client application reads coding. same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.

In JDBC there is no check that always every user has updated data. This check has to be added by the developer.

32.What are the Collection types in Hibernate ?
    

Bag Set List Array Map

33.What are the ways to express joins in HQL? HQL provides four ways of expressing (inner and outer) joins:   

An implicit association join An ordinary join in the FROM clause A fetch join in the FROM clause. A theta-style join in the WHERE clause.

34.Define cascade and inverse option in one-many mapping? cascade - enable operations to cascade to child entities. cascade="all|none|save-update|delete|all-delete-orphan" inverse - mark this collection as the "inverse" end of a bidirectional association. inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are? 35.What is Hibernate proxy? The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked. 36.How can Hibernate be configured to access an instance variable directly and not through a setter method ? By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object. 37.How can a whole class be mapped as immutable?

Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application. 38.What is the use of dynamic-insert and dynamic-update attributes in a class mapping? Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.




dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

39.What do you mean by fetching strategy ? A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query. 40.What is automatic dirty checking? Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction. 41.What is transactional write-behind? Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.
 42.What are Callback interfaces? Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.

43.What are the types of Hibernate instance states ? Three types of instance states:

  

Transient -The instance is not associated with any persistence context Persistent -The instance is associated with a persistence context Detached -The instance was associated with a persistence context which has been closed – currently not associated

44.What are the differences between EJB 3.0 & Hibernate Hibernate Vs EJB 3.0 :Hibernate Session–Cache or collection of loaded objects relating to a single unit of work XDoclet Annotations used to support Attribute Oriented Programming Defines HQL for expressing queries to the database Supports Entity Relationships through mapping files and annotations in JavaDoc Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API Provides callback support through lifecycle, interceptor, and validatable interfaces Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships EJB 3.0 Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit Java 5.0 Annotations used to support Attribute Oriented Programming Defines EJB QL for expressing queries Support Entity Relationships through Java 5.0 annotations Provides and Entity Manager Interface for managing CRUD operations for an Entity Provides callback support through Entity Listener and Callback methods

Entity Relationships are bidirectional or unidirectional

45.What are the types of inheritance models in Hibernate? There are three types of inheritance models in Hibernate:
  

Table per class hierarchy Table per subclass Table per concrete class

What is ORM? Latest answer: Object Relational Model is a programming technique. This technique is used to convert the data from an incompatible type to that of a relational database. The mapping is done by using the OOP.............. What is Hibernate? Latest answer: Hibernate is an ORM tool. Hibernate is a solution for object-relational mapping and a persistence management layer. For example a java application is used to save data of an object to a database................. Why do you need ORM tools like hibernate? Latest answer: Hibernate is open source ORM tool. Hibernate reduces the time to perform database operations. Hibernate has advantages over using entity beans or JDBC calls. The implementation is done by just using POJOs............ What are the main advantages of ORM like hibernate? Latest answer: The SQL code / statements in the application can be eliminated without writing complex JDBC / Entity Bean code................. What are the core interfaces of Hibernate framework? Latest answer: Session Interface: The basic interface for all hibernate applications. The instances are light weighted and can be created and destroyed without expensive process............ Explain how to configure Hibernate. Latest answer: Hibernate uses a file by name hibernate.cfg.xml. This file creates the connection pool and establishes the required environment. A file named .hbm.xml is used to author mappings...............

Define HibernateTemplate. Latest answer: HibernateTemplate is a helper class that is used to simplify the data access code. This class supports automatically converts HibernateExceptions which is a checked exception into.............. What are the benefits of HibernateTemplate? Latest answer: HibernateTemplate, which is a Spring Template class, can simplify the interactions with Hibernate Sessions............ What is Hibernate proxy? Latest answer: Mapping of classes can be made into a proxy instead of a table. A proxy is returned when actually a load is called on a session........... Explain the types of Hibernate instance states. Latest answer: The persistent class’s instance can be in any one of the three different states. These states are defined with a persistence context. The Hibernate has the following instance states:............. Explain the Collection types in Hibernate. Latest answer: A collection is defined as a one-to-many reference. The simplest collection type in Hibernate is........... What is lazy initialization in hibernate? Latest answer: The delaying the object creation or calculating a value or some process until the first time it is needed. The retrieval of particular information only at the time when the object is accessed............ What is lazy fetching in hibernate? Latest answer: Lazy fetching is associated with child objects loading for its parents. While loading the parent, the selection of loading a child object is to be specified /

mentioned in the hbm.xml file.............. What is the difference between sorted and ordered collection in hibernate? Latest answer: Sorted Collection The sorted collection is a collection that is sorted using the Java collections framework. The sorting is done in the memory of JVM that is running hibernate, soon after reading the data from the database............ Explain the difference between transient (i.e. newly instantiated) and detached objects in hibernate. Latest answer: Transient objects do not have association with the databases and session objects. They are simple objects and not persisted to the database........... Explain the advantages and disadvantages of detached objects. Latest answer: Detached objects passing can be done across layers upto the presentation layer without using Data Transfer Objects................ What is Hibernate Query Language (HQL)? Latest answer: Hibernate Query Language is designed for data management using Hibernate technology. It is completely object oriented and hence has notions like inheritance, polymorphism and abstraction............ Explain the general flow of Hibernate communication with RDBMS? Latest answer: The Hibernate configuration is to be loaded and creation of configuration object is done. The mapping of all hbm files will be performed automatically............ Explain the role of Session interface in Hibernate. Latest answer: Session interface is a single threaded object. The representation of single unit of work with the Java application and the persistence database is done by

this object.......... What is a SessionFactory? Latest answer: The SessionFactory is the concept that is a single data store and thread safe. Because of this feature, many threads can access this concurrently and the sessions are requested, and also............. State the role of SessionFactory interface plays in Hibernate. Latest answer: The SessionFactory is used to create Sessions. Each application is having usually only one SessionFactory........... Explain the difference between load() and get() in Hibernate. Latest answer: load() Use this method if it is sure that the objects exist. The load() method throws an exception,when the unique id could not found in the database.................. What is the difference between merge and update? Latest answer: update () : When the session does not contain an persistent instance with the same identifier, and if it is sure use update for the data persistence in hibernate.......... What is the advantage of Hibernate over jdbc? Latest answer: Hibernate code will work well for all databases, for ex: Oracle,MySQL, etc. where as JDBC is database specific........... Why hibernate is advantageous over Entity Beans & JDBC? Latest answer: An entity bean always works under the EJB container, which allows reusing of the object external to the container. An object can not be detached in entity beans and in hibernate detached objects are supported..............

Explain the main difference between Entity Beans and Hibernate. Latest answer: Entity beans are to be implemented by containers, classes, descriptors. Hibernate is just a tool that quickly persist the object tree to a class hierarchy in a database and without using a single SQL.................. Explain the difference between hibernate and Spring. Latest answer: Hibernate is an ORM tool for data persistency. Spring is a framework for enterprise applications...............

What is ORM? Latest answer: Object Relational Model is a programming technique. This technique is used to convert the data from an incompatible type to that of a relational database. The mapping is done by using the OOP.............. What is Hibernate? Latest answer: Hibernate is an ORM tool. Hibernate is a solution for object-relational mapping and a persistence management layer. For example a java application is used to save data of an object to a database................. Why do you need ORM tools like hibernate? Latest answer: Hibernate is open source ORM tool. Hibernate reduces the time to perform database operations. Hibernate has advantages over using entity beans or JDBC calls. The implementation is done by just using POJOs............ What are the main advantages of ORM like hibernate? Latest answer: The SQL code / statements in the application can be eliminated without writing complex JDBC / Entity Bean code.................

What are the core interfaces of Hibernate framework? Latest answer: Session Interface: The basic interface for all hibernate applications. The instances are light weighted and can be created and destroyed without expensive process............ Explain how to configure Hibernate. Latest answer: Hibernate uses a file by name hibernate.cfg.xml. This file creates the connection pool and establishes the required environment. A file named .hbm.xml is used to author mappings............... Define HibernateTemplate. Latest answer: HibernateTemplate is a helper class that is used to simplify the data access code. This class supports automatically converts HibernateExceptions which is a checked exception into.............. What are the benefits of HibernateTemplate? Latest answer: HibernateTemplate, which is a Spring Template class, can simplify the interactions with Hibernate Sessions............ What is Hibernate proxy? Latest answer: Mapping of classes can be made into a proxy instead of a table. A proxy is returned when actually a load is called on a session........... Explain the types of Hibernate instance states. Latest answer: The persistent class’s instance can be in any one of the three different states. These states are defined with a persistence context. The Hibernate has the following instance states:.............

Explain the Collection types in Hibernate. Latest answer: A collection is defined as a one-to-many reference. The simplest collection type in Hibernate is........... What is lazy initialization in hibernate? Latest answer: The delaying the object creation or calculating a value or some process until the first time it is needed. The retrieval of particular information only at the time when the object is accessed............ What is lazy fetching in hibernate? Latest answer: Lazy fetching is associated with child objects loading for its parents. While loading the parent, the selection of loading a child object is to be specified / mentioned in the hbm.xml file.............. What is the difference between sorted and ordered collection in hibernate? Latest answer: Sorted Collection The sorted collection is a collection that is sorted using the Java collections framework. The sorting is done in the memory of JVM that is running hibernate, soon after reading the data from the database............ Explain the difference between transient (i.e. newly instantiated) and detached objects in hibernate. Latest answer: Transient objects do not have association with the databases and session objects. They are simple objects and not persisted to the database........... Explain the advantages and disadvantages of detached objects. Latest answer: Detached objects passing can be done across layers upto the presentation layer without using Data Transfer Objects................

What is Hibernate Query Language (HQL)? Latest answer: Hibernate Query Language is designed for data management using Hibernate technology. It is completely object oriented and hence has notions like inheritance, polymorphism and abstraction............ Explain the general flow of Hibernate communication with RDBMS? Latest answer: The Hibernate configuration is to be loaded and creation of configuration object is done. The mapping of all hbm files will be performed automatically............ Explain the role of Session interface in Hibernate. Latest answer: Session interface is a single threaded object. The representation of single unit of work with the Java application and the persistence database is done by this object.......... What is a SessionFactory? Latest answer: The SessionFactory is the concept that is a single data store and thread safe. Because of this feature, many threads can access this concurrently and the sessions are requested, and also............. State the role of SessionFactory interface plays in Hibernate. Latest answer: The SessionFactory is used to create Sessions. Each application is having usually only one SessionFactory........... Explain the difference between load() and get() in Hibernate. Latest answer: load() Use this method if it is sure that the objects exist. The load() method throws an exception,when the unique id could not found in the database..................

What is the difference between merge and update? Latest answer: update () : When the session does not contain an persistent instance with the same identifier, and if it is sure use update for the data persistence in hibernate.......... What is the advantage of Hibernate over jdbc? Latest answer: Hibernate code will work well for all databases, for ex: Oracle,MySQL, etc. where as JDBC is database specific........... Why hibernate is advantageous over Entity Beans & JDBC? Latest answer: An entity bean always works under the EJB container, which allows reusing of the object external to the container. An object can not be detached in entity beans and in hibernate detached objects are supported.............. Explain the main difference between Entity Beans and Hibernate. Latest answer: Entity beans are to be implemented by containers, classes, descriptors. Hibernate is just a tool that quickly persist the object tree to a class hierarchy in a database and without using a single SQL..................

Read answer What is the advantage of Hibernate over jdbc? Latest answer: Hibernate code will work well for all databases, for ex: Oracle,MySQL, etc. where as JDBC is database specific........... Read answer Why hibernate is advantageous over Entity Beans & JDBC? Latest answer: An entity bean always works under the EJB container, which allows reusing of the object external to the container. An object can not be detached in entity beans and in hibernate detached objects are supported.............. Read answer Explain the main difference between Entity Beans and Hibernate. Latest answer: Entity beans are to be implemented by containers, classes, descriptors. Hibernate is just a tool that quickly persist the object tree to a class hierarchy in a database and without using a single SQL..................


				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:516
posted:12/18/2009
language:English
pages:73