Search the Web for JAVA Answers:

Search the Web for more JAVA Answers:
Hint: Press Ctrl+ to increase the font size of this blog and Ctrl- to decrease the font size of this blog.

Java Servlet Pages Answers

1. What are servlets?
Answer: A Servlet is a Java class which conforms to the Java Servlet API, a protocol by which a Java class may respond to http requests. Thus, a software developer may use a servlet to add dynamic content to a Web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML. Servlets are the Java counterpart to non-Java dynamic Web content technologies such as CGI and ASP.NET. Servlets can maintain state in session variables across many server transactions by using HTTP cookies, or URL rewriting.
-----------------------------------------------------------------
2. How to find whether a parameter exists in the request object?
Answer:
1.boolean hasFoo = !(request.getParameter("foo") == null ||request.getParameter("foo").equals(""));
2. boolean hasParameter =request.getParameterMap().contains(theParameter);
-----------------------------------------------------------------
3. How can I send user authentication information while making URLConnection?
Answer: You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.
-----------------------------------------------------------------
4. Can we use the constructor, instead of init(), to initialize servlet?
Answer: Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that earlier versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructor a ServletConfig.
That no longer applies, but servlet containers still will only call your no-argument constructor. So you won't have access to a ServletConfig or ServletContext.
-----------------------------------------------------------------
5. How can a servlet refresh automatically if some new data has entered the database?
Answer: You can use a client-side Refresh or Server Push. 
-----------------------------------------------------------------
6. The code in a finally clause will never fail to execute, right?
Answer: Using System.exit(1); in try block will not allow finally code to execute.
-----------------------------------------------------------------
7. What is HttpTunneling
Answer: HTTP tunneling is used to encapsulate other protocols within the HTTP or HTTPS protocols. Normally the intra-network of an organization is blocked by a firewall and the network is exposed to the outer world only through a specific web server port , that listens for only HTTP requests. To use any other protocol, that by passes the firewall, the protocol is embedded in HTTP and send as HttpRequest.
-----------------------------------------------------------------
8. What is Server Side Push and how is it implemented and when is it useful?
Answer: Server Side push is useful when data needs to change regularly on the clients application or browser, without intervention from client. Standard examples might include apps like Stock's Tracker, Current News etc. As such server cannot connect to client's application automatically. The mechanism used is, when client first connects to Server,  then Server keeps the TCP/IP connection open. But it's not always  feasible to keep the connection to the server open. So another method used is, to use the standard HTTP protocols ways of refreshing the page, which is normally supported by all browsers.


META HTTP-EQUIV="Refresh",CONTENT="5;URL=/servlet/stockquotes/


This will refresh the page in the browser automatically and loads the new data every 5 seconds.
-----------------------------------------------------------------
9. What are the phases in JSP? 
Answer: 
a) Translation phase: Conversion of JSP to a Servlet source, and then compilation of servlet source into a class file. The translation phase is typically carried out by the JSP engine itself, when it receives an incoming request for the JSP page for the first time.
b) init(), service() and destroy() method as usual as Servlets.
-----------------------------------------------------------------
10.  What is the difference between sendRedirect( ) and forward( ) methods?
Answer: A sendRedirect method creates a new request (it is also reflected in browser URL ) where as forward method forwards the same request to the new target (hence the change is NOT reflected in browser URL). The previous request scope objects are no longer available after a redirect because it results in a new request, but it is available in forward. sendRedirect() is slower compared to forward.
-----------------------------------------------------------------
11. Is there some sort of event that happens when a session object gets bound or unbound to the session? 
Answer: HttpSessionBindingListener will hear the events When an object is added and/or remove from the session object, or when the session is invalidated, the objects are first removed from the session, whether the session is invalidated manually or automatically (timeout).
-----------------------------------------------------------------
12. What do the differing levels of bean storage (page, session, app) mean?
Answer:
-Page life time: No storage. This is the same as declaring the variable in a scriptlet and using it from there.
-Session life time: The storage exists for the session of the request.
request.getSession(true).putValue "myKey", myObj);
-Application level: The storage exists for the lifetime of the servlet.
getServletConfig().getServletContext().setAttribute("myKey ",myObj )
-Request level: The storage exists for the lifetime of the request, which may be forwarded between jsp's and servlets.
-----------------------------------------------------------------
13. Is it true that servlet containers service each request by creating a new thread? If that is true, how does a container handle a sudden dramatic surge in incoming requests without significant performance degradation? 
Answer: The implementation depends on the Servlet engine. For each request generally, a new thread is created. But to give performance boost, most containers, create and maintain a thread pool at the server startup time. To service a request, they simply borrow a thread from the pool and when they are done, return it to the pool. For this thread pool, upper bound and lower bound is maintained. Upper bound prevents the resource exhaustion problem associated with unlimited thread allocation. The lower bound can instruct the pool not to keep too many idle threads, freeing them if needed.
-----------------------------------------------------------------
14.  Can I just abort processing a JSP?
Answer: Yes. Because your JSP is just a servlet method, you can just put  % return; %  in tags.
-----------------------------------------------------------------
15. What is URL Encoding and URL Decoding ? 
Answer: URL encoding is the method of replacing all the spaces and other extra characters into their hexadecimal characters and URL decoding is the reverse process converting all hexadecimal characters back their normal form.
-----------------------------------------------------------------
16. Do objects stored in a HTTP Session need to be serializable? Or can it store any object?
Answer: Yes, the objects need to be serializable, but only if your servlet container supports persistent sessions. Most lightweight servlet engines (like Tomcat) do not support this. However, many EJB-enabled servlet engines do. Even if your engine does support persistent sessions, it is usually possible to disable this feature.
-----------------------------------------------------------------
17. What is the difference between session and cookie?
Answer: The difference between session and a cookie is two-fold.
1) Session should work regardless of the settings on the client browser. Even if users decide to forbid the cookie (through browser settings) session still works. Currently there is no way to disable sessions from the client browser.
2) Session and cookies differ in type and amount of information they are capable of storing.
javax.servlet.http.Cookie class has a setValue() method that accepts Strings.
javax.servlet.http.HttpSession has a setAttribute() method which takes a string to denote the name and java.lang.Object which means that HttpSession is capable of storing any java object. Cookie can only store string objects.
The Key difference would be cookies are stored in your hard disk whereas a session aren't stored in your hard disk. Sessions are basically like tokens, which are generated at authentication. A session is available as long as the browser is opened.
-----------------------------------------------------------------
18. What is the difference between ServletContext and ServletConfig?
Answer: Both are interfaces. The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method. The ServletContext interface provides information to servlets regarding the environment in which they are running. It also provides standard way for servlets to write events to a log file.
-----------------------------------------------------------------
19. What are the differences between GET and POST service methods? 
Answer: A GET request is a request to get a resource from the server. Choosing GET as the "method" will append all of the data to the URL and it will show up in the URL bar of your browser. The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters. A POST request is a request to post (to send) form data to a resource on the server. A POST on the other hand will (typically) send the information through a socket back to the webserver and it won't show up
in the URL bar. You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
-----------------------------------------------------------------
20. What is the difference between GenericServlet and HttpServlet?
Answer: GenericServlet is an abstract class it can handle all types of protocols,whereas the HttpServlet can handle only Http specific protocols. In generic we use only service method but Http we use the  doGet() & doPost().
----------------------------------------------------------------------------------
21.  What is the maximum amount of information that can be saved in a Session Object ?
Answer: There is no limit on the amount of information that can be saved in a Session Object. Only limitation will be the RAM available on the server machine.
The only limit is the Session ID length(Identifier) , which should not exceed more than 4KB. If the data to be store is very huge, then it's preferred to save it to a temporary file onto hard disk, rather than saving it in session. Internally if the amount of data being saved in Session exceeds the predefined limit, most of the servers write it to a temporary cache on Hard disk.
-----------------------------------------------------------------
22. Explain the status codes of HttpResponse object.
Answer:
100-199: Informational
200-299: Request was successful
300-399: Request file has moved
400-499: Client error
500-599: Server error
-----------------------------------------------------------------
23. What is Servlet chaining?
Answer:  Servlet Chaining means the output of one servlet act as a input to another servlet. Servlet Aliasing allows us to invoke more than one servlet in sequence when the URL is opened with a common servlet alias. The output from first Servlet is sent as input to other Servlet and so on. The Output from the last Servlet is sent back to the browser. The entire process is called Servlet Chaining.


Advantages of Servlet chaining:
1) Chaining reduces the demand on a single servlet.
2) Modular design.
3) Enables different complex processes to be maintained by more than one person.
4) Allows steps in a process to be modified (servlet 1 to servlet 2 or servlet 1 to servlet 3 to servlet 2).
5) Removes the complexity in a single servlet.
-----------------------------------------------------------------
24. I am using servlets. I need to store an object NOT a string in a cookie. Is that possible? The helpfile says BASE64 encoding is suggested for use with binary values. How can I do that? 
Answer: You could serialize the object into a ByteArrayOutputStream and then Base64 encode the resulting byte[]. We must keep in mind the size limitations of a cookie and the overhead of transporting it back and forth between the browser and the server.
Some of the limitations are:
* at most 300 cookies
* at most 4096 bytes per cookie 
* at most 20 cookies per unique host or domain name
-----------------------------------------------------------------
25. Suppose that Myservlet implements SingleThreadModel and there are Local variables, Instance variables, Class variables,Request attributes,Session attributes and Context attributes. Which among these variables would be thread safe? 
Answer Local,Instance and request variables are thread safe.
-----------------------------------------------------------------
26. The first time a Jsp page is requested which method is called?
Answer: The first time a jsp page is requested jspInit method is called and the request is handled by _jspService.
-----------------------------------------------------------------
27. Assume there is a servlet which is placed inside a .jar file and the .jar file is placed under WEB-INF/lib folder. Now you have the same servlet class under WEB-INF/classes folder. Which servlet
class do you think will be called when there is a request to that particular servlet? 
Answer The servlet in WEB-INF/classes folder will be called. Classes under WEBINF/classes will override the classes under WEB-INF/lib.
-----------------------------------------------------------------
28. Can we implement an interface in a JSP?
Answer: No.
-----------------------------------------------------------------
29. What is the difference between ServletContext and PageContext? Answer:
ServletContext: Gives the information about the container.
PageContext: Gives the information about the Request.
-----------------------------------------------------------------
30. What is the difference between request.getRequestDispatcher() and context.getRequestDispatcher()? Answer:
request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource
context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.

-----------------------------------------------------------------
31. How to pass information from JSP to included JSP? Answer Using %jsp:param (in tags)

-----------------------------------------------------------------
32. What is the difference between directive include and jsp include?

Answer: 

%@ include (in tags) : Used to include static resources during translation time.
%jsp:param (in tags):  Used to include dynamic content or static content during runtime.

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


That is the key difference, but this has some important implications:
1) If you use a RequestDispatcher, the target servlet/JSP receives the same request/response objects as the original servlet/JSP. Therefore, you can pass data between them using request.setAttribute(). With a sendRedirect(), it is a new request from the client, and the only way to pass data is through the session or with web parameters (url?name=value).

2) A sendRedirect() also updates the browser history. Suppose you have JSP-1 which has a form that targets Servlet-2, which then redirects to JSP-3. With a redirect, the user's address bar will read "http://[host]/JSP-3". If the user clicks the Reload/Refresh button, only JSP-3 will be re-executed, not Servlet-2.

If you use a RequestDispatcher to forward from Servlet-2 to JSP-3, the user's address bar will read "http://[host]/Servlet-2". A reload/refresh will execute both Servlet-2 and JSP-3. This can be important if Servlet-2 performs some system update (such as credit-card processing).

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


35. What is the difference between Model 1 and Model 2 architecture? 
Answer: In Model 1 there is no Controller and in Model 2 there is a Controller.
-----------------------------------------------------------------
36. How can my application get to know when a HttpSession is removed?
Answer: Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method. Create an instance of that class and put that instance in HttpSession.

-----------------------------------------------------------------
37. How can I implement a thread-safe JSP page?
Answer: You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive 

%@page isThreadSafe="false" (in tags). within your JSP page.
-----------------------------------------------------------------
38. How many JSP scripting elements are there and what are they?
Answer: There are three scripting language elements:
- declarations     -scriptlets      -expressions
-----------------------------------------------------------------
39. In the Servlet 2.4 specification SingleThreadModel has been deprecated,why?
Answer: Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.
-----------------------------------------------------------------
40. 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. Do note that you should always supply a relative URL for the file attribute. 
-----------------------------------------------------------------
41. Can a JSP page process HTML FORM data?
Answer: Yes. However, unlike servlets, you are not required to implement HTTP protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression as:


%String item = request.getParameter("item");
int howMany = new Integer(request.getParameter("units")).intValue();% (in tags)
-----------------------------------------------------------------

42. What JSP lifecycle methods can I override?
Answer: You cannot override the _jspService() method within a JSP page. You can however,
override the jspInit() and jspDestroy() methods within a JSP page.


 jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page.  It is good programming practice to free any allocated resources within jspDestroy().

The jspInit() and jspDestroy() methods are each executed only once during the lifecycle of a JSP page.
-----------------------------------------------------------------

43. How do I perform browser redirection from a JSP page?
Answer:  You can use the response implicit object to redirect the browser to a different resource, as:
response.sendRedirect("http://www.foo.com/path/error.html");

You can also use the: jsp:forward page="/newpage.jsp"/  (in tags)


Also note that you can only use this before any output has been sent to the client.
If you want to pass any parameters then you can pass using:

jsp:forward page="/servlet/login" (in tags)
jsp:param name="username" value="jsmith" / (in tags)
/jsp:forward (in tags)
-----------------------------------------------------------------
44. Can a JSP page instantiate a serialized bean?
Answer: Yes! 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" / (in tags)
jsp:getProperty name="shop" property="album" /   (in tags)

Note: Although you would have to name your serialized file "filename.ser", you only indicate "filename" as the value for the beanName attribute. Also, you will have to place your serialized file within the WEB-INF\jsp\beans directory for it to be located by the JSP engine.

-----------------------------------------------------------------
45. Can you make use of a ServletOutputStream object from within a JSP page?
Answer:  No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object
out) for replying to clients. A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementation perspective, it is not. A page author can always disable the default buffering for any page using a page directive as:
%@ page buffer="none" % (in tags)
-----------------------------------------------------------------
46. What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or
Synchronization? Answer: Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

-----------------------------------------------------------------
47. Can I stop JSP execution while in the midst of processing a request?
Answer: Yes. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick (asuming Java is your scripting language) is to use the return statement when you want to terminate further processing. For example,consider:

% if (request.getParameter("foo") != null)
{   // generate some html or update bean property }
 else
{ /* output some error message or provide redirection back to the input form after creating a memento bean updated with the 'valid' form elements that were input. This bean can now be used by the previous form to initialize the input elements that were valid then, return from the body of the _jspService() method to terminate further processing */
return; }
% (in tags)
-----------------------------------------------------------------
48. How can I get to view any compilation/parsing errors at the client while developing JSP pages?
Answer: With JSWDK 1.0, set the following servlet initialization property within the \WEB-INF\servlets.properties file for your application:
jsp.initparams.sendErrToClient=true
This will cause any compilation/parsing errors to be sent as part of the response to the client.

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

-----------------------------------------------------------------
50. Can I invoke a JSP error page from a servlet?
Answer: Yes, you can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a requestDispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute.
However, note that you can do this from only within controller servlets. If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following translation error:
java.lang.IllegalStateException: Cannot forward as OutputStream or Writer has already been obtained.
-----------------------------------------------------------------
51. How can you store international / Unicode characters into a cookie?
Answer: URLEncode the cookie:
URLEnocder.encoder(str);
And use URLDecoder.decode(str) when you get the stored cookie.

-----------------------------------------------------------------
52. What are the implicit objects? 
Answer: Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are:

request         response               pageContext         session                   exception
application                  out                config                           page 

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

-----------------------------------------------------------------
54. How can I implement a thread-safe JSP page? What are the advantages and disadvantages of using it?
Answer: You can make your JSPs thread-safe by having them implement the 
SingleThreadModel interface. This is done by adding this directive within your JSP page:
%@ page isThreadSafe="false" %   (In tags)

With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. But you should try really hard to make them thread-safe the old fashioned way: by making them thread-safe through
synchronization.
-----------------------------------------------------------------
55. How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
Answer: You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.


%response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server%

-----------------------------------------------------------------
56. How do I use comments within a JSP page? 
Answer: 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");%
--% (in tags)
-----------------------------------------------------------------
57. Response has already been commited error. What does it mean?
Answer: This error shows up only when you try to redirect a page after you already have written something in your page. This happens because HTTP specification forces the header to be set up before the lay out of the page can be shown. When you try to send a redirect status (Number is line_status_402), your HTTP server cannot send it right now if it hasn't finished to set up the header. If it didn't start to set up the header, there are no problems, but if it 's already begin to set up the header, then your HTTP server expects these headers to be finished setting up and it cannot be the case if the stream of the page is not over... In this last case it's like you have a file started with some output (like testing your variables...) ... and before you indicate that the file is over (and before the size of the page can be setted up in the header), you try to send a redirect status... It s simply impossible due to the specification of HTTP 1.0 and 1.1

-----------------------------------------------------------------
58. How can I enable session tracking for JSP pages if the browser has disabled cookies?
Answer: 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. 
-----------------------------------------------------------------
60. How can I set a cookie and delete a cookie from within a JSP page?
Answer: A cookie (mycookie) can be set and deleted using the following scriptlet:

% Cookie mycookie = new Cookie("aName","aValue");   //creating a cookie
response.addCookie(mycookie);                                    
Cookie killMyCookie = new Cookie("mycookie", null);   //delete a cookie
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);% (in Tags)
-----------------------------------------------------------------

61. How does a servlet communicate with a JSP page?
Answer: The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.


public void doPost (HttpServletRequest request, HttpServletResponse response) 

{ try {
govi.FormBean f = new govi.FormBean();
String id = request.getParameter("id");
f.setName(request.getParameter("name"));
f.setAddr(request.getParameter("addr"));
f.setAge(request.getParameter("age"));
//use the id to compute additional bean properties like info,maybe perform a db query, etc.
 f.setPersonalizationInfo(info);
request.setAttribute("fBean",f);
getServletConfig().getServletContext().getRequestDispatcher("/jsp/Bean1.jsp").forward(request, response);
} catch (Exception ex) { . .}
}


The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.
jsp:useBean id="fBean" class="govi.FormBean" scope="request"/
jsp:getProperty name="fBean" property="name" /

jsp:getProperty name="fBean" property="addr" /
jsp:getProperty name="fBean"property="age" / 
jsp:getProperty name="fBean" property="personalizationInfo" /
-----------------------------------------------------------------
62. How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default?
Answer: One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSP engine.  In any case, your new superclass has to fulfill the contract with the JSP engine by:

Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise ensuring that all the methods in the Servlet interface are declared final Additionally, your servlet superclass also needs to do the following:
-The service() method has to invoke the _jspService() method
-The init() method has to invoke the jspInit() method
-The destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may throw a translation error.
-----------------------------------------------------------------

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



%@ page isErrorPage="true" %
% out.println(" Some Error Occured:");
PrintWriter pw = response.getWriter();
exception.printStackTrace(pw);
out.println("Something more");%  (In Tags)
-----------------------------------------------------------------
 64. How do you pass an initParameter to a JSP?
Answer: The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet.
-----------------------------------------------------------------
65. How can my JSP page communicate with an EJB Session Bean?
Answer: The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean:


%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject,foo.AccountHome,
foo.Account" %
%! //declare a "global" reference to an instance of the home interface of the session bean
AccountHome accHome=null;
public void jspInit()
{
InitialContext cntxt = new InitialContext( ); //obtain an instance of the home interface
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome =(AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
}%
% Account acct = accHome.create(); //instantiate the session bean
acct.doWhatever(...);  //invoke the remote methods%
-----------------------------------------------------------------
66. How do you prevent the creation of a Session in a JSP Page and why?
Answer: 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. The page directive is used to prevent a JSP page from automatically creating a session: %@ page session="false" (In tags)
-----------------------------------------------------------------

67. What are the different types of JSP tags?

The different types of JSP tags are as follows:




-----------------------------------------------------------------
68. If we declare a page isThreadSafe="false" then how the page will act?
Answer: A JSP page is by default thread unsafe. That means when server finds a request to JSP, an instance is created and the request is processed. The code inside service method is processed. While in this process, if another request arrives, Server again starts executing the code inside service method for 2nd one. Multitasking is invoked to switch CPU between execution of these 2 threads created. Both are executing same code so, so if any thread changes a variable value and then second reads it, it will get changed one. 


Though this is bad programming practice to have code like this, in most cases this becomes unavoidable. At this time make page threadSafe="true". This will make service method synchronized and at a time only one thread will execute the code. other thread have to wait till that time. But just think how bad will be the response time of server when 100s of requests arrives at a time!