You are on page 1of 10

SP Questions What is JSP?

Java Server Pages technology (JSP) is used to create dynamic web page.It is an extension to the servlet.A JSP is internally converted into servlet.
What is the life-cycle of JSP?

When a request is mapped to a JSP page for the first time, it translates the JSP page into a servlet class and compiles the class. It is this servlet that services the client requests. A JSP page has seven phases in its lifecycle, as listed below in the sequence of occurrence: Translation Compilation Loading the class Instantiating the class jspInit() invocation _jspService() invocation jspDestroy() invocation
What is the jspInit() method?

The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method of servlets. This method is invoked by the container only once when a JSP page is initialized. It can be overridden by a page author to initialize resources such as database and network connections, and to allow a JSP page to read persistent configuration data.
What is the _jspService() method?

The _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new request comes to a JSP page. This method takes the HttpServletRequest and HttpServletResponse objects as its arguments. A page author cannot override this method, as its implementation is provided by the container.
What is the jspDestroy() method?

The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container when a JSP page is about to be destroyed. This method is similar to the destroy() method of servlets. It can be overridden by a page author to perform any cleanup operation such as closing a database connection.
What JSP lifecycle methods can I override?

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().
What is a output comment?

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 ? 1 2 3 4 5 6 7 8 9 <!-- comment [ <%= expression %> ] --> Example <!-- This is a commnet sent to client on <%= (newjava.util.Date()).toLocaleString() %> --> Displays in the page source: <!-- This is a commnet sent to client on January24,2013-->

What is a Hidden Comment?

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 --%> 1 2 Examples 3 <%@ page language="java" %> 4 5 <%-- This comment will not be visible to the colent in the page source --%> 6
What is difference between hide comment and output comment?

The jsp comment is called hide comment whereas html comment is called output comment.If user views the source of the page, the jsp comment will not be shown whereas html comment will be shown.
What is a Expression?

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 %> 1 <%= (newjava.util.Date()).toLocaleString() %> 2

You cannot use a semicolon to end an expression


What is a Declaration?

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 %> 1 <%!inti =0; %> 2 <%!inta, b, c; %> 3
What is a Scriptlet?

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.
What are implicit objects? List them?

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 o o o o o o o o o request response pageContext session application out config page exception

Difference between forward and sendRedirect?

When you invoke a forward request, the request is sent to another resource on the server,

without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
How can I override the jspInit() and jspDestroy() methods within a JSP page?

The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations: ? 1 2 3 4 5 6 7 8 9 1 0

<%! publicvoidjspInit() { ... } %> <%! publicvoidjspDestroy() { ... } %>

What is page directive?

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"> 1 Example:<%@ include file="header.jsp" %> 2
What are the attributes of page directive?

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.

What is the include directive?

There are thirteen attributes defined for a page directive of which the important attributes 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: ? 1 <%@ include file ="FileName"%> This directive has only one attribute called file that specifies the name of the file to be included.
What are the JSP standard actions?

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. Examples: include, forward, useBean,etc. object
What are the standard actions available in JSP?

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: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.
What is the <jsp:useBean> standard action?

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.
What are the scopes available in <jsp:useBean>?

The scopes available in <jsp:useBean> are as follows:

page scope:

It specifies that the object will be available for the entire JSP page but not outside the

page. It specifies that the object will be associated with a particular request and exist as long as the request exists. application scope: It specifies that the object will be available throughout the entire Web application
request scope:

but not outside the application. session scope: It specifies that the object will be available throughout the session with a particular client.
What is the <jsp:forward> standard action?

The <jsp:forward>standard action forwards a response from a servlet or a JSP page to another page. The execution of the current page is stopped and control is transferred to the forwarded page. The syntax of the<jsp:forward>standard action is : <jsp:forward page="/targetPage" /> Here, targetPage can be a JSP page, an HTML page, or a servlet within the same context. If anything is written to the output stream that is not buffered before <jsp:forward>, an IllegalStateException will be thrown. Note : Whenever we intend to use <jsp:forward> or <jsp:include> in a page, buffering should be enabled. By default buffer is enabled.
What is the <jsp:include> standard action?

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.
Difference Between include Directive and include Action of JSP Include Directive
include directive is processed at the translation time include directive can use relative or absolute path Include directive can only include contents of resource it will not process the dynamic resource

Include Action
Include action is processed at the run time. Include action always use relative path Include action process the dynamic resource and result will be added to calling JSP Here we can pass other parameter also using

We can not pass any other parameter JSP:param We cannot pass any request or response object to calling In this case its possible. jsp to included file or JSP or vice versa

How can one Jsp Communicate with Java file.

we have import tag ? 1 <%@ pageimport="market.stock.* %> like this we can import all the java file to our jsp and use them as a regular class another way is servlet can send the instance of the java class to our jsp and we can retrieve that object from the request obj and use it in our page.
How do I prevent the output of my JSP or Servlet pages from being cached by the browser?

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. ? <% 1 response.setHeader("Cache-Control","no-store");//HTTP 1.1 2 response.setHeader("Pragma\","no-cache");//HTTP 1.0 3 response.setDateHeader ("Expires",0);//prevents caching at the proxy server 4 %> 5
How is scripting disabled?

Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a subelement of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows: ? <jsp-property-group> 1 <url-pattern>*.jsp 2 <scripting-invalid>true 3 </jsp-property-group> 4
How does JSP handle run-time exceptions?

You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example: ? 1 <%@ page errorPage=\"error.jsp\" %> 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:

? 1 <%@ page isErrorPage=\"true\" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.
How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?

You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive ? 1 <%@ page isThreadSafe="false"% > within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe .
How do I use a scriptlet to initialize a newly instantiated bean?

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"class="com.Bar.Foo"> 1 <jsp:setProperty name="foo"property="today" 2 value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>"/ > 3 4 <%-- scriptlets calling bean setter methods go here --%> 5 6 </jsp:useBean > 7

How can I set a cookie and delete a cookie from within a JSP page?

- A cookie, mycookie, can be deleted using the following scriptlet: ? 1 2 3 4 5 6 7 8 9 1 0 1 1

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

How can I get to print the stacktrace for an exception occuring within my JSP page?

- By printing out the exceptions stack trace, you can usually diagonse a problem better when debugging JSP pages. By looking at a stack trace, a programmer should be able to discern which method threw the exception and which method called that method. However, you cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. following snippet demonstrates how you can print a stacktrace from within a JSP error page: ? <%@ page isErrorPage="true"%> 1 <% 2 out.println(" "); 3 PrintWriter pw = response.getWriter(); 4 exception.printStackTrace(pw); 5 out.println(" "); 6 %> 7
How do you pass an InitParameter to a JSP?

- The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and prints them to the console. ? 1 <%@ pageimport="java.util.*"%> 2 <%! 3 ServletConfig cfg =null; 4 publicvoidjspInit(){

5 6 7 8 9 1 0 1 1 1 2

ServletConfig cfg=getServletConfig(); for(Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) { String name=(String)e.nextElement(); String value = cfg.getInitParameter(name); System.out.println(name+"="+value); } } %>

You might also like