Showing posts with label jsp. Show all posts
Showing posts with label jsp. Show all posts

Friday, June 25, 2010

SERVLET

QUESTION: 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.

QUESTION: How many cookies can one set in the response object of the servlet? Also, are there any restrictions on the size of cookies?
ANSWER: If the client is using Netscape, the browser can receive and store 300 total cookies

4 kilobytes per cookie (including name)
20 cookies per server or domain

QUESTION: What?s the difference between sendRedirect( ) and forward( ) methods?
ANSWER: A sendRedirect method creates a new request (it?s also reflected in browser?s URL ) where as forward method forwards the same request to the new target(hence the chnge is NOT reflected in browser?s URL).
The previous request scope objects are no longer available after a redirect because it results in a new request, but it?s available in forward.
SendRedirectis slower compared to forward.

QUESTION: 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, in which case the objects are first removed from the session, whether the session is invalidated manually or automatically (timeout).

QUESTION: 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 - request.getSession(true).putValue "myKey", myObj);
application level ? 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

QUESTION: 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.

QUESTION: Can I just abort processing a JSP?
ANSWER: Yes. Because your JSP is just a servlet method, you can just put (whereever necessary) a < % return; % >

QUESTION: What is URL Encoding and URL Decoding ?
ANSWER: URL encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex Characters and Decoding is the reverse process converting all Hex Characters back their normal form.

JSP CONTINUES ... 3

QUESTION: What is a Hidden Comment?
ANSWER: A comments 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 --%\>.

QUESTION: What is a Expression?
ANSWER: 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. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like
You cannot use a semicolon to end an expression

QUESTION: What is a Declaration?
ANSWER: A declaration declares one or more variables or methods for use later in the JSP source file.
A declaration must contain at least one complete declarative statement. You 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.

QUESTION: What is a Scriptlet?
ANSWER: A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can

1.Declare variables or methods to use later in the file (see also Declaration).
2.Write expressions valid in the page scripting language (see also Expression).
3.Use any of the JSP implicit objects or any object declared with a tag.

You must write plain text, HTML-encoded text, or other JSP tags outside 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 you can display it.

QUESTION: What are implicit objects? List them?
ANSWER: Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below
  1. request
  2. response
  3. pageContext
  4. session
  5. application
  6. out
  7. config
  8. page
  9. exception  
QUESTION: Difference between forward and sendRedirect?

ANSWER: When you 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. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

QUESTION: What are the different scope valiues for the ?
ANSWER: The different scope values for are

1. page

2. request

3.session

4.application

QUESTION: Explain the life-cycle mehtods in JSP?
ANSWER: THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - 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 interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService().

The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.

The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.

The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.

Thursday, June 24, 2010

JSP CONTINUES ... 2

QUESTION: How do I mix JSP and SSI #include?
ANSWER: If you're just including raw HTML, use the #include directive as usual inside your .jsp file.



But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. Ronel Sumibcay (ronel@LIVESOFTWARE.COM) says: If your data.inc file contains jsp code you will have to use


The is used for including non-JSP files.

QUESTION: How can you store international / Unicode characters into a cookie?
ANSWER: One way is, before storing the cookie URLEncode it.

URLEnocder.encoder(str);

And use URLDecoder.decode(str) when you get the stored cookie.
 
QUESTION: What are the implicit objects?

ANSWER: Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are:

  1. request
  2. response
  3. pageContext
  4. session
  5. application
  6. out
  7. config
  8. page
  9. exception

 QUESTION: Is JSP technology extensible?

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

 
QUESTION: How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?

ANSWER: You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive

  within your JSP page.

With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine.

 
More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition.

SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use . You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe

 
QUESTION: How does JSP handle run-time exceptions?

 ANSWER: You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:

 

 
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:

 

 

the Throwable object describing the exception may be accessed within the error page via the exception implicit object.

Note: You must always use a relative URL as the value for the errorPage attribute.

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

ANSWER: You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.

 

 
QUESTION: 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:

 

 --%>

 You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:

 

 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:

 

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

 ANSWER: This error show only when you try to redirect a page after you already have written something in your page. This happens because HTTP specification force the header to be set up before the lay out of the page can be shown (to make sure of how it should be displayed...content-type="text/html" or "text/xml" or "plain-text" or "image/jpg", etc...) When you try to send a redirect status (Number is line_status_402), your HTTP server cannot send it right now if it hasn't finished to set up the header. If not starter to set up the header, there are no problems, but if it 's already begin to set up the header, then your HTTP server expects these headers to be finished setting up and it cannot be the case if the stream of the page is not over... In this last case it's like you have a file started with 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

 

QUESTION: How do I use a scriptlet to initialize a newly instantiated bean?

ANSWER: 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 CONTINUES...1

QUESTION: Is there a way to reference the "this" variable within a JSP page?

ANSWER: Yes, there is. Under JSP 1.0, the page implicit object is equivalent to "this", and returns a reference to the servlet generated by the JSP page.

QUESTION: How do I instantiate a bean whose constructor accepts parameters using the useBean tag?
ANSWER: Consider the following bean: package bar;
public class FooBean {
public FooBean(SomeObj arg) {
...
}
//getters and setters here
}

The only way you can instantiate this bean within your JSP page is to use a scriptlet. For example, the following snippet creates the bean with session scope:
&l;% SomeObj x = new SomeObj(...);
bar.FooBean foobar = new FooBean(x);
session.putValue("foobar",foobar);
%> You can now access this bean within any other page that is part of the same session as: &l;%
bar.FooBean foobar = session.getValue("foobar");
%>
To give the bean "application scope", you will have to place it within the ServletContext as:
To give the bean "request scope", you will have to place it within the request object as:
If you do not place the bean within the request, session or application scope, the bean can be accessed only within the current JSP page (page scope).
Once the bean is instantiated, it can be accessed in the usual way:
jsp:getProperty name="foobar" property="someProperty"/ jsp:setProperty name="foobar" property="someProperty" value="someValue"/

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

QUESTION: Can we implement an interface in a JSP?
ANSWER: No

QUESTION: What is the difference between ServletContext and PageContext?
ANSWER: ServletContext: Gives the information about the container
PageContext: Gives the information about the Request


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

QUESTION: How to pass information from JSP to included JSP?
ANSWER: Using

JSP

QUESTION: How do I mix JSP and SSI #include?
ANSWER: If you're just including raw HTML, use the #include directive as usual inside your .jsp file.

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

The is used for including non-JSP files.
QUESTION: Can a JSP page process HTML FORM data?
ANSWER: Yes. However, unlike servlets, you are not required to implement HTTP-protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression as:

or


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

QUESTION: How do I include static files within a JSP page?
ANSWER: Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. The following example shows the syntax:

Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.

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

You can also physically alter the Location HTTP header attribute, as shown below:

You can also use the: 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 >
QUESTION: Can a JSP page instantiate a serialized bean?
ANSWER: No problem! The useBean action specifies the beanName attribute, which can be used for indicating a serialized bean. For example:
 
A couple of important points to note. Although you would have to name your serialized file "filename.ser", you only indicate "filename" as the value for the beanName attribute. Also, you will have to place your serialized file within the WEB-INF\jsp\beans directory for it to be located by the JSP engine.

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


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

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

QUESTION: How can I get to view any compilation/parsing errors at the client while developing JSP pages?
ANSWER: With JSWDK 1.0, set the following servlet initialization property within the \WEB-INF\servlets.properties file for your application:

jsp.initparams=sendErrToClient=true

This will cause any compilation/parsing errors to be sent as part of the response to the client.