JSP Interview Questions and Answers
Last updated on 23rd Oct 2020, Blog, Interview Question
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.
1. What Is A Jsp And What Is It Used For?
Ans:
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. What Are The Two Kinds Of Comments In Jsp And What’s The Difference Between Them ?
Ans:
- <%– JSP Comment –%>
- <!– HTML Comment –>
3. What Is Jsp Technology?
Ans:
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. What Is Jsp Page?
Ans:
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. What Are The Implicit Objects?
Ans:
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
6. How Many Jsp Scripting Elements And What Are They?
Ans:
There are three scripting language elements:
1. declarations
2. scriptlets
3. expressions
7. Why Are Jsp Pages The Preferred Api For Creating A Web-based Client Program?
Ans:
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. Is Jsp Technology Extensible?
Ans:
YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
9. Can We Use The Constructor, Instead Of Init(), To Initialize Servlet?
Ans:
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 constructor 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. How Can A Servlet Refresh Automatically If Some New Data Has Entered The Database?
Ans:
You can use a client-side Refresh or Server Push.
11. The Code In A Finally Clause Will Never Fail To Execute, Right?
Ans:
Using System.exit(1); in try block will not allow finally code to execute.
12. How Many Messaging Models Do Jms Provide For And What Are They?
Ans:
JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.
13. What Information Is Needed To Create A Tcp Socket?
Ans:
The Local Systems IP Address and Port Number. And the Remote System’s IPAddress and Port Number.
14. What Class.forname Will Do While Loading Drivers?
Ans:
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.
Subscribe For Free Demo
Error: Contact form not found.
15. How To Retrieve Warnings?
Ans:
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. How Many Jsp Scripting Elements Are There And What Are They?
Ans:
There are three scripting language elements: declarations, scriptlets, expressions.
17. In The Servlet 2.4 Specification Singlethreadmodel Has Been Deprecated, Why?
Ans:
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. What Are Stored Procedures? How Is It Useful?
Ans:
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 preprocessor. 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.How Do I Include Static Files Within A Jsp Page?
Ans:
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. Why Does Jcomponent Have Add() And Remove() Methods But Component Does Not?
Ans:
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. How Do I Prevent The Output Of My Jsp Or Servlet Pages From Being Cached By The Browser?
Ans:
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. How Do You Restrict Page Errors Display In The Jsp Page?
Ans:
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. What Jsp Lifecycle Methods Can I Override?
Ans:
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. How Do I Perform Browser Redirection From A Jsp Page?
Ans:
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 believe this is the case with the response.sendRedirect() method as well. If you want to pass any parameters then you can pass using.
25. How Does Jsp Handle Run-time Exceptions?
Ans:
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. How Do I Use Comments Within A Jsp Page?
Ans:
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. 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?
Ans:
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-by reference” 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. How Can I Implement A Thread-safe Jsp Page?
Ans:
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. How Can I Declare Methods Within My Jsp Page?
Ans:
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:
- file1.jsp:
- file2.jsp
- <%test(out);% >
30. Can I Stop Jsp Execution While In The Midst Of Processing A Request?
Ans:
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. Can A Jsp Page Process Html Form Data?
Ans:
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. Is There A Way To Reference The “this” Variable Within A Jsp Page?
Ans:
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. Is There A Way I Can Set The Inactivity Lease Period On A Per-session Basis?
Ans:
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. How Does A Servlet Communicate With A Jsp Page?
Ans:
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. Can You Make Use Of A Servletoutputstream Object From Within A Jsp Page?
Ans:
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. Can A Jsp Page Instantiate A Serialized Bean?
Ans:
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. What Is Jsp?
Ans:
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. How Do I Mix Jsp And Ssi #include? What Is The Difference Between Include Directive & Jsp:include Action?
Ans:
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. 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?
Ans:
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. How Can I Set A Cookie And Delete A Cookie From Within A Jsp Page?
Ans:
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. How Do You Connect To The Database From Jsp?
Ans:
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. What Is The Page Directive Is Used To Prevent A Jsp Page From Automatically Creating A Session?
Ans:
- <%@ page session=”false”>
43. How Do You Delete A Cookie Within A Jsp?
Ans:
- Cookie mycook = new Cookie(“name”,”value”);
- response.addCookie(mycook);
- Cookie killmycook = new Cookie(“mycook”,”value”);
- killmycook.setMaxAge(0);
- killmycook.setPath(“/”);
- killmycook.addCookie(killmycook);
44. Can We Implement An Interface In A Jsp?
Ans:
No
45. What Is The Difference Between Servletcontext And Pagecontext?
Ans:
ServletContext: Gives the information about the container
PageContext: Gives the information about the Request.
46. What Is The Difference In Using Request.getrequestdispatcher() And Context.getrequestdispatcher()?
Ans:
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. How To Pass Information From Jsp To Included Jsp?
Ans:
Using <%jsp:param> tag.
48. How Is Jsp Include Directive Different From Jsp Include Action?
Ans:
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. Can We Override The Jspinit(), _jspservice() And Jspdestroy() Methods?
Ans:
We can override jspinit() and jspDestroy() methods but not _jspService().
50. Why Is _jspservice() Method Starting With An ‘_’ While Other Life Cycle Methods Do Not?
Ans:
_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. What Happens When A Page Is Statically Included In Another Jsp Page?
Ans:
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. 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?
Ans:
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. Can You Override Jspinit() Method? If Yes, In Which Cases?
Ans:
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. What Is The Difference Between Directive Include And Jsp Include?
Ans:
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. What Is The Difference Between Requestdispatcher And Sendredirect?
Ans:
1.RequestDispatcher: server-side redirect with request and response objects.
2.sendRedirect : Client-side redirect with new request and response objects.
56. How Does Jsp Handle Runtime Exceptions?
Ans:
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. How Can My Application Get To Know When A Httpsession Is Removed?
Ans:
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. What Is A Output Comment?
Ans:
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 comment sent to client on January 24, 2004 –>
59. What Is A Hidden Comment?
Ans:
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. What Is A Expression?
Ans:
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
- <%= some expression %>
- <%= (new java.util.Date()).toLocaleString() %>
- You cannot use a semicolon to end an expression.
61. What Is A Declaration?
Ans:
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. What Is A Scriptlet?
Ans:
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
- Declare variables or methods to use later in the file (see also Declaration).
- Write expressions valid in the page scripting language (see also Expression).
- 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. What Are Implicit Objects? List Them?
Ans:
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. Difference Between Forward And Sendredirect?
Ans:
When you invoke a forward request, the request is sent to another resource the server, without the client being informed that a different resource is going to process the request. This process occurs completely within the web container. 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.
65. What Are The Different Scope Values For The ?
Ans:
The different scope values for <jsp:useBean> are
- page
- request
- session
- application.
66. Explain The Life-cycle Methods In Jsp?
Ans:
The generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. The HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of these three interfaces. The JspPage interface declares only two methods – jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interface specifically for the JSp pages serving HTTP requests.
This interface declares one method_jspService().
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. What’s A Better Approach For Enabling Thread-safe Servlets And Jsps? Singlethreadmodel Interface Or Synchronization?
Ans:
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 synchronized 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. What Is The Difference Between Jsp And Servlets ?
Ans:
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. What Is Difference Between Custom Jsp Tags And Beans?
Ans:
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. What Are The Different Ways For Session Tracking?
Ans:
Cookies, URL rewriting, HttpSession, Hidden form fields.
71. What Mechanisms Are Used By A Servlet Container To Maintain Session Information?
Ans:
Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information.
72. Difference Between Get And Post?
Ans:
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. What Is Session?
Ans:
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. What Is Servlet Mapping?
Ans:
The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to Servlets.
75. What Is Servlet Context ?
Ans:
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. What Is A Servlet ?
Ans:
Servlet is a java program that runs inside a web container.
77. How Is Scripting Disabled?
Ans:
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. What Is A Jsp Expression?
Ans:
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. What Are Jsp Declarations?
Ans:
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. What Is The Jsp:plugin Action ?
Ans:
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. What Are Scripting Elements?
Ans:
JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms:
Expressions Of the form <%= expression %> that are evaluated and inserted into the output,
Scriptlets Of the form <% code %> that are inserted into the servlet’s service method,
Declarations Of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods.
82. What Is The Standard Action?
Ans:
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. What Is The Jsp:getproperty Action?
Ans:
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. Differentiate Between Pagecontext.include And Jsp:include?
Ans:
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. What Are The Standard Actions Available In Jsp?
Ans:
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.
86. What Are The Jsp Standard Actions?
Ans:
- 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.
87. What Is The Include Directive?
Ans:
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.
88. What Are The Attributes Of Page Directive?
Ans:
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.
89. What Is Page Directive?
Ans:
- 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” %>
90. What Are Jsp Directives?
Ans:
- 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.
91. What Are Advantages Of Jsp?
Ans:
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.
92. How Do I Use A Scriptlet To Initialize A Newly Instantiated Bean?
Ans:
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 >
93. What Are The Steps Required In Adding A Jsp Tag Libraries?
Ans:
- 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.
94. Outline The Major Difference Between The Session And Cookie?
Ans:
Sessions are always stored in the server side whereas cookies are always stored in the client side.
95. How Method Is Declared Within Jsp Page?
Ans:
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.
96. Is It Possible By A Jsp Page To Process Html Form Data?
Ans:
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.
97. How Cookies Are Deleted In Jsp?
Ans:
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 the response. setHeader(expires {Mention the time} attribute), which will delete the cookies after that prescribed time.
Are you looking training with Right Jobs?
Contact Us- AngularJS Interview Questions and Answers
- Dot Net Interview Questions and Answers
- jQuery Interview Questions and Answers
- Java Interview Questions and Answers
Related Articles
Popular Courses
- Java Training
11025 Learners
- Dot Net Training
12022 Learners
- Angular Training
11141 Learners
- What is Dimension Reduction? | Know the techniques
- Difference between Data Lake vs Data Warehouse: A Complete Guide For Beginners with Best Practices
- What is Dimension Reduction? | Know the techniques
- What does the Yield keyword do and How to use Yield in python ? [ OverView ]
- Agile Sprint Planning | Everything You Need to Know