JSP Interview Questions & Answers

4 avg. rating (80% score) - 1 votes

JSP Interview Questions & Answers

Are you good at JSP (JavaServer Pages) topics? Looking for a great career opportunity in JSP? Then we have provided you the complete set of JSP (JavaServer Pages) Interview Question and Answers along with the various jobs role. We have provided all level of expertise interview questions in our site. JSP (JavaServer Pages) jobs provides you a great career. There are numerous number of jobs in the various leading companies with the job roles like Java Developer - Spring/jsp/weblogic, Java Developer(Freshers), Java Developer - JSP/Servlets, Java Developer - J2ee/jsp/servlets, Senior Software Engineer - Java/J2EE/JSP and many other roles too. To clear any job in the first attempt one should prepare well on all topics of JSP (JavaServer Pages). For more details visit our site www.wisdomjobs.com.

JSP Interview Questions

JSP Interview Questions
    1. Question 1. What Is A Jsp And What Is It Used For?

      Answer :

      Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page.

    2. Question 2. What Are The Two Kinds Of Comments In Jsp And What's The Difference Between Them ?

      Answer :

      <%-- JSP Comment --%>
      <!-- HTML Comment -->

    3. Question 3. What Is Jsp Technology?

      Answer :

      Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language.

    4. Question 4. What Is Jsp Page?

      Answer :

      A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.

    5. Question 5. What Are The Implicit Objects?

      Answer :

      Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are:
      --request
      --response
      --pageContext
      --session
      --application
      --out
      --config
      --page
      --exception

    6. Question 6. How Many Jsp Scripting Elements And What Are They?

      Answer :

      There are three scripting language elements:
      --declarations
      --scriptlets
      --expressions

    7. Question 7. Why Are Jsp Pages The Preferred Api For Creating A Web-based Client Program?

      Answer :

      Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.

    8. Question 8. Is Jsp Technology Extensible?

      Answer :

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

    9. Question 9. Can We Use The Constructor, Instead Of Init(), To Initialize Servlet?

      Answer :

      Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or Servlet Context.

    10. Question 10. How Can A Servlet Refresh Automatically If Some New Data Has Entered The Database?

      Answer :

      You can use a client-side Refresh or Server Push.

    11. Question 11. The Code In A Finally Clause Will Never Fail To Execute, Right?

      Answer :

      Using System.exit(1); in try block will not allow finally code to execute.

    12. Question 12. How Many Messaging Models Do Jms Provide For And What Are They?

      Answer :

      JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.

    13. Question 13. What Information Is Needed To Create A Tcp Socket?

      Answer :

      The Local Systems IP Address and Port Number. And the Remote System’s IPAddress and Port Number.

    14. Question 14. What Class.forname Will Do While Loading Drivers?

      Answer :

      It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.

    15. Question 15. How To Retrieve Warnings?

      Answer :

      SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object .

      SQLWarning warning = stmt.getWarnings();
      if (warning != null)
      {
      while (warning != null)
      {
      System.out.println(\"Message: \" + warning.getMessage());
      System.out.println(\"SQLState: \" + warning.getSQLState());
      System.out.print(\"Vendor error code: \");
      System.out.println(warning.getErrorCode());
      warning = warning.getNextWarning();
      }
      }

    16. Question 16. How Many Jsp Scripting Elements Are There And What Are They?

      Answer :

      There are three scripting language elements: declarations, scriptlets, expressions.

    17. Question 17. In The Servlet 2.4 Specification Singlethreadmodel Has Been Deprecated, Why?

      Answer :

      Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.

    18. Question 18. What Are Stored Procedures? How Is It Useful?

      Answer :

      A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements every time a query is run. Each database has its own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db’s support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases.

    19. Question 19. How Do I Include Static Files Within A Jsp Page?

      Answer :

      Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. 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.

    20. Question 20. Why Does Jcomponent Have Add() And Remove() Methods But Component Does Not?

      Answer :

      Because JComponent is a subclass of Container, and can contain other components and jcomponents. How can I implement a thread-safe JSP page? - You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" % > within your JSP page.

       

    21. Question 21. 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.

    22. Question 22. How Do You Restrict Page Errors Display In The Jsp Page?

      Answer :

      You first set "Errorpage" attribute of PAGE directory to the name of the error page (ie Errorpage= "error.jsp")in your jsp page .Then in the error jsp page set "isErrorpage=TRUE". When an error occur in your jsp page it will automatically call the error page.

    23. Question 23. 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:

    24. Question 24. 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. send Redirect ; 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.

    25. Question 25. How Does Jsp Handle Run-time Exceptions?

      Answer :

      You can use the errorPage attribute of the page directive to have uncaught runtime 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.

    26. Question 26. 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.

    27. Question 27. Is It Possible To Share An Httpsession Between A Jsp And Ejb? What Happens When I Change A Value In The Httpsession From Inside An Ejb?

      Answer :

      You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable. This has to be consider as "passed-by-value", that means that it's read-only in the EJB.

      If anything is altered from inside the EJB, it won't be reflected back to the HttpSession of the Servlet Container. The "pass-byreference" can be used between EJBs Remote Interfaces, as they are remote references.

      While it IS possible to pass an HttpSession as a parameter to an EJB object, it is considered to be "bad practice" in terms of object oriented design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejb's api. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end.

      Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction will be flexible enough to support it.

    28. Question 28. How Can I Implement A Thread-safe Jsp Page?

      Answer :

      You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" % > within your JSP page.

    29. Question 29. How Can I Declare Methods Within My Jsp Page?

      Answer :

      You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions.

      Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare.

      For example:
      Another Example:
      file1.jsp:
      file2.jsp
      <%test(out);% >

    30. Question 30. 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 (assuming Java is your scripting language) is to use the return statement when you want to terminate further processing.

    31. Question 31. Can A Jsp Page Process Html Form Data?

      Answer :

      Yes. However, unlike Servlet, 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.

    32. Question 32. 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.

    33. Question 33. Is There A Way I Can Set The Inactivity Lease Period On A Per-session Basis?

      Answer :

      Typically, a default inactivity lease period for all sessions is set within your JSPengine admin screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API, you 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.

    34. Question 34. How Does A Servlet Communicate With A Jsp Page?

      Answer :

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

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

      The JSP page Bean1.jsp can then process fBean, a fter 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" /

    35. Question 35. 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.

    36. Question 36. Can A Jsp Page Instantiate A Serialized Bean?

      Answer :

      No problem! The use Bean 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-INFjspbeans directory for it to be located by the JSP engine.

    37. Question 37. What Is Jsp?

      Answer :

      Let's consider the answer to that from two different perspectives: that of an HTML designer and that of a Java programmer.

      If you are an HTML designer, you can look at JSP technology as extending HTML to provide you with the ability to seamlessly embed snippets of Java code within your HTML pages. These bits of Java code generate dynamic content, which is embedded within the other HTML/XML content you author. Even better, JSP technology provides the means by which programmers can create new HTML/XML tags and JavaBeans components, which provide new features for HTML designers without those designers needing to learn how to program.

      Note: A common misconception is that Java code embedded in a JSP page is transmitted with the HTML and executed by the user agent (such as a browser). This is not the case. A JSP page is translated into a Java servlet and executed on the server. JSP statements embedded in the JSP page become part of the servlet generated from the JSP page. The resulting servlet is executed on the server. It is never visible to the user agent. If you are a Java programmer, you can look at JSP technology as a new, higher-level means to writing servlets. Instead of directly writing servlet classes and then emitting HTML from your servlets, you write HTML pages with Java code embedded in them. The JSP environment takes your page and dynamically compiles it. Whenever a user agent requests that page from the Web server, the servlet that was generated from your JSP code is executed, and the results are returned to the user.

    38. Question 38. How Do I Mix Jsp And Ssi #include? What Is The Difference Between Include Directive & Jsp:include Action?

      Answer :

      If you're just including raw HTML, use the #include directive as usual inside your .jsp file.

      <!--#include file="data.inc"-->
      

      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 <%@ vinclude="data.inc" %>

      The is used for including non-JSP files.

      include directive - <%@ include file="fileName" %> - as is the case with all other directives in a JSP page, this include directive is also processed at the time when the JSP page is translated into its equivalent servlet. This directive simply causes the contents of the specified file to be pasted into the JSP page at the place where the page contains this directive. Irrespective of whether the included resource is a static resource or a JSP page - only the contents of the file are pasted (and not the processed results). This directive is normally used for including static resources only - like, banner, header, footer, etc. for the obvious reason.

      include action -<jsp:include page="relativeURL"></jsp:include> this include action is executed at run time and the specified 'page' is first executed and then the result of that 'page' is appended to the response object of the calling JSP at the point where the tag occurs. Obviously if the specified page is a static resource then the contents of it are included as there won't be an executed result in that case. This action allows additional parameters to be passed via child element of this include action element.

    39. Question 39. How Do You Prevent The Creation Of A Session In A Jsp Page And Why? What Is The Difference Between Include Directive & Jsp:include Action?

      Answer :

      By default, a JSP page will automatically create a session for the request if one does not exist.
      However, sessions consume resources and if it is not necessary to maintain a session, one should not be created. For example, a marketing campaign may suggest the reader visit a web page for more information. If it is anticipated that a lot of traffic will hit that page, you may want to optimize the load on the machine by not creating useless sessions.

    40. Question 40. How Can I Set A Cookie And Delete A Cookie From Within A Jsp Page?

      Answer :

      A cookie, mycookie, can be deleted using the following scriptlet:

      <%//creating a cookieCookie mycookie = new Cookie("aName","aValue");
      response.addCookie(mycookie);
      //delete a cookieCookie killMyCookie = new Cookie("mycookie", null);
      killMyCookie.setMaxAge(0);killMyCookie.setPath("/");
      response.addCookie(killMyCookie);%>
      

    41. Question 41. How Do You Connect To The Database From Jsp?

      Answer :

      A Connection to a database can be established from a jsp page by writing the code to establish a connection using a jsp scriptlets.

      Further then you can use the resultset object "res" to read data in the following way.

    42. Question 42. What Is The Page Directive Is Used To Prevent A Jsp Page From Automatically Creating A Session?

      Answer :

      <%@ page session="false">

    43. Question 43. How Do You Delete A Cookie Within A Jsp?

      Answer :

      Cookie mycook = new Cookie("name","value");
      response.addCookie(mycook);
      Cookie killmycook = new Cookie("mycook","value");
      killmycook.setMaxAge(0);
      killmycook.setPath("/");
      killmycook.addCookie(killmycook);

    44. Question 44. Can We Implement An Interface In A Jsp?

      Answer :

      No

    45. Question 45. What Is The Difference Between Servletcontext And Pagecontext?

      Answer :

      ServletContext: Gives the information about the container
      PageContext: Gives the information about the Request.

    46. Question 46. 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.

    47. Question 47. How To Pass Information From Jsp To Included Jsp?

      Answer :

      Using <%jsp:param> tag.

    48. Question 48. How Is Jsp Include Directive Different From Jsp Include Action. ?

      Answer :

      When a JSP include directive is used, the included file's code is added into the added JSP page at page translation time, this happens before the JSP page is translated into a servlet. While if any page is included using action tag, the page's output is returned back to the added page. This happens at runtime.

    49. Question 49. Can We Override The Jspinit(), _jspservice() And Jspdestroy() Methods?

      Answer :

      We can override jspinit() and jspDestroy() methods but not _jspService().

    50. Question 50. Why Is _jspservice() Method Starting With An '_' While Other Life Cycle Methods Do Not?

      Answer :

      _jspService() method will be written by the container hence any methods which are not to be overridden by the end user are typically written starting with an '_'. This is the reason why we don't override _jspService() method in any JSP page.

    51. Question 51. What Happens When A Page Is Statically Included In Another Jsp Page?

      Answer :

      An include directive tells the JSP engine to include the contents of another file (HTML, JSP, etc.) in the current page. This process of including a file is also called as static include.

    52. Question 52. A Jsp Page, Include.jsp, Has A Instance Variable "int A", Now This Page Is Statically Included In Another Jsp Page, Index.jsp, Which Has A Instance Variable "int A" Declared. What Happens When The Index.jsp Page Is Requested By The Client?

      Answer :

      Compilation error, as two variables with same name can't be declared. This happens because, when a page is included statically, entire code of included page becomes part of the new page. at this time there are two declarations of variable 'a'. Hence compilation error.

    53. Question 53. Can You Override Jspinit() Method? If Yes, In Which Cases?

      Answer :

      yes, we can. We do it usually when we need to initialize any members which are to be available for a servlet/ JSP throughout its lifetime.

    54. Question 54. What Is The Difference Between Directive Include And Jsp Include?

      Answer :

      include directive :

      • The file gets included at the compile time.
      • it is static in nature.output comes with jsp page but whole file contains is included in jsp then compilation is done.

      action tag :

      • The file gets included at the run time. This is faster.
      • it is dynamic in nature.output of yhe file willbe included in the jsp file.

    55. Question 55. What Is The Difference Between Requestdispatcher And Sendredirect?

      Answer :

      RequestDispatcher: server-side redirect with request and response objects.

      sendRedirect : Client-side redirect with new request and response objects.

    56. Question 56. How Does Jsp Handle Runtime Exceptions?

      Answer :

      Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.

    57. Question 57. How Can My Application Get To Know When A Httpsession Is Removed?

      Answer :

      Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method.
      Create an instance of that class and put that instance in HttpSession.

    58. Question 58. What Is A 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 January 24, 2004 -->

    59. Question 59. 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 --%\>. 

      JSP Syntax
      <%-- comment --%>

      Examples
      <%@ page language="java" %>
      <html>
      <head><title>A Hidden Comment </title></head>
      <body>
      <%-- This comment will not be visible to the colent in the page source --%>
      </body>
      </html>

    60. Question 60. 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
      <%= someexpression %> 
      <%= (new java.util.Date()).toLocaleString() %>
      You cannot use a semicolon to end an expression.

    61. Question 61. 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. 
      <%! somedeclarations %>
      <%! int i = 0; %>
      <%! int a, b, c; %>

    62. Question 62. 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 <jsp:useBean> 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.

    63. Question 63. 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
      • request
      • response
      • pageContext
      • session
      • application
      • out
      • config
      • page
      • exception.

    64. Question 64. Difference Between Forward And Sendredirect?

      Answer :

      When you invoke a forward request, the request is sent to another resource ohe 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.

    65. Question 65. What Are The Different Scope Valiues For The ?

      Answer :

      The different scope values for <jsp:useBean> are
      1. page
      2. request
      3.session
      4.application.

    66. Question 66. 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 page 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.

    67. Question 67. 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.

    68. Question 68. What Is The Difference Between Jsp And Servlets ?

      Answer :

      JSP is used mainly for presentation only. A JSP can only be HttpServlet that means the only supported protocol in JSP is HTTP. But a servlet can support any protocol like HTTP, FTP, SMTP etc.

    69. Question 69. What Is Difference Between Custom Jsp Tags And Beans?

      Answer :

      Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components: the tag handler class that defines the tag's behavior ,the tag library descriptor file that maps the XML element names to the tag implementations and the JSP file that uses the tag library.

      JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags .

      Custom tags and beans accomplish the same goals -- encapsulating complex behavior into simple and accessible forms. There are several differences.

      Custom tags can manipulate JSP content; beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans. Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page. Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

    70. Question 70. What Are The Different Ways For Session Tracking?

      Answer :

      Cookies, URL rewriting, HttpSession, Hidden form fields.

    71. Question 71. What Mechanisms Are Used By A Servlet Container To Maintain Session Information?

      Answer :

      Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information.

    72. Question 72. Difference Between Get And Post?

      Answer :

      In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 255 characters, not secure, faster, quick and easy. The data is submitted as part of URL.

      In POST data is submitted inside body of the HTTP request. The data is not visible on the URL and it is more secure.

    73. Question 73. What Is Session?

      Answer :

      The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests. The session is stored on the server.

    74. Question 74. What Is Servlet Mapping?

      Answer :

      The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets.

    75. Question 75. What Is Servlet Context ?

      Answer :

      The servlet context is an object that contains a information about the Web application and container. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use.

    76. Question 76. What Is A Servlet ?

      Answer :

      servlet is a java program that runs inside a web container.

    77. Question 77. How Is Scripting Disabled?

      Answer :

      Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a sub element of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows:
      <jsp-property-group>
      <url-pattern>*.jsp</url-pattern>
      <scripting-invalid>true</scripting-invalid>
      </jsp-property-group>

    78. Question 78. What Is A Jsp Expression?

      Answer :

      A JSP expression is used to write an output without using the out.print statement. It can be said as a shorthand representation for scriptlets. An expression is written between the <%= and %> tags. It is not required to end the expression with a semicolon, as it implicitly adds a semicolon to all the expressions within the expression tags.

    79. Question 79. What Are Jsp Declarations?

      Answer :

      As the name implies, JSP declarations are used to declare class variables and methods in a JSP page. They are initialized when the class is initialized. Anything defined in a declaration is available for the whole JSP page. A declaration block is enclosed between the <%! and %> tags. A declaration is not included in theservice() method when a JSP is translated to a servlet.

    80. Question 80. What Is The Jsp:plugin Action ?

      Answer :

      This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the browser run an applet using the Java plugin.

    81. Question 81. What Are Scripting Elements?

      Answer :

      JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms:

      1. Expressionsof the form <%= expression %> that are evaluated and inserted into the output,
      2. Scriptletsof the form <% code %> that are inserted into the servlet's service method,
      3. Declarationsof the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods.

    82. Question 82. What Is The Standard Action?

      Answer :

      The <jsp:param> standard action is used with <jsp:include> or <jsp:forward> to pass parameter names and values to the target resource. The syntax of the <jsp:param> standard action is as follows: 
      <jsp:param name="paramName" value="paramValue"/>

    83. Question 83. What Is The Jsp:getproperty Action?

      Answer :

      The <jsp:getProperty> action is used to access the properties of a bean that was set using the <jsp:getProperty> action. The container converts the property to a String as follows:

      • If it is an object, it uses the toString() method to convert it to a String.
      • If it is a primitive, it converts it directly to a String using the valueOf() method of the corresponding Wrapper class.
      • The syntax of the <jsp:getProperty> method is: <jsp:getProperty name="Name" property="Property" />

      Here, name is the id of the bean from which the property was set. The property attribute is the property to get. A user must create or locate a bean using the <jsp:useBean> action before using the <jsp:getProperty> action.

    84. Question 84. Differentiate Between Pagecontext.include And Jsp:include?

      Answer :

      The <jsp:include> standard action and thepageContext.include() method are both used to include resources at runtime. However, thepageContext.include() method always flushes the output of the current page before including the other components, whereas<jsp:include> flushes the output of the current page only if the value = of flush is explicitly set to true as follows:
      <jsp:include page="/index.jsp" flush="true"/>

    85. Question 85. What Is The Standard Action?

      Answer :

      The <jsp:include> standard action enables the current JSP page to include a static or a dynamic resource at runtime. In contrast to the include directive, the include action is used for resources that change frequently. The resource to be included must be in the same context.The syntax of the <jsp:include> standard action is as follows:
      <jsp:include page="targetPage" flush="true"/> 
      Here, targetPage is the page to be included in the current JSP.

    86. Question 86. What Is The Standard Action?

      Answer :

      The <jsp:useBean> standard action is used to locate an existing JavaBean or to create a JavaBean if it does not exist. It has attributes to identify the object instance, to specify the lifetime of the bean, and to specify the fully qualified classpath and type.

    87. Question 87. What Are The Standard Actions Available In Jsp?

      Answer :

      The standard actions available in JSP are as follows:

      • <jsp:include>:It includes a response from a servlet or a JSP page into the current page.It differs from an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time.
      • <jsp:forward>:It forwards a response from a servlet or a JSP page to another page.
      • <jsp:useBean>:It makes a JavaBean available to a page and instantiates the bean.
      • <jsp:setProperty>:It sets the properties for a JavaBean.
      • <jsp:getProperty>:It gets the value of a property from a JavaBean component and adds it to the response.
      • <jsp:param>:It is used in conjunction with <jsp:forward>;, <jsp:, or plugin>; to add a parameter to a request. These parameters are provided using the name-value pairs.
      • <jsp:plugin>:It is used to include a Java applet or a JavaBean in the current JSP page.

       

    88. Question 88. What Are The Jsp Standard Actions?

      Answer :

      • The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client.
      • They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward a request to a new page, to generate a browser-specific code, etc.
      • Ex: include, forward, useBean,etc.

    89. Question 89. What Is The Include Directive?

      Answer :

      There are thirteen attributes defined for a page directive of which the importantattributes are as follows:
      • The include directive is used to statically insert the contents of a resource into the current JSP.
      • This enables a user to reuse the code without duplicating it, and includes the contents of the specified file at the translation time.
      • The syntax of the include directive is as follows:
      <%@ include file = "FileName" %>
      • This directive has only one attribute called file that specifies the name of the file to be included.

    90. Question 90. What Are The Attributes Of Page Directive?

      Answer :

      There are thirteen attributes defined for a page directive of which the important attributes are as follows:
      import: It specifies the packages that are to be imported.
      session: It specifies whether a session data is available to the JSP page.
      contentType: It allows a user to set the content-type for a page.
      isELIgnored: It specifies whether the EL expressions are ignored when a JSP is translated to a servlet.

    91. Question 91. What Is Page Directive?

      Answer :

      • A page directive is to inform the JSP engine about the headers or facilities that page should get from the environment.
      • Typically, the page directive is found at the top of almost all of our JSP pages.
      • There can be any number of page directives within a JSP page (although the attribute – value pair must be unique).
      • The syntax of the include directive is: <%@ page attribute="value">
      • Example:<%@ include file="header.jsp" %>

    92. Question 92. What Are Jsp Directives?

      Answer :

      • JSP directives are messages for the JSP engine. i.e., JSP directives serve as a message from a JSP page to the JSP container and control the processing of the entire page.
      • They are used to set global values such as a class declaration, method implementation, output content type, etc.
      • They do not produce any output to the client.
      • Directives are always enclosed within <%@ ….. %> tag.
      • Ex: page directive, include directive, etc.

    93. Question 93. What Are Advantages Of Jsp

      Answer :

      whenever there is a change in the code, we dont have to recompile the jsp. it automatically does the compilation. by using custom tags and tag libraries the length of the java code is reduced.

    94. Question 94. 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:useBean id="foo" >
      <jsp:setProperty name="foo" property="today"
      value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date())
      %>"/ >
      <%-- scriptlets calling bean setter methods go here --%>
      </jsp:useBean >

    95. Question 95. What Is The Page Directive Is Used To Prevent A Jsp Page From Automatically Creating A Session:

      Answer :

      <%@ page session="false">

    96. Question 96. What Are The Steps Required In Adding A Jsp Tag Libraries?

      Answer :

      Create a TLD file and configure the required class Information.
      Create the Java Implementation Source extending the JSP Tag Lib Class (TagSupport).
      Compile and package it as loosed class file or as a jar under lib folder in Web Archive File for Class loading.
      Place the TLD file under the WEB-INF folder.
      Add reference to the tag library in the web.xml file.

    97. Question 97. Outline The Major Difference Between The Session And Cookie?

      Answer :

      Sessions are always stored in the server side whereas cookies are always stored in the client side.

    98. Question 98. How Method Is Declared Within Jsp Page?

      Answer :

      Methods can be declared for use within JSP page as declaration and this method can be invoked within any other method which is declared or within JSP scriptlets or expressions. Direct access to the JSP implicit objects like request, response, session etc is forbidden within JSP methods but implicit Java server page variable is allowed to pass as parameters to the method which is declared.

    99. Question 99. Is It Possible By A Jsp Page To Process Html Form Data?

      Answer :

      Yes it is possible by simply obtaining the data from the FORM input via the request implicit object which lies with a scriptlet or expression but it doesn't require to implement any HTTP – Protocol methods like goGet() or doPost() within the JSP page.

    100. Question 100. How Cookies Is Deleted In Jsp?

      Answer :

      There are two ways by which the cookies can be deleted in JSP. Firstly, by setting the setMaxAge() of the cookie class to zero. And secondly by setting a timer in the header file that is response. setHeader(expires {Mention the time} attribute), which will delete the cookies after that prescribed time.

    101. Question 101. What Are Custom Tags And Why It Is Needed?

      Answer :

      JSP tags are extended by creating a custom set of tags which is called as tag library (taglib). The page which uses custom tags declares taglib and uniquely names, defines and associates a tag prefix to differentiate the usage of those tags.

    102. Question 102. Outline The Difference Between Java Server Page Forward And Servlet Forward Method?

      Answer :

      The only minor difference between both the methods is that Java Server page forward method can’t forward to another JSP page in another web application or container whereas servlet forward method can do so.

    103. Question 103. State The Difference Between The Expression And Scriptlet?

      Answer :

      JSP, Expressions is used to display the values of variable or to return the values by invoking the getter methods. However, JSP expressions begins with <> and does not have semicolon at the end of the expression. Scriptlet can contain variable, method or expressions that are valid within the page scripting language. Within the scripting tags and page scripting language any valid operations can be performed.

    104. Question 104. How A Run - Time Application Is Handled In Jsp?

      Answer :

      In JSP the errorpage attribute of the page is used as a directive to have uncaught run – time exceptions and which is automatically forwarded to an page which processes the error. If an uncaught exception is encountered while processing the request, then the browser redirects to the JSP error page.

    105. Question 105. What Is Declaration In Jsp?

      Answer :

      In Java Server pages Declaration is used to declare and define variables and methods that can be used in the Java Server Pages. The variable which is declared is initialized once and it retain its value for every subsequent client request.

    106. Question 106. How To Override The Lifecycle Methods Of Jsp?

      Answer :

      Lifecycle method jspService() cannot be overridden within a JSP page however methods like jspInit() and jspDestroy() can be overridden within a JSP page. Method jspInit() is used for allocating resource while method jspDestroy() is used to free allocated resource. But it should be kept in mind that during the lifecycle of a Java Server Page both the method jsplnit() and jspDestroy() is executed once and are declared as JSP declarations.

    107. Question 107. How Jsp Calls A Stored Procedure?

      Answer :

      Java Server Pages possess all the characteristics of java and to call and have similar syntax to call a function. Functions and stored procedures of a database can be called by using the statement callable. Another way to call the stored procedure is by writing the JDBC code in between the tag of scriptlet tab.write.

    108. Question 108. What Are The Implicit Objects In Jsp?

      Answer :

      There are all total 9 implicit objects in JSP. Application interface refers to the web application’s interface whereas Session interface refers to the user’s session. Request interface refers to the page which is currently requested whereas Response interface refers to the response which is currently made by the user. Config interface refers to the servlet configuration. Class like out, page, page Context and exception refers to the output stream of the page, servlet instance of the page, environment of the page, error handling respectively.

    109. Question 109. How Servlet Differ From Jsp?

      Answer :

      Both Servlet and Java Server Pages are API which generate dynamic web content. A servlet is nothing but a java class which implements the interface to run within a web and on the other hand Java server pages is a bit complicated thing which contain a mixture of Java scripts, Java directives, Java elements and HTML. The main difference among both servlet and Java server pages is that JSP is document oriented and servlet on the other hand act likes a program.

    110. Question 110. What Is Jsp? Describe Its Concept?

      Answer :

      JSP is a technology that combines HTML/XML markup languages and elements of Java programming Language to return dynamic content to the Web client, It is normally used to handle Presentation logic of a web application, although it may have business logic.

    111. Question 111. What Are The Lifecycle Phases Of A Jsp?

      Answer :

      JSP page looks like a HTML page but is a servlet. When presented with JSP page the JSP engine does the following 7 phases.
      1. Page translation: -page is parsed, and a java file which is a servlet is created.
      2. Page compilation: page is compiled into a class file
      3. Page loading : This class file is loaded.
      4. Create an instance :- Instance of servlet is created
      5. jspInit() method is called
      6. _jspService is called to handle service calls
      7. _jspDestroy is called to destroy it when the servlet is not required.

    112. Question 112. What Is A Translation Unit?

      Answer :

      JSP page can include the contents of other HTML pages or other JSP files. This is done by using the include directive. When the JSP engine is presented with such a JSP page it is converted to one servlet class and this is called a translation unit, Things to remember in a translation unit is that page directives affect the whole unit, one variable declaration cannot occur in the same unit more than once, the standard action jsp:useBean cannot declare the same bean twice in one unit.

    113. Question 113. How Is Jsp Used In The Mvc Model

      Answer :

      JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client.

    114. Question 114. What Are Context Initialization Parameters

      Answer :

      Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or JSP.

    115. Question 115. What's The 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 completely with in the web container And then returns to the calling method. When a sendRedirect 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 completely 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.

    116. Question 116. 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.

    117. Question 117. In The Servlet 2.4 Specification Singlethreadmodel Has Been Deprecates, Why?

      Answer :

      Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.

Jsp Tutorial

Jsp Practice Tests

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

JSP Tutorial