1. What are Predefined variables or implicit objects?-
Answer: Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application. The JSP implicit objects are:
application
javax.servlet.ServletContext
The context for the JSP page's servlet and any Web components contained in the same application.
config
javax.servlet.ServletConfig
Initialization information for the JSP page's servlet.
exception
java.lang.Throwable
Accessible only from an error page.
out
javax.servlet.jsp.JspWriter
The output stream.
Page
java.lang.Object
The instance of the JSP page's servlet processing the current request. Not typically used by JSP page authors.
pageContext
javax.servlet.jsp.PageContext
The context for the JSP page. Provides a single API to manage the various scoped attributes.
request
Subtype of javax.servlet.ServletRequest
The request triggering the execution of the JSP page.
response
Subtype of javax.servlet.ServletResponse
The response to be returned to the client. Not typically used by JSP page authors.
session
javax.servlet.http.HttpSession
The session object for the client.
2.What are JSP actions?
Ans: JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include: jsp:include - Include a file at the time the page is requested. jsp:useBean - Find or instantiate a JavaBean. jsp:setProperty - Set the property of a JavaBean. jsp:getProperty - Insert the property of a JavaBean into the output. jsp:forward - Forward the requester to a newpage. Jsp: plugin - Generate browser-specific code that makes an OBJECT or EMBED
3.How do you pass data (including JavaBeans) to a JSP from a servlet?
Ans:
(1) Request Lifetime: Using this technique to pass beans, a request dispatcher (using either “include” or forward”) can be called. This bean will disappear after processing this request has been completed.
Servlet: request. setAttribute(”theBean”, myBean);
RequestDispatcher rd = getServletContext(). getRequestDispatcher(”thepage. jsp”);
rd. forward(request, response);
JSP PAGE:<jsp: useBean id=”theBean” scope=”request” ”. . . . . ” />
(2) Session Lifetime: Using this technique to pass beans that are relevant to a particular session (such as in individual user login) over a number of requests. This bean will disappear when the session is invalidated or it times out, or when you remove it.
Servlet: HttpSession session = request. getSession(true);
session. putValue(”theBean”, myBean); /* You can do a request dispatcher here, or just let the bean be visible on the next request */
JSP Page:<jsp:useBean id=”theBean” scope=”session” ”. . . ” />
3) Application Lifetime: Using this technique to pass beans that are relevant to all servlets and JSP pages in a particular app, for all users. For example, I use this to make a JDBC connection pool object available to the various servlets and JSP pages in my apps. This bean will disappear when the servlet engine is shut down, or when you remove it.
Servlet: GetServletContext(). setAttribute(”theBean”, myBean);
JSP PAGE:<jsp:useBean id=”theBean” scope=”application” ”. . . ” />
4. What is the difference between <jsp:include page = ... > and <%@ include file = ... >?.
Answer: Both the tag includes the information from one page in another. The differences are as follows:
<jsp:include page = ... >: This is like a function call from one jsp to another jsp. It is executed ( the included page is executed and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful to for modularizing the web application. If the included file changed then the new content will be included in the output.
<%@ include file = ... >: In this case the content of the included file is textually embedded in the page that have <%@ include file=".."> directive. In this case in the included file changes, the changed content will not included in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.
5. What is the difference between <jsp:forward page = ... > and response.sendRedirect(url),?.
Answer: The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The response.sendRedirect kills the session variables.
6.What are all the different scope values for the <jsp:useBean> tag? <jsp:useBean> tag is used to use any java object in the jsp page.
Ans:Here are the scope values for <jsp:useBean> tag:
a) page
b) request
c) session and
d) application
7. How you will handle the runtime exception in your jsp page?
Ans: The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and then forwarded to an error processing page.
For example:
<%@ page errorPage="customerror.jsp" %>
above code forwards the request to "customerror.jsp" page if an uncaught exception is encountered during request processing. Within "customerror.jsp", you must indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true" %>.
8. What exactly happens behind the scenes when a JSP page is compiled? Is it converted to a servlet? If it is, then does each request to a JSP page result in the creation of a new servlet?
Ans: The first time a request is made for a JSP file, either directly from a client browser or from a servlet, the JSP file is translated into a servlet by the "JSP engine" (which is itself a servlet -in the JSWDK, it is known as JspServlet). If there are any syntax errors within the JSP file, the translation phase fails, triggering an error message to the client. If it was successful, the generated servlet code is compiled, the servlet is loaded into memory by the JSP engine. At this point, the JSP engine also invokes the jspInit() method, and initializes the servlet. The jspInit() method is invoked just once during the lifetime of the servlet. Then the jspService() method is invoked to process the request and reply to the client. For all subsequent requests to the JSP page, the server checks to see whether the .jsp file has changed since it was last accessed. If there is no change, the request is handled by the jspService() method of the servlet stored in memory in a concurrent manner. Note that since the servlet is always stored in memory, the response is very fast. If the .jsp file has changed, the server automatically recompiles the page file, replaces the servlet in memory, and handles the request as described above. Although JSPs are efficient, there is a slight delay on the first request for a .jsp page since the JSP file has to be compiled into a servlet. Also, the JSP engine may remove the servlet from memory in a nondeterministic way at any time owing to resource constraints. When this happpens, it first invokes the jspDestroy() method, before flagging the servlet instance for garbage collection.
9. Can a JSP be multi-threaded?
Ans: By default, the service() methods of all JSP pages execute in a multithreaded fashion.Each client request is dispatched in a concurrent manner within a separate thread by the servlet engine. Thus, it is important to synchronize access to any page shared state in the default scenario. You can make a page "thread-safe" and have it serve client requests in a single-threaded fashion by setting the page tag's isThreadSafe attribute to false: <%@ page isThreadSafe="false" %>
This causes the generated servlet to implement the SingleThreadModel interface.
10. How do you stop all futher processing in a JSP page?
Ans: You could always just stuff a return in a scriptlet. ...
<% String action = (String)request.getParameter("action");
if(s.equals("stop!"))
return; %> ...
This should work with all JSP implementations. Keep in mind that what you are doing in essence is returning from the middle of a Servlet service() method. I always recommend use of "if" and "else" statements control the flow of the JSP page, rather than bluntly returning.
11. When I reference 'session' or 'request' from within a method contained in a declaration, I get an 'Undefined variable' compile error. Why?
Ans: The implicit objects session, request, etc. are defined in the JSP service method _jspService(). The are not instance level variables of the created JSP class. Hence, they are not immediately available to methods outside the service method. You would need to pass them in as parameters.
12. How do I include a file in my JSP file where I don't know the filename to include until runtime?
Ans: This question describes the basic difference between the %@include file="abc.jsp"% directive and the <jsp:include page="abc.jsp"> tag. Basically, the first is done at compile time and the latter is done at runtime. If the filename itself isn't known until runtime, you need to include another directive in the use of <jsp:include> like:
<% String filename = "foo.jsp"; %>
<jsp:include page="<%= filename %>" flush="true"/>
13. How can I call a servlet from a JSP page? How can I pass variables from the JSP that the servlet can access?
Ans: You can use <jsp:forward page="/relativepath/YourServlet" /> or
response.sendRedirect("http://path/YourServlet").
Variables can be sent as:
<jsp:forward page=/relativepath/YourServlet>
<jsp:param name="name1" value="value1" />
<jsp:param name="name2" value="value2" />
</jsp:forward>
You may also pass parameters to your servlet by specifying
response.sendRedirect("http://path/YourServlet?param1=val1").
See also:
· What servlet code corresponds to the various "scope" values for the
<jsp:useBean> tag?
14. How to disable browser caching for a specific JSP?
Ans:It is possible to keep the browser from caching a JSP page response. The following hints added to the response header seem to prevent most modern browsers from pulling pages out of cache when the same URL is "hit":
<%
response.setHeader( "Pragma", "no-cache" );
response.setHeader( "Cache-Control", "no-cache" );
response.setDateHeader( "Expires", 0 );
%>
The same effect can be achieved by using meta tags in the HTML header:
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="Sat, 01 Dec 2001 00:00:00 GMT">
The Cache-Control header was added in HTTP 1.1, while the other two were also present in HTTP 1.0.
15. Write code to display a dropdown for countries given the countries in the form of a Map. JSTL and Scriptlets. Approach is observed.
16. Explain how to implement the "Delete Selected" from a "Tabular Data" which has check boxes. Use JSF or JSTL or Struts
17. What is the best practice regarding the use of scriptlets in JSP pages? Why? (Hint: Avoid)How can you avoid scriptlet code? (Hint:custom tags, Java beans)
18. What do you understand by the term JSP compilation? (Hint: compiles to servlet code)
Answer: Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application. The JSP implicit objects are:
application
javax.servlet.ServletContext
The context for the JSP page's servlet and any Web components contained in the same application.
config
javax.servlet.ServletConfig
Initialization information for the JSP page's servlet.
exception
java.lang.Throwable
Accessible only from an error page.
out
javax.servlet.jsp.JspWriter
The output stream.
Page
java.lang.Object
The instance of the JSP page's servlet processing the current request. Not typically used by JSP page authors.
pageContext
javax.servlet.jsp.PageContext
The context for the JSP page. Provides a single API to manage the various scoped attributes.
request
Subtype of javax.servlet.ServletRequest
The request triggering the execution of the JSP page.
response
Subtype of javax.servlet.ServletResponse
The response to be returned to the client. Not typically used by JSP page authors.
session
javax.servlet.http.HttpSession
The session object for the client.
2.What are JSP actions?
Ans: JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include: jsp:include - Include a file at the time the page is requested. jsp:useBean - Find or instantiate a JavaBean. jsp:setProperty - Set the property of a JavaBean. jsp:getProperty - Insert the property of a JavaBean into the output. jsp:forward - Forward the requester to a newpage. Jsp: plugin - Generate browser-specific code that makes an OBJECT or EMBED
3.How do you pass data (including JavaBeans) to a JSP from a servlet?
Ans:
(1) Request Lifetime: Using this technique to pass beans, a request dispatcher (using either “include” or forward”) can be called. This bean will disappear after processing this request has been completed.
Servlet: request. setAttribute(”theBean”, myBean);
RequestDispatcher rd = getServletContext(). getRequestDispatcher(”thepage. jsp”);
rd. forward(request, response);
JSP PAGE:<jsp: useBean id=”theBean” scope=”request” ”. . . . . ” />
(2) Session Lifetime: Using this technique to pass beans that are relevant to a particular session (such as in individual user login) over a number of requests. This bean will disappear when the session is invalidated or it times out, or when you remove it.
Servlet: HttpSession session = request. getSession(true);
session. putValue(”theBean”, myBean); /* You can do a request dispatcher here, or just let the bean be visible on the next request */
JSP Page:<jsp:useBean id=”theBean” scope=”session” ”. . . ” />
3) Application Lifetime: Using this technique to pass beans that are relevant to all servlets and JSP pages in a particular app, for all users. For example, I use this to make a JDBC connection pool object available to the various servlets and JSP pages in my apps. This bean will disappear when the servlet engine is shut down, or when you remove it.
Servlet: GetServletContext(). setAttribute(”theBean”, myBean);
JSP PAGE:<jsp:useBean id=”theBean” scope=”application” ”. . . ” />
4. What is the difference between <jsp:include page = ... > and <%@ include file = ... >?.
Answer: Both the tag includes the information from one page in another. The differences are as follows:
<jsp:include page = ... >: This is like a function call from one jsp to another jsp. It is executed ( the included page is executed and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful to for modularizing the web application. If the included file changed then the new content will be included in the output.
<%@ include file = ... >: In this case the content of the included file is textually embedded in the page that have <%@ include file=".."> directive. In this case in the included file changes, the changed content will not included in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.
5. What is the difference between <jsp:forward page = ... > and response.sendRedirect(url),?.
Answer: The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The response.sendRedirect kills the session variables.
6.What are all the different scope values for the <jsp:useBean> tag? <jsp:useBean> tag is used to use any java object in the jsp page.
Ans:Here are the scope values for <jsp:useBean> tag:
a) page
b) request
c) session and
d) application
7. How you will handle the runtime exception in your jsp page?
Ans: The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and then forwarded to an error processing page.
For example:
<%@ page errorPage="customerror.jsp" %>
above code forwards the request to "customerror.jsp" page if an uncaught exception is encountered during request processing. Within "customerror.jsp", you must indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true" %>.
8. What exactly happens behind the scenes when a JSP page is compiled? Is it converted to a servlet? If it is, then does each request to a JSP page result in the creation of a new servlet?
Ans: The first time a request is made for a JSP file, either directly from a client browser or from a servlet, the JSP file is translated into a servlet by the "JSP engine" (which is itself a servlet -in the JSWDK, it is known as JspServlet). If there are any syntax errors within the JSP file, the translation phase fails, triggering an error message to the client. If it was successful, the generated servlet code is compiled, the servlet is loaded into memory by the JSP engine. At this point, the JSP engine also invokes the jspInit() method, and initializes the servlet. The jspInit() method is invoked just once during the lifetime of the servlet. Then the jspService() method is invoked to process the request and reply to the client. For all subsequent requests to the JSP page, the server checks to see whether the .jsp file has changed since it was last accessed. If there is no change, the request is handled by the jspService() method of the servlet stored in memory in a concurrent manner. Note that since the servlet is always stored in memory, the response is very fast. If the .jsp file has changed, the server automatically recompiles the page file, replaces the servlet in memory, and handles the request as described above. Although JSPs are efficient, there is a slight delay on the first request for a .jsp page since the JSP file has to be compiled into a servlet. Also, the JSP engine may remove the servlet from memory in a nondeterministic way at any time owing to resource constraints. When this happpens, it first invokes the jspDestroy() method, before flagging the servlet instance for garbage collection.
9. Can a JSP be multi-threaded?
Ans: By default, the service() methods of all JSP pages execute in a multithreaded fashion.Each client request is dispatched in a concurrent manner within a separate thread by the servlet engine. Thus, it is important to synchronize access to any page shared state in the default scenario. You can make a page "thread-safe" and have it serve client requests in a single-threaded fashion by setting the page tag's isThreadSafe attribute to false: <%@ page isThreadSafe="false" %>
This causes the generated servlet to implement the SingleThreadModel interface.
10. How do you stop all futher processing in a JSP page?
Ans: You could always just stuff a return in a scriptlet. ...
<% String action = (String)request.getParameter("action");
if(s.equals("stop!"))
return; %> ...
This should work with all JSP implementations. Keep in mind that what you are doing in essence is returning from the middle of a Servlet service() method. I always recommend use of "if" and "else" statements control the flow of the JSP page, rather than bluntly returning.
11. When I reference 'session' or 'request' from within a method contained in a declaration, I get an 'Undefined variable' compile error. Why?
Ans: The implicit objects session, request, etc. are defined in the JSP service method _jspService(). The are not instance level variables of the created JSP class. Hence, they are not immediately available to methods outside the service method. You would need to pass them in as parameters.
12. How do I include a file in my JSP file where I don't know the filename to include until runtime?
Ans: This question describes the basic difference between the %@include file="abc.jsp"% directive and the <jsp:include page="abc.jsp"> tag. Basically, the first is done at compile time and the latter is done at runtime. If the filename itself isn't known until runtime, you need to include another directive in the use of <jsp:include> like:
<% String filename = "foo.jsp"; %>
<jsp:include page="<%= filename %>" flush="true"/>
13. How can I call a servlet from a JSP page? How can I pass variables from the JSP that the servlet can access?
Ans: You can use <jsp:forward page="/relativepath/YourServlet" /> or
response.sendRedirect("http://path/YourServlet").
Variables can be sent as:
<jsp:forward page=/relativepath/YourServlet>
<jsp:param name="name1" value="value1" />
<jsp:param name="name2" value="value2" />
</jsp:forward>
You may also pass parameters to your servlet by specifying
response.sendRedirect("http://path/YourServlet?param1=val1").
See also:
· What servlet code corresponds to the various "scope" values for the
<jsp:useBean> tag?
14. How to disable browser caching for a specific JSP?
Ans:It is possible to keep the browser from caching a JSP page response. The following hints added to the response header seem to prevent most modern browsers from pulling pages out of cache when the same URL is "hit":
<%
response.setHeader( "Pragma", "no-cache" );
response.setHeader( "Cache-Control", "no-cache" );
response.setDateHeader( "Expires", 0 );
%>
The same effect can be achieved by using meta tags in the HTML header:
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="Sat, 01 Dec 2001 00:00:00 GMT">
The Cache-Control header was added in HTTP 1.1, while the other two were also present in HTTP 1.0.
15. Write code to display a dropdown for countries given the countries in the form of a Map. JSTL and Scriptlets. Approach is observed.
16. Explain how to implement the "Delete Selected" from a "Tabular Data" which has check boxes. Use JSF or JSTL or Struts
17. What is the best practice regarding the use of scriptlets in JSP pages? Why? (Hint: Avoid)How can you avoid scriptlet code? (Hint:custom tags, Java beans)
18. What do you understand by the term JSP compilation? (Hint: compiles to servlet code)