Translate

Wednesday, January 1, 2014

JSP

Q1. Explain JSP model-1 and JSP model-2.
Ans.
JSP model-1: Generally for small projects. We use JSP for view and beans for business logic.
JSP model-2 (MVC architecture): For large projects. We use JSP+Servlet+Java Beans.


Q2. What are differnet JSP methods
Ans.
1. jspInit()
2. jspDestory()
3. _jspService()


As methods starting with '_' cann't be overridden, so you can't override _jspService() though you can override jspInit() and jspDestory().

Q3. How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default?
Ans. 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

1.) Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise. Ensure that all the methods in the Servlet interface are declared final.

2.) Additionally, your servlet superclass also needs to do the following:
a.) The service() method has to invoke the _jspService() method
b.) The init() method has to invoke the jspInit() method
c.) 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" %>

Q4. JSP implicit objects.
Ans. There are nine implicit objects. Here is the list of all the implicit objects: 


Object
Class
application
javax.servlet.ServletContext
config
javax.servlet.ServletConfig
request
javax.servlet.ServletRequest
response
javax.servlet.ServletResponse
session
javax.servlet.http.HttpSession
out
javax.servlet.jsp.JspWriter
pageContext
javax.servlet.jsp.pageContext
exception
java.lang.Throwable
page
java.lang.Object


Q5. JSP elements or type of JSP tags
Ans: SAD: Scripting, Actions and Directives

1. Scripting/Code Related tags: Declarations, Expressions, Scripting elements
a. declaration: (<%! ..... %>) or <jsp:declaration> variables or methods </jsp:declaration>
Everything written over here, becomes part of init() method. Variables declared inside declarations have servlet scope i.e they are declared/initialized in init method. So, you need to be careful while modifying them and these objects need to be serializable. As an alternative, if you don’t need multithreading, you can use <%@ page isThreadSafe=”false” %>. By default, it’s true.

b. expression: (<%= ... %> ) or <jsp:expression> java expression without semicolon </jsp:expression>. Its Part of service method.

c. scriplet: (<% ....%>) or <jsp:scriptlet> Java code</jsp:scriplet> (Later is available from JSP 2.0). However, variables declared inside scriplets are inserted in service method.

2. Actions:
a. forward: ex: 
<jsp:forward…>
b. include: ex: 
<jsp:include…> 
c. useBean
ex: <jsp:useBean..>

3. Directives: Denoted as <%@.....%>
a. page directive: ex: <%@ page import=”kjlj”>
b. include directive: 
<%@ include file=”abc”/>
c. taglib directive

Q6. What all tags a JSP is made up of?
Ans. A JSP is made up of
1. Display technology tags
2. JSP standard action tags
3. Custom tags

After that we have
1. JSP EL
2. JSTL

Q7. Difference b/w include directive and include action.
Ans: include directive and jsp:include are quite similar. But later one, instead of loading the text of the included file in the original file, it actually calls the included target at run-time (the way a browser would call the included target. In practice, this is actually a simulated request rather than a full round-trip between the browser and the server). 

Q8. What are the JSP atrributes?
Ans: attribute is a tag in a JSP page.
       <jsp:attribute name="attributeName" [ trim= "true | false" ] />

Below example generates an HTML header tag with a lang attribute:
<jsp:element name="${content.headerName}" xmlns:jsp="http://java.sun.com/JSP/Page">
      <jsp:attribute name="lang">abc</jsp:attribute>
      <jsp:body>xyz</jsp:body>
</jsp:element>


Q9. What is the difference between a JspWriter denoted by the “out” implicit object and the PrintWriter object obtained from response.getWriter() method?
Ans. JSPs should use the JspWriter denoted by the “out” implicit object for sending output back to the client. A JspWriter is a buffered version of the PrintWriter. JspWriter also differs from a PrintWriter by throwing java.io.IOException, which a PrintWriter does not. The advantage of throwing an exception is that if your HTTP connection is broken for some reason, your JSP won’t sit there trying to send characters to a broken connection.

Q10. Setting the content type in JSP Page.
Ans. Each JSP page starts with for html content
              <%@ page contentType="text/html”>


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

Q12. Explain hidden and output comments?
Ans: An output comment is a comment that is sent to the client where it is viewable in the browser’s source. On the other hand, a hidden comment documents a JSP page but does not get sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags.

Output comment
<!-- This is a comment which is sent to the client -->

Hidden Comment
<%-- This comment will not be visible to the client --%>


Q13. Is there a way to reference the "this" variable within a JSP page?
Ans. Yes, there is. The page implicit object is equivalent to "this", and returns a reference to the servlet generated by the JSP page

Q14. How do you prevent the creation of a session in a JSP Page and why?
Ans. Include this in the Jsp page if you want to avoid creating a session:
           <%@ page session= “false” >

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

Q15. When we increase the buffer size in our project using page directive attribute ‘buffer’ what changes we observe?

Ans. The default buffer size is 8k and when we increase the buffer size of the page using the buffer attribute of the page directive then the storage capacity will be increased. If the buffer size is too large then the performance will degrade. A larger buffer allows more content to be written before anything is actually sent back to the client, thus providing the JSP page with more time to set appropriate status codes and headers or to forward to another Web resource. A smaller buffer decreases server memory load and allows the client to start receiving data more quickly.

Instead of increasing the buffer size, use autoFlush true. By default the autoFlush is true only. So even the content which is to be send to the client crosses 8k, jsp doesn’t throws exception.

Q16. Is it compulsory to enable buffering?
Ans. No. But in cases, where a.jsp forwards to b.jsp, buffer must be enabled in a.jsp. This is because, if you set the buffer to "none" you will get the following error:
       java.lang.IllegalStateException: Illegal to clear() when buffer size == 0

Q17. What is the difference between buffer clear and buffer flush.
Ans.
Buffer clear: It's used in "jsp:forward". Here buffer is cleared and hence won't appear in forwarded page
Buffer flush: Used in "jsp:include". Here buffer is flushed, before request is sent to page to be included.


Q18. How do you handle errors in JSP?
Ans. Invalid jsp tag throws ParseException and syntax error gives JasperException. Use "isErrorPage" tag to indicate that jsp is an error page. This directive makes the exception object (of type javax.servlet.jsp.JspException) available to the error page, so that you can retrieve, interpret, and possibly display information about the cause of the exception in the error page. exception” is an implicit object accessible only within error pages i.e. the pages with directive <%@ page isErrorPage=”true” %>

<%@ page isErrorPage="true|false" %>
<body>
       <%= exception.getMessage() %>
</body>


// To send control to go to errorpage.jsp on error from abc.jsp, use the following:
<%@ page errorPage="errorpage.jsp" %>

Note: You must always use a relative URL as the “errorPage” attribute value. The above code redirects the browser client to the error.jsp page. Within your error.jsp page, you need to indicate that it is an error processing page with the “isErrorPage” attribute of the “page” directive as shown above.

Q19. How will you specify a global error page as opposed to using “errorPage” and “isErrorPage”attributes?
Ans. You could specify your error page in the web.xml deployment descriptor as shown below:

// by exception type
<error-page>
      <exception-type>java.lang.Throwable</exception-type
      <location>/error.jsp</location>
</error-page>

// by HTTP error codes
<error-page>
      <error-code>404</error-code>
      <location>/error404.html</location>
</error-page>

You could retrieve the java.lang.Throwable object within your error.jsp page as follows:
      <%= request.getAttribute("javax.servlet.error.exception") %>

Q20. What are the input types in html whose name-value pairs are not submitted to server.
Ans: For below input types, name value pairs are not submitted. Ex:
           input type = "button”
           input type ="reset"

Even input type="submit" gets submitted as name value pair.

Q21. Why do we need to specify action attribute in form tag.
Ans. In case, we don't specify action attribute, form gets submitted to itself only. If submission has to go to some other source, we have to specify the action attribute.

Ex: Let's say below in index.html
<form action = "WelcomeServlet" method="GET"> => Here form is submitted to WelcomeServlet

<form method="GET"> => Here form is submitted to index.html only.


Q22. How would you get the browser to request for an updated page in 10 seconds from the server?
Ans.
<%
      response.setHeader(“Refresh”, 10);

%>

Refresh does not stipulate continual updates. It just specifies in how many seconds the next update should take place. The “Refresh” header is very useful because it lets the servlet display a partial list of items or an introductory image to be displayed while the complete results or real page is displayed later (say in 10 seconds). You can also specify another page to be reloaded as follows:
       response.setHeader(“Refresh”, “10;URL=http://localhost:8080/myCtxt/crm.do”);

Above setting can be directly set in the <HEAD> section of the HTML page as shown below as opposed to setting it in the servlet. This is useful for static HTML pages.
  <META HTTP-EQUIV=”Refresh” CONTENT=”5; URL=http://localhost:8080/myCtxt/crm.do”/>

Q23. How do you prevent the HTML output of your JSP page being cached?

Ans.
<%
    response.setHeader(“Cache-Control”, “no=store”); //HTTP 1.1
    response.setDateHeader(“Expires”, 0);
%>

No comments:

Post a Comment