SIDE-BANNERCENTER-BANNERSIDE-BANNER * Oh God! Let there be PEACE. Make them calm, gentle, humble and stable. Make them realize their mistakes. Make them to confess, seek and pray for forgiveness. Let there be forgiveness for true hearts. Show them the right path on which they can walk. Let there be justice, satisfaction and happiness. Let them know that you are the justice and truth. Let them know that the innocent is never punished. Give them the strength, courage and wisdom to quit bad and to achieve good purpose. Let there be leaders who are followed by goodness. Make them competitive to achieve good. Remove their greed, wickedness and bad ambitions. Let them know that your love is infinite. Speak to them in simple ways so they understand. May your heart hear their pure hearts. * Never say die.Live and let live.* Accept Good if not, it Perishes.* What you Sow is what you Reap.* United we Stand divided we Fall.* Where there is a Will there is a Way.* Love is the strongest Power on earth.* When going gets Tough the Tough gets going.* For every problem created there is a perfect Solution.* When your hand starts paining you don't Cut it, Cure it.* A good purpose of life is the persistence to be constructive.* The arch of justice is wide, but it bends towards freedom and justice.* Lion king says he wants all the Power but none of the Responsibilities.* Life is a puzzle which can be solved by Hard work, Character and Discipline.* Money is like Manure, Spread it and it does good.* Pile it up in one place and it Stinks.* When a man wants to be a King he should exactly know the responsibilities of a King.* The only thing necessary for evil to triumph is for good men to do nothing - Edmund Burke.* Face is the reflection of mind.* A purpose of life is a life of purpose.* Beauty lies in the eyes of the beholder.* Necessity is the mother of all inventions. Real friends are those who help us in troubles.* Freedom and Power are lost if it’s miss utilized. Repeating mistakes will lead to sin and blunders.* Quantity is appreciated only when it has Quality.* Everyday is a new day, which brings hope with it.* Ego of superiority is the destruction of individuality.* We cannot learn to swim without going into the water.* Everything happens for good and thus leads to destiny.* Every problem has a perfect solution, we need to find them.* A good purpose of life is the persistence for constructiveness.* It’s hard to create good things where as it’s easy to break them.* Ideas are appreciated and respected only when we express them.* Mistakes do happen by humans, they are forgiven when we pray.* Freedom means giving others the right to achieve good purposes.* We have to put our efforts and leave the rest for destiny to decide.* All big things start with a first step.* First step is sometimes difficult.* Prayers come true when the purpose is good, thus pray for everyone.* Dreams come true when we have faith and pray for good things in life.* We got to have strength, courage and wisdom to achieve good things in life.* Every relationship has a meaning; we have to give them the proper meaning.* The only thing necessary for the triumph of evil is for good men to do nothing.* If wealth is lost, nothing is lost. If health is lost, something is lost. But, if character is lost, everything is lost.* “Stand up, be bold, be strong. Take the whole responsibility on your own shoulders, and know that you are the creator of your own destiny.” - Swami Vivekananda.
HOME-PAGEREALIZATIONQUOTESPUZZLESPRAYERSPERCEPTIONSMUSIC-DOWNLOADSTORIESJOKES
BOOKSBITTER-TRUTHANCIENT-SCRIPTURESBEAUTIFUL-LIFETHOUGHTSFRIENDSHIPPRAYERS-TO-WORSHIPWinning-Publications

QUANTITY is appreciated only when it has QUALITY. Recitation is the mother of Memory. Necessity is the mother of Invention. Knowledge grows when distributed. Enrichment for Information Technology. Persistence to be constructive is the key to success.

Thursday, February 14, 2008

Java Server Pages



* Explain the life-cycle methods in JSP?
A: The generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package.
The HttpJspPage interface extends the JspPage interface which extends Servlet interface of the javax.servlet package. The generated servlet class thus implements all the methods of these three interfaces.
The JspPage interface declares only two methods: "jspInit()" and "jspDestroy()" that must be implemented by all JSP pages regardless of the client-server protocol.
However the JSP specification has provided the HttpJspPage interface specifically for the JSP pages serving HTTP requests. This interface declares one method "_jspService()"
JspPage.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.
HttpJspPage._jspservice()- The container calls the method for each request, passing the request and response objects. This method cannot be overridden.
JspPage.jspDestroy()- The container calls this method to destroy the servlet instance. It is the last method called in the servlet instance.

* What are the phases in JSP? (JSP)
A: Translation phase, conversion of JSP to a Servlet source, then the Compilation of servlet source into a class file. The translation phase is typically carried out by the JSP engine itself, when it initially receives an request for the JSP page. The init(), service() and destroy() are the life cycle methods.

* What JSP life cycle methods can we override? (Sun-Tutor-1) (Sun-Tutor-2)
A: We can 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(). Note that we cannot override the _jspService() method within a JSP page.
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() { . . . } %>

* How many JSP scripting elements are there and what are they? (Elements)
A: There are three JSP scripting language elements: declarations, scriptlets, expressions.

* What is a Expression tag element?
A: 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 and is short for out.println().
We cannot use a semicolon to end an expression. Only one statement per tag.
Expression tag is used to insert Java values directly into the output.
The following Expression tag displays time on the output: <.%= (new java.util.Date()).toLocaleString() %>
The same thing can be done using Scriptlet tag: <.% String str = (new java.util.Date()).toLocaleString(); out.println(str); %>

* What is a Declaration tag element?
A: A declaration tag (<.%! -- %>) declares one or more variables or methods to be used in the JSP source file. We can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file and must contain at least one complete declarative statement.
<.%! some declarations %>
<.%! int i = 0; %>
<.%! int a, b, c; %>

* What is a Scriptlet tag element?
A: A scriptlet tag (<.% --- %>) can contain any number of language statements, variable or method declarations, or expressions that are valid in the scripting language. Within scriptlet tags, we can:
1.Declare variables or methods.
2.Write expressions valid in the scripting language.
3.Use any of the JSP implicit objects or any object declared with a <.jsp:usebean> tag.
We cannot include: plain text, HTML-encoded text, or other JSP tags in the scriptlet.
Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which it is displayed.
Between <.% and %> tags,any valid Java code is called a Scriptlet. This code can access any variable or bean declared.
For example,to print a variable: <.% String username="visualbuilder"; out.println(username); %>

* How do we use a scriptlet to initialize a newly instantiated bean? (JavaBean)
A: 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. (Tutor) (Sun 1.4 Tutor)
The following example shows the "today" property of the Foo bean initialized to the current date when it is instantiated. Note that here, we use a scriptlet within the jsp:setProperty action. (Web Services)
<.jsp:usebean id='foo' class='com.Bar.Foo'>
<.jsp:setproperty name='foo' property='today' value='_'>
<.%-- scriptlets calling bean setter methods go here --%>
<./jsp:setproperty>

What are implicit objects? List them?
These are the objects which are readily available in the JSP file without any declarations or initializations. These objects are parsed by the JSP engine and are inserted into the generated servlet.
List of implicit objects: request, response, pageContext, session, application, out, config, page, exception.

Difference between forward and sendRedirect? (Java Quiz)
A: 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. When we invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container.
The sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to the redirected page. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. The browser issues a completely new request. Any object that is stored as request attribute before the redirect occurs will be lost. Thus HttpServletResponse.sendRedirect kills the session variables. This extra round trip makes a redirect slower than the forward.

What is the difference between <.jsp:include page = ... > and <.%@ include file = ... >?
A: Both the tags includes the information from one page in another. The differences are as follows: (JSP Syntax)
<.jsp:include page = "/index.jsp"
>: This is like a function call from one JSP to another JSP. The included page is executed and the generated html content is included in the content of calling JSP. This happens at runtime. It is executed each time the page is accessed by the client. This approach is useful for modularizing the web application. If the included file changes, then the new content will be included in the output.
<.%@ include file = "relativeURL" >: (OR <.jsp:directive.include file="_">) A relative URL is just the path segment of an URL, without a protocol, port, or domain name (Ex: "/beans/calendar.jsp"). In this case the content of the included file is textually embedded in the requested JSP page. The include process is STATIC.
The included file is added at the time of page translation, i.e before translation of jsp to servlet. The included file must not contain <.html>, <./html>, <.body>, or <./body> tags, as the entire content of the included file is added to the including JSP page. The included file can be a JSP page, HTML file, XML document, or text file.

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

* How do we 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:
<.%@ include file="copyright.html" %> OR <.jsp:directive.include file="relativeURL" />
Do note that we must 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.

* How do we mix JSP and SSI #include?
If we are just including raw HTML, we may use the #include directive inside the .jsp file.
<.!--#include file="data.inc"-->.
This is used for including non-JSP files.
But it's trickier if we want the server to evaluate any JSP file that's included. If our data.inc file contains jsp code, we have to use <.%@ vinclude="data.inc" %>

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

* How does JSP handle run-time exceptions?
A: You can use the errorPage attribute of the page directive to handle uncaught run-time exceptions automatically forwarded to an error processing page. For example: <.%@ page errorPage="error.jsp" %> redirects the browser to the JSP page "error.jsp" if an uncaught exception is encountered during request processing. Within error JSP, if you indicate that it is an error-processing page, using the directive: <.%@ page isErrorPage="true" %> the Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: We must always use a relative URL as the value for the errorPage attribute.

* How can we get to print the stack-trace for an exception occurring within the JSP page?
By printing out the exception's stack trace, we 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, we cannot print the stack-trace using the JSP out implicit variable, which is of type JspWriter. We may have to use a PrintWriter object instead. The following snippet demonstrates how we can print a stack-trace from within a JSP error page:
<.%@ page isErrorPage="true" %.>
<.% out.println(" ");
PrintWriter pw = response.getWriter();
exception.printStackTrace(pw); out.println(" "); %.>

* Can we just abort processing a JSP?
Yes we can, because our JSP is just a servlet method, we can just put a <.% return; %.> whereever necessary.

* What is a JSP output comment?
Answer: A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.
JSP Syntax
<.!-- comment [ <%= expression %> ] -->
Example 1
<.!-- This is a commnet sent to client on <%= (new java.util.Date()).toLocaleString() %> -->
Displays in the page source:
<.!-- This is a commnet sent to client on (Month) (Date), (Year) -->

How can we implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
A: We can make our JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <.%@ page isThreadSafe="false" % > within our JSP page. With this, instead of a single instance of the servlet generated for our JSP page loaded in memory, we will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. We can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for our JSP engine. More importantly, we must avoid using the tag for variables. If we do use this tag, then one should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use . Its better to make them thread-safe the old fashioned way.

* What is a Hidden Comment?
Answer: A comment that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.
You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>.
JSP Syntax
<.%-- comment --%>
Examples
<.%@ page language="java" %>
<.title>A Hidden Comment <./title>
<.%-- This comment will not be visible to the client in the page source --%>

How can we prevent the word "null" from appearing in our HTML input text fields when we populate them with a resultset that has null values?
A: We can make a simple wrapper function, like String blanknull(String s) { return (s == null) ?"":s; } then use it inside our JSP form, like <.input name="lastName" value="<.%=blanknull(lastName)%.>" type="text".>

What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
A: Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If we anticipate our users to increase in the future, we may be better off implementing explicit synchronization for our shared data. The key however, is to effectively minimize the amount of code that is synchronized so that we 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 we did add more memory and increased the size of the instance pool.

How can we enable session tracking for JSP pages if the browser has disabled cookies?
A: 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, we need to append the session ID for each and every link that is part of our servlet response. Adding the session ID to a link is greatly simplified by means of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if we 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()); %>

What is the difference b/w variable declared inside a declaration part and variable declared in scriplet part?
A: Variable declared inside declaration part is treated as a global variable. That means after conversion of JSP file into servlet, that variable will be outside the service method or it will be declared as instance variable. And its scope is available to complete JSP in the converted servlet class. Where as if we declare a variable inside a scriplet, that variable will be declared inside a service method and its scope is within the service method.

Is there a way to execute a JSP from the command-line or from our own application?
A: There is a little tool called JSPExecutor that allows you to do just that. The developers aim was not to write a full blown servlet engine, but to provide means to use JSP for generating source code or reports. Therefore most HTTP-specific features (headers, sessions, etc) are not implemented, i.e. no response-line or header is generated. Nevertheless we can use it to pre-compile JSP for our website.
GnuJsp is a similar tool, like JspExtractor. GNU-JSP translates "*.jsp" files to java source files. Also compiles and runs them. It runs on a wide range of platforms, webservers and servlet engines.

* Can a JSP page process HTML FORM data?
Yes it can, unlike servlets, we are not required to implement HTTP-protocol specific methods like doGet() or doPost() within our JSP page. we can obtain the data for the FORM input elements from 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") %.>

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

* Can a JSP page instantiate a serialized bean?
Yes, it can! 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">
Although we have to name our serialized file "filename.ser", we indicate "filename" as the value for the beanName attribute. We have to place our serialized file within the WEB-INF\jsp\beans directory for it to be located by the JSP engine. (Serialization Example.)

* Can we make use of a ServletOutputStream object from within a JSP page?
No we cannot. We are supposed to make use of only a JSPWriter object (Available to us 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" autoflush="true/false" %>

* Can we stop JSP execution while in the midst of processing a request?
Yes we can. 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 is to use the return statement when we 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; } %>

* How can we view any compilation/parsing errors at the client while developing JSP pages?
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.

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

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

* Can we implement an interface in a JSP?
No, we cannot implement an interface in a JSP file.

* What is the difference between ServletContext and PageContext?
ServletContext: Gives the information about the container.
PageContext: Gives the information about the Request.

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

*
How to set a cookie and delete a cookie in a JSP page?
<.% //creating a cookie
Cookie mycook = new Cookie("name","value");
response.addCookie(mycook);
//delete a cookie
Cookie killmycook = new Cookie("mycook","value");
killmycook.setMaxAge(0);
killmycook.setPath("/");
response.addCookie(killmycook); %.>

* How can you store international / Unicode characters into a cookie?
One way is, before storing the cookie URLEncode it.
String = URLEncoder.encode(str); // This method uses the platform's default encoding as the encoding scheme.
And use URLDecoder.decode(str) when you get the stored cookie.

* Is JSP technology extensible?
YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries. JSP developers can create custom tag libraries by createing their own tag libraries for common functions. This lets web page developers work with familiar tools and constructs, such as tags, to perform sophisticated functions.

* How can we prevent the output of 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 %.>

* How can we use comments within a JSP page?
We can use "JSP-style" comments to selectively block out code while debugging or simply to comment our scriptlets. JSP comments are not visible at the client side. For example:
<.%-- this scriptlet is commented <.% out.println("Hello World"); %.> --%.>
We can also use HTML-style comments anywhere within our JSP page. These comments are visible at the client side. For example:
<.!-- (c) 2004 sun-java.com --.>
We can also use comments supported by our JSP scripting language within our scriptlets. For example, assuming Java is the scripting language, we can have:
<.% //some comment /** yet another comment **/ %.>

* Whats the meaning of error: "Response has already been committed"?
Case 1: We can get an IllegalStateException when we attempt to write to the output stream after something else has been written to it. For example if we are using jsp:include, if the outer jsp has already called getWriter() on the response object, then the inner jsp will get an IllegalStateException if it calls getOutputStream() on the same response object. Response.sendRedirect() throws this error if the response has already been committed increasing the buffer of jsp page can help so that it doesn't get committed before having to send the redirect <%@ page buffer="16kb" %> (default is 8kb).
Case 2: This error is shown only when we try to redirect a page after we have already written something in that page. This happens because HTTP specification forces the header to be set up before the layout of the page can be shown (to make sure of how it should be displayed, content-type="text/html" or "text/xml" or "plain-text" or "image/jpg", etc.) When we try to send a redirect status (Number is line_status_402), our HTTP server cannot send it if it hasn't finished to set up the header. There are no problems if the header is not yet set, but if it's already begun to set up the header, then our 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 case it's like we have a file started with some output (like testing our variables.) and before we indicate that the file is over (and before the size of the page can be set up in the header), we try to send a redirect status. It's improper as per the specifications of HTTP 1.0 and 1.1.

* How can we declare methods within a JSP page?
We can declare methods for use within our JSP page as declarations. The methods can then be invoked within any other methods we declare, or within JSP scriptlets and expressions. Do note that we do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, we should be able to pass any of the implicit JSP variables as parameters to the methods we declare. For example: <.%! public String whereFrom(HttpServletRequest req) { HttpSession ses = req.getSession(); ... return req.getRemoteHost(); } %.>
<.% out.print("Hi there, this is out.print method. "); %.>
<.%= 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" %.>
<.% test(out); %. >

* Is there any way we can set the inactivity lease period on a per-session basis?
Typically, a default inactivity lease period for all sessions is set within our JSP engine admin screen OR associated properties file. However, if our JSP engine supports the Servlet 2.1 API, we 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.

* How does a servlet communicate with a JSP page?
The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by the browser. The bean is 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" .>

* How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default?
One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSP engine. In any case, your new superclass has to fulfill the contract with the JSP engine by:
Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final Additionally, your servlet superclass also needs to do the following:
The service() method has to invoke the _jspService() method
The init() method has to invoke the jspInit() method
The destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may throw a translation error.
Once the superclass has been developed, you can have your JSP extend it as follows:
<.%@ page extends="packageName.ServletName" %.>

* How do you pass an InitParameter to a JSP?
The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and prints them to the console.
<.%@ page import="java.util.*" %.>
<.%! ServletConfig cfg =null; public void jspInit() { ServletConfig cfg=getServletConfig(); for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) { String name=(String)e.nextElement(); String value = cfg.getInitParameter(name); System.out.println(name+"="+value); } } %.>

* How can my JSP page communicate with an EJB Session Bean?
The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean:
<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>
<%! //declare a "global" reference to an instance of the home interface of the session bean AccountHome accHome=null; public void jspInit() { //obtain an instance of the home interface InitialContext cntxt = new InitialContext( ); Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB"); accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class); } %>
<% //instantiate the session bean Account acct = accHome.create(); //invoke the remote methods acct.doWhatever(...); // etc etc... %>

* How can my application get to know when a HttpSession is removed?
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.

* We made our class Cloneable but still we get "Can’t access protected method clone". Why?
Some of the Java books imply that all we have to do in order to have our class support clone() is implement the Cloneable interface. But it's not so. Perhaps that was the intent at some point, but that’s not the way it works currently. As it stands, we have to implement our own public clone() method, even if it doesn’t do anything special and just calls super.clone().



*[Read All Stories.]

*[Read:Two Wolves.] *[Moral Stories.] *[Karna.] *[Ekalavya.] *[Krishna-and-Sudama.] *[Freedom-and-Prison.]

*[Read:Blind-Men-Buddha.] *[Tied-Elephants.] *[Critical-mass-Experiment.] *[Healing-affection.]

*[Read:Punyakoti-Truth.] *[Reply-to-Question.] *[Hasty-decision.] *[False-Cry.] *[Views.]

Read: Peace

Home Download Music Prayers Puzzles - Riddles - Think Add to Google

Stories.

*The-Monkey’s-Justice-for-two-cats. *The-Blind-Men-And-The-Elephant. *Manoj-Kargudri. *Two-rich-merchants-and-a-thief. *Healing-is-contagious. *Two-saints-in-a-market-place. *A-Terrible-Fight-Between-Two-Wolves. *Hen-that-laid-golden-eggs. *Healing-forgiveness-and-affection. *Elephants-held-by-small-ropes. *Story-of-Punyakoti-the-strength-of-truth. *What-is-the-reason? *Reply-Depends-on-the-Question. *Critical-mass-Experiment. *The-Brahman's-Wife-and-the-Mongoose. *The-Boy-Who-Cried-Wolf. *Difference-between-Heaven-and-Hell! *Freedom-and-Prison! *It's-in-Your-Eyes!

No comments:

About Me

My photo
Simple guy who believes in being Competitive rather than being Ambitious. Persistence to be constructive, without frustrations, is a good purpose of life.
.

* * * * * * * * * * * * *

MeetUp Message Board:
Read: Wishes-and-Prayers. *Issue-of-Illegal-Immigration-&-Happy-Kingdom. *The-New-York-Hillary-Rodham-Clinton *Cast-God-Religion! *Barack-Obama-Meetup *Duty- Responsibility-Law-and-Order *John-Edwards-One-America *Good-Wishes-Life-is-Meaningful-&-Beautiful *Dennis-Kucinich-Meetup *Let-there-be-peace! *Bill-Richardson-for-President-2008 *Logic-of-Good-and-Bad-convert-bad-to-good *MORAL-STORY-Elephants-held-by-small-ropes.
* * * * * * * * * * * * *

Realizations.
*Realizations-In-Real-Life-Please-be-gentle-and-humble. *Manoj-D-Kargudri. *Amazing-Constructive-Vibrations. *Astrology. *Creating-Leaders. *How-ideas-are-concluded-and-decisions-are-materialized. *“Relationships-in-Life”-“Partnerships-in-Life”. *The-path-of-victory-the-path-of-life-winning-in-looseing. *An-attempt-for-definition. *Speak-with-a-heart. *These-are-contagious. *Key-to-happy-kingdom. *MIRACLES. *Better-to-create-one! *Cast-God-and-Religion! *Manoj-Kargudri. *Things-become-inevitable! *We-are-all-looking-for! *Phase-of-Life. *Destiny-Karma-and-God. *Struggle-perfection-and-Money. *Independence-and-Freedom. *Relationships-and-Happiness.
* * * * * *

Quotes.
*Love-Compassion-Tolerance-Forgiveness-Courtesy. *Manoj-D-Kargudri. *True-to-Heart-going-back-to-Basics!
* * * * * *

Puzzles-Riddles-Think.
*River-Crossing-Puzzles-Brain-Teasers. *Manoj-Kargudri. *Perpetual-Motion-Gravity-and-Kinetics. *Illusions-Paradoxes-Perpetually-ascending-staircase. *Milk-man-with-no-measureing-jar. *Amazing-Horoscope-Mind-Reader. *Find-the-hidden-images-in-these-STEREOGRAMS. *Are-they-12-or-13? *What-would-U-do? *ABCD-Four-Digit-Number. *10-Digit-Number. *4-QUESTIONS...GOOD-LUCK! *Think-Wise.
* * * * * *

Prayers.
*God-gave-us-everything-we-ever-needed. *Good-Wishes. *Manoj-Kargudri. *Love-Compassion-Tolerance-Forgiveness-Courtesy. *Interview-With-God! *He-is-the-one! *Candle-of-Hope! *Let-there-be-Peace! *Manoj-Kargudri.
* * * * * *

Perceptions.
*Issue-of-Illegal-Immigration. *To-which-religion-does-this-universe-belongs-to? *Law-and-order-helps-to-maintain-justice. *Implementing-regulations-by-justice. *Putting-our-sincere-efforts. *Religion-and-cast. *Impact-of-reservation-based-on-religion-and-cast. *Free-and-Fare-Education-system-Electoral-system.
* * * * * *

Stories.
*The-Monkey’s-Justice-for-two-cats. *The-Blind-Men-And-The-Elephant. *Manoj-Kargudri. *Two-rich-merchants-and-a-thief. *Healing-is-contagious. *Two-saints-in-a-market-place. *A-Terrible-Fight-Between-Two-Wolves. *Hen-that-laid-golden-eggs. *Healing-forgiveness-and-affection. *Elephants-held-by-small-ropes. *Story-of-Punyakoti-the-strength-of-truth. *What-is-the-reason? *Reply-Depends-on-the-Question. *Critical-mass-Experiment. *The-Brahman's-Wife-and-the-Mongoose. *The-Boy-Who-Cried-Wolf. *Difference-between-Heaven-and-Hell! *Freedom-and-Prison! *It's-in-Your-Eyes!
* * * * * *

Jokes.
*Please-listen-to-me. *The-Silent-Treatment! *Surgeon-Vs-Mechanic. *Manoj-Kargudri. *God's-doing-a-lot-better-job-lately.
* * * * * *

The-Bitter-Truth.
*Duty-Responsibility-Law-and-Order. *"Happy-Kingdom"-proudly-proclaimed-as-"Paradise". *Trying-to-learn-something-for-the-first-time. *Time-is-the-only-solution. *For-every-Action-there-is-an-Equal-and-Opposite-Reaction. *Logic-of-Good-and-Bad. *Manoj-Kargudri. *Duties-Responsibilities-verses-Luxuries-and-Pleasures. *Beggars!
* * * * * *

Life-is-Beautiful.
*Creating-successful-constructive-personality. *Why-God-Gave-Us-Friends? *Way-to-Paradise. *Creating-the-Beautiful-World. *Doing-the-job-of-goodness. *Life-is-Meaningful. *Manoj-Kargudri. *The-A-to-Z-for-Goodness. *Life-is-full-of-Tests. *History-Proves-That. *Love-in-different-forms. *True-to-the-heart.
* * * * * *

Prayers-To-Worship.
*Please-do-not-leave-me-ever. *Let’s-make-it-happen. *Faith-in-Patience. *The-only-one-I've-got. *Someone-somewhere. *How-I-Love-You. *Will-You? *Successful-Life. *Manoj-Kargudri. *Please-say-something. *Way-to-Paradise. *My-Everything.
* * * * * *

Friendship.
*Life-Still-Has-A-Meaning. *Heavenly-Garden. *GOD-SPEAK-TO-ME! *Why-God-Made-Friends? *I-asked-the-Lord! *A-Best-Friend! *Why-GOD-Gave-Us-Friends? *Portrait-of-a-Friend. *Friends-till-the-end. *Some-Assorted! *Forever-Friends. *What-is-a-friend!
* * * * * *

Winning-Publications.
*Significance-of-Nava-ratna (Nava-Graha). *Amazing-Constructive-Vibrations. *Manoj-Kargudri. *The-piercing-of-the-ears (karnavedha) . *Nature-Cure. *Steps-to-improve-work-place. *Steps-Involved-In-Relationships. *Some-of-the-aspects-which-materialize-the-relationships.
* * * * * *

Music-Download.
*Bhakti-Songs. *Manoj-Kargudri. *English-Songs. *Gazal-Bhajan-Hindi. *Hindi-Life. *Hindi-Love. *Hindi-Old-Kishore. *Hindi-Old-Mukesh. *Hindi-Old-Songs. *Hindi-Rock. *Hindi-Pops. *Instrumental. *Vocal-Ragas.
* * * * * *

Technology.
*READ: Why-JAVA *Manoj-Kargudri. *Start-Learning-JAVA *Why-Java's-Hot *Start-Using-LINUX *Java-Q-&-A *Question *Java-SE-6-Doc *Struts-Doc *Java-Tutorial-Index *Java-Certification *Tech. *Struts. *Manoj-Kargudri. *Servlet. *JSP. *EJB. *JNDI-JMS *SQL. *JDBC. *CORE-JAVA: *OOP *CLASS. *Manoj-Kargudri. *ABSTRACT *EXCEPTIONS *THREADS *UTILS *PACKAGES *JVM *CASTING *NETWORKING *RMI-XML
* * * * * *

MUSIC-DOWNLOAD.
*Hindi-Vocal-Raga. *Hindi-Remix-Rock. *Hindi-Old-Songs. *Hindi-Mukesh-Mohd-Rafi-Songs. *Hindi-LOVE-Songs. *Hindi-Remix-LIFE. *English-Rock-Songs. *Kannada-Janapada-Geete. *Kannada-Film-Songs. *Kannada-Devotional-Songs. *Instrumental-Music. *Manoj-Kargudri. *Hindi-Pop-Songs. *Hindi-Bhakti-Songs. *Hindi-Kishore-Kumar-SAD. *Hindi-Kishore-Kumar-JOY. *Hindi-R-D-Burman. *Hindi-Gazals. *English-Soft-Songs.
* * * * * *