Showing posts with label jsp. Show all posts
Showing posts with label jsp. Show all posts

October 10, 2012

What will be the output of the following JSP code ?

Jsp Code:



<! int a =20>
<! int b = 30>
<%= b* a>




May be bellow answers suitable(chose any one):
(A) The code will not compile
(B) The value of b multiplied by a is 30
(C) The value of b multiplied by a is 300
(D) The value of b multiplied by a is 600
(E) The value of b multiplied by a is 0

Why The is the correct answer(s):
(C) The value of b multiplied by a is 300

Explanation:
Although the variable "a" is declared twice, the code should still compile as written. In the first declaration
 <% int a = 10; %>, the variable "a" will be declared as a local variable. In the second declaration 
<%! int a = 20; %>, the variable "a" will be declared as an instance variable, global to the translated servlet class.
Upon translation, the Container will translate the JSP code similar to the following:
public class ..._jsp
{
int a = 20;
int b = 30;
public void _jspService (....)
{
int a = 10;
out.write ("The value of b multiplied by a is ");
out.print (b * a);
}
Since the local variable "a" has precedence over the global variable "a", 
the expression (b * a) evaluates as (30 *10), which equals 300.

Reference: http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPIntro7.html
Read more ...

February 11, 2012

Jsp Interview Questions part1

1)What is a singleton class?How do you write it? Illustrate with an example?

A class which must create only one object (ie. One instance) irrespective of any number of object created based on that class.

Steps to develop single ton class:-

(i)Create a Private construtor, so that outside class can not access this constructor. And declare a private static reference of same class

(ii)Write a public Factory method which creates an object. Assign this object to private static Reference and return the object

Sample Code:-

class SingleTon
{
private static SingleTon st=null;

private SingleTon()
{
System.out.println(“\nIn constructor”);
}

public static SingleTon stfactory()
{
if(st==null)
st=new SingleTon();
return st;
}

}

2) What is the difference between using HttpSession & a Stateful Session bean? Why can't HttpSession be used instead of of Session bean?

HttpSession is used to maintain the state of a client in webservers which are based on Http protocol. Where as Stateful Session bean is a type of bean which can also maintain the state of the client in Application servers based on RMI-IIOP

3)What is Temporary Servlet?

When we send a request to access a JSP, servlet container internally creates a 'servlet' & executes it. This servlet is called as 'Temporary servlet'. In general this servlet will be deleted immediately. to create & execute a servlet base on a JSP we can used following command.

Java weblogic.jspc—keepgenerated *.jsp

4) Generally Servlets are used for complete HTML generation. If you want to generate partial HTML's that include some static text (this should not be hard coded in servlets) as well as some dynamic text, what method do you use?

Using 'RequestDispather.include(“xx.html”) in the servlet code we can mix the partial static HTDirectoryML page.

Ex:- RequestDispatcher rd=ServletContext.getRequestDispatcher(“xx.html”);
rd.include(request,response);

5)Difference between jsp:forward and jsp:include tags?

jsp:forward action tag redirect the servlet Request and Servlet Response to another resource specified in the tag. The path of the resource is 'relative path'. The output generated by current JSP will be discarded.

jsp:include action tag process the resource as part of the current jsp. It include the o/p generated by resource, which is specified in the Tag to the current JSP

(*) In both the cases single Request proceses multiple resources

6)Purpose of jsp:plugin tag

It is used to generate client browser specified HTML tags which results in download of the java plugin software. And the execution of the applet or java Bean component that is specified in the tag.

7)Which method is called first each time a Servlet is invoked?

When the servlet obj is not created init() method will be called. It servlet object already exists service() method will be called.

8)Why DB connections are not written directly in JSP's?

The main purpose of JSP is to seperate the business logic & presentation logic. DB connections deal with pure java code. If write this kind of code in JSP, servlet container converts the JSP to servlet using JSP compiler which is the time consuming process so this is better to write code wich deals with DB connections, Authentication and Authorization etc. in the java bean and use the tag to perform the action.

9)What is key diffrence between using an jsp:forward tag and HttpServletResponse.sendRedirect()?

Ans: The jsp:forward action tag allows the request to be forwarded to another resource (servlet/jsp/HTML) which are available in the same web-application (context).

Where as in the case of Response.sendRedirect() the request to be forwarded/redirected to another resource in the same web-application or some other web-application in the same server, or to a resource on some other web-server. The key difference is by using jsp:forward tag

single request from a browser can process multiple resources. Where as by using SendRedirect() multiple requests take place in order to process multiple resources.

10)Why beans are used in J2EE architecture instead of writing all the code in jsp's?

In order to seperate the business logic and presentation logic beans are used. We write the business logic in the Beans. Where there is a change in business process we have to modify only the bean code not jsp code and viceversa.

11)How can a servlet can call JSP error page?

By simply including an error-page tag in “web.xml” file

error-page
exception-type javax.servlet.ServletException /exception-type
location /error.jsp /location

the placement of the error file i.e /errorjsp.jsp within the location tags and then the end tag of error-page

By using Response.sendRedirect(“error.jsp”); or by using RequestDispatcher.forward(“error.jsp”); we can call jsp error page in servlet.

12)Explain MVC (Model-View-Controller) architecture?

MVC:- In model view controller design pattern, the software has split into 3 pieces.

MODEL-> Responsible for Managing Data-> Ex. Java Beans

VIEW-> Responsible for generating the views->Ex. Jsp's

CONTROLLER-> Responsible for user interactions & co-ordinate with MODEL &VIEW

13)what are JSP implicit Objects:-

out: used to send the content to the browser
ex: out.println(“xx”)

Response: Represent HttpServlet Reques

Response: Represent HttpServletResponse

Page Context: used to access the objects like session, servlet context, Request, Response etc...

Session: Points to HttpSession objects

Application: Points to servlet context objects

Page: Points to current servlet objects

Exception: Points to Exception

14)JSP Action Tags, Directive Tags & Scripting Tags?

Action Tag: These tags effect the runtime behaviour of the jsp page and the response set back to client tags are :

jsp: usebean tag : instantiates a new jsp bean class

jsp: setProperty tag : setting the properties at runtime

jsp:param tag : used to sending parameters

jsp:include tag : include a resource at runtime

jsp:forward tag: forward the control to specific resource

jsp:plugin tag : to plugin a web resource url applet

Directives:

These tags effect the overall structure of the servlet that result from translation. 3 types of directives are defined.

Page directive: used to define and manipulate the no. of page dependent attributes that effect the whole jsp.

include directive: This instructs the container to include the content of the resource in the current jsp this file is parsed once, when translation is done.

Taglib directive: To use tag extentions to define custom tags.

Scriptlets: There are used to include javacode in jsp page these are of 3 types

scriptlet: used to write pure java code

declarations: used to declare java variables and methods

Expressions: These send the value of a java expression back to client. These results are converted to string and displayed at client.

15) jsp:useBean tag and it's properties?

To separate the code from the presentation it would be good idea to encapsulate the code in java object instantiate it and use it in our jsp. This instance is varaible is called 'id'.We can also specific life time of this object by using 'scope' attribute

jsp:useBean id='name' scope=”scope” class=”beanclass”/

Properties:

id: a case sensitive name is used.

Scope: The scope with in which the reference is available. page, request,session, application are possible values page is default

class: the fully qulified classes name

beanname: The name of the java beanclass

type: This type must be super class of the beans classes

16)How do you implement Singe Thread Model in JSP?

By simply include a page directives tag

%@page isThreadSafe=”false” %

17)How do you declare a page as Error Page. What tag you include in a JSP page so that it goes to specified error page in case of an exception?

By including a page directive tag %@ page isErrorPage=”true”%

then this page is including a page directive in our jsp pages

%@page errorpage=”url of the above jsp”% tag

calling this page is including a page directive in our jsp page

%@page errorpage=”url of the above jsp”%

18)What is Request Dispatcher? How do you get it?

The name itself reveals that it is used to dispatch the control to requesting resource. It is an interface used to include any resource with in our servlet or forward the controler to any other resource. It contains two methods.

Forward(“---url”);

forward(“---url”);

For getting this we have a method in servlet context interface. So we can get it by servlet context object

sc.getRequestDispatcher();

19) Difference between JSP & Servlets?

Both are web applications used to produce web content that means dynamic web pages. Bot are used to take the requests and service the clients. The main difference between them is, In servlets both the presentation and business logic are place it together. Where as in jsp both are separated by defining java beans .

In jsp's the overall code is modulated so the developer who deesn't know about java can write jsp pages by simply knowing the additional tages and class names.

One more important to be considered is servlet take less time to compile. Jsp is a tool to simplify the process and make the process automate.

20)Difference between Hashtable & HashMap?

Hash table is a Collection of objects .To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. Hashtable is Sychronized and permit non- null values only.

Hashtable maps keys to values. Any non-null object can be used as a key or as a value.

The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.
Read more ...

Jsp Interview Questions part 2

21)What's the difference between the == operator and the equals() method? What test does
Object.equals() use, and why?
The == operator would be used, in an object sense, to see if the two objects were
actually the same object. This operator looks at the actually memory address to see if it
actually the same object. The equals() method is used to compare the values of the
object respectively. This is used in a higher level to see if the object values are equal.
Of course the the equals() method would be overloaded in a meaningful way for
whatever object that you were working with.

22)why do you create interfaces, and when MUST you use one.
You would create interfaces when you have two or more functionalities talking to each other. Doing it this
way help you in creating a protocol between the parties involved.

23)What is the difference between instanceof and isInstance?
instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class
exception.
isInstance()--Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a
ClassCastException. It returns false otherwise.

24)How many methods do u implement if implement the Serializable Interface?
The Serializable interface is just a "marker" interface, with no methods of its own to implement.
Are there any other 'marker' interfaces?
java.rmi.Remote
java.util.EventListener

25)Name four methods every Java class will have.
public String toString();
public Object clone();
public boolean equals();
public int hashCode();

26)What does the "abstract" keyword mean in front of a method? A class?
Abstract keyword declares either a method or a class. If a method has a abstract keyword in front of it,it is called abstract method.Abstract method hs no body.It has only arguments and return type.
Abstract methods act as placeholder methods that are implemented in the subclasses.Abstract classes can't be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class contains any abstract method it must be declared as abstract.

27)Does Java have destructors?
No garbage collector does the job working in the background

28)Are constructors inherited? Can a subclass call the parent's class constructor? When?
You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor of one of it's superclasses. One of the main reasons is because you probably don't want to overide the superclasses constructor, which would be possible if they were inherited. By giving the developer the ability to override a superclasses constructor you would erode the encapsulation abilities of the language.

29)What does the "final" keyword mean in front of a variable? A method? A class?
FINAL for a variable : value is constant
FINAL for a method : cannot be overridden
FINAL for a class : cannot be derived

30)Access specifiers: "public", "protected", "private", nothing?
Public – any other class from any package can instantiate and execute the classes and methods
Protected – only subclasses and classes inside of the package can access the classes and methods
Private – the original class is the only class allowed to executed the methods.

Read more ...

June 21, 2011

What is difference between page and pageContext in JSP pages?

The page and pageContext are implicit JSP Objects. The page object represents the generated servlet instance itself, i.e., it is same as the "this" keyword used in a Java file. As a result, you do not typically know who the super class is, and consequently do not normally make use of this object or its methods.
The pageContext object represents the environment for the page, containing useful information like page attributes, access to the requestresponse and session objects, as well as the JspWriter referenced by out. This object also has methods for including another URL's contents, and for forwarding or redirecting to another URL. For example, to forward a request to another resource from in a JSP page, we can do that by using the pageContextvariable:

pageContext.forward ("other.jsp"); 

Implicit ObjectClass or InterfacePurpose, Function, or Uses
pagejava.lang.ObjectRefers to the generated Servlet class. Since page refers to the generated class and the class implements the Servlet interface, it is a valid cast it to Servlet. And the page variable could also be cast to JspPage orHttpJspPage since these two interfaces are derived from the Servlet interface and are implemented by the generated servlet class. For example,
<%= ((Servlet)page).getServletInfo () %>
pageContextjavax.servlet. jsp.PageContextUsed for storing and retrieving page-related information and sharing objects within the same translation unit and same request.
Also used as a convenience class that maintains a table of all the other implicit objects. For example,
public void _jspService (
      HttpServletRequest request, 
      HttpServletResponse response
) throws java.io.IOException, 
ServletException { 

 ... 
    try { 

     ... 
   application = pageContext.getServletContext();
   config = pageContext.getServletConfig();
  session = pageContext.getSession();
   out = pageContext.getOut(); 
     ... 

    } catch (Throwable t) {
     ... 
    } finally {
     ... 
    }
}
Read more ...

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.
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 implementingSingleThreadModel through the admin screen for your JSP engine. 
Read more ...

June 07, 2011

Calling one jsp from another jsp

The above question is just like calling a method() in the java/c++/c classes. It will call the method() and after completion of method execution it will start execution of next instruction after the method call. It will be done in JSP by using 

pageContext.include("./nextjsppage.jsp");

when you use this statement the jsp page(nextjsppage.jsp) will include into our current jsp code.


OR


one.jsp
<%
------------
------
-------
RequestDispatcher rd=application.getRequestDispatcher("/two.jsp");
rd.include(request,response);
--------------
---------------
%>

two.jsp
<%-----
------
------
%>
Read more ...

Servlets™ and JSP™ Technologies FAQ

What are Servlets and how can they help in developing Web Applications?
"Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database. Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface.Servlets can be embedded in many different servers because the servlet API, which you use to write servlet assumes nothing about the server's environment or protocol. Servlets have become most widely used within HTTP servers; many web servers support the Servlet API. 


What is the Advantage of using Servlets over CGI programming?
Servlets are only instantiated when the client first accesses the program. That is, the first time any client hits the URL that is used to access the Servlet, the Servlet engine instantiates that object. All subsequent accesses are done to that instance. This keeps the response time of Servlets lower than that of CGI programs, which must be run once per hit. Also, because a Servlet is instantiated only once, all accesses are put through that one object. This helps in maintaining objects like internal Connection Pooling or user session tracking and lots of other features.
Here are a few more of the many applications for Servlets:
1. Allowing collaboration between people. A Servlet can handle multiple requests concurrently, and can synchronize requests. This allows Servlets to support systems such as on-line conferencing.
2. Forwarding requests. Servlets can forward requests to other servers and Servlets. Thus Servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.


What is the Jakarta Project ?
The goal of the Jakarta Project is to provide commercial-quality server solutions based on the Java Platform that are developed in an open and cooperative fashion. The flagship product, Tomcat, is a world-class implementation of the Java Servlet 2.2 and JavaServer Pages 1.1Specifications. This implementation will be used in the Apache Web Server as well as in other web servers and development tools." (The Apache Software Foundation). 


Where can i find a good tutorial and more details on Servlets?
These URL's are a good starting point if you want to know more about Servlets.
<!--[if !supportLists]-->§  <!--[endif]-->http://java.sun.com/products/servlet/
<!--[if !supportLists]-->§  <!--[endif]-->http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets.html
<!--[if !supportLists]-->§  <!--[endif]-->Developing Applications using Servlets (Tutorial)


How do I connect to a database from my Servlet?
Java includes support for databases, using Java Database Connectivity (JDBC). Most modern databases offer JDBC drivers, which allow you to connect any Java application (including Servlets) directly to your database.
If your database vendor does not offer a JDBC driver, and there are no third party drivers available, you may like to use a JDBC bridge. For example, the ODBC-JDBC bridge allows you to connect to any ODBC data source, which many databases support. Also there are four type of Drivers 
Type I   :   JDBC-ODBC bridge
Type II  :   native-API partly JavaTM technology-enabled driver
Type III :   net-protocol fully Java technology-enabled driver
Type IV :   native-protocol fully Java technology-enabled driver
For a list of currently available Database drivers, please visit this page http://industry.java.sun.com/products/jdbc/drivers
Creating a new Connection to Database frequently could slow down your application. Most of the projects use a concept called Connection Pooling. Here when the Servlet starts up, in the init method , a pool of connections are created and are stored in memory (Mostly in a Vector). When a transaction with Database is required, then the next free available connection is retrieved from this Vector and used for that purpose. Once it's work is done, it is again put back into Connections Pool, indicating it is available. Today most of the JDBC Drivers support this feature have inbuilt connection pooling mechanisms.
Please Note : If you are creating your own Connection Pooling, it is strongly recommended to close all the open connections in the destroy method. Else there are chances of your data getting corrupted.


How do I get authentication with myServlet?
Many popular Servlet engines offer Servlet authentication and the API has a call HttpServletRequest.getUserName() which is responsible for returning the username of an authenticated user.


What is a Session Object ? 
Session Object is used to maintain a user session  related information on the Server side. You can store , retrieve and remove information from a Session object according to your program logic. A session object created for each user persists on the server side, either until user closes the browser or user remains idle for the session expiration time, which is configurable on each server.


How to create Session object and use it for storing information ?
This code will get the Session context for the current user and place values of count1 and count2 into MyIdentifier1 and MyIdentifier2 respectively 
HttpSession session = req.getSession(true); //Creating a Session instance
session.putValue ("MyIdentifier1",count1);  // Storing Value into session Object
session.putValue ("MyIdentifier2", count2);  
session.getValue(MyIdentifier1); // Prints value of Count
session.removeValue(MyIdentifier1); // Removing Valuefrom Session Object


What is the Max amount of information that canbe saved in a Session Object ?
As such there is no limit on the amount of information that can be saved in a Session Object. Only the RAM available on the server machine is the limitation. The only limit is the Session ID length(Identifier) , which should not exceed more than 4K. If the data to be store is very huge, then it's preferred to save it to a temporary file onto hard disk, rather than saving it in session. Internally if the amount of data being saved in Session exceeds the predefined limit, most of the servers write it to a temporary cache on Hard disk. 


How to confirm that user's browser accepted the Cookie ? 
There's no direct API to directly verify that user's browser accepted the cookie. But the quick alternative would be, after sending the required data tothe users browser, redirect the response to a different Servlet which would try to read back the cookie. If this Servlet is able to read back the cookie, then it was successfully saved, else user had disabled the option to accept cookies. 



Read more ...

March 28, 2010

Brifly JSP Qustions

1. What is JSP  ? Describe its concept.
  Java Server Pages (JSP) is a server side component for the generation of dynamic information as the response. Best suitable to implement view components (presentation layer components). It is part of SUN’s J2EE platform.

2 . Explain the benefits of JSP?
These are some of the benefits due to the usage of JSP they are:
Portability, reusability and logic components of the language can be used across various platforms.
Memory and exception management.
Has wide range of API which increases the output functionality.
Low maintenance and easy deployment.
Robust performance on multiple requests.


3. Is JSP technology extensible?
Yes, it is. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
4 .Can we implement an interface in a JSP?
No
5 What are the advantages of JSP over Servlet?
  1. Best suitable for view components
  2. we can separate presentation and business logic
  3. The JSP author not required to have strong java knowledge
  4. If we are performing any changes to the JSP, then not required to recompile and reload explicitly
  5. We can reduce development time.
6. Differences between Servlets and JSP?
Servlets
JSP
1. Best suitable for processing logic 1. Best suitable for presentation logic
2. we cannot separate business and presentation logic 2. Separation of presentation and business logic is possible
3. Servlet developer should have strong knowledge in Java 3.JSP author is not required to have strong knowledge in Java
4. For source code changes ,we have to perform explicitly compilation 4. For source code changes ,it is not required to perform explicit compilation
5. Relatively development time is more 5. Relatively development time is less
7 . Explain the differences between ASP and JSP?

The big difference between both of these technologies lies with the design of the software. JSP technology is server and platform independent whereas ASP relies primarily on Microsoft technologies.
8 . Can I stop JSP execution while in the midst of processing a request?
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 we want to terminate further processing.
9. How to Protect JSPs from direct access ?
If the JSP is secured resource then we can place inside WEB-INF folder so that end user is not allowed to access directly by the name. We can provide the url pattern by configuring in web.xml
   
          Demo JSP
           /WEB-INF/test.jsp
   
       
             Demo JSP
             /test
       
            
..
10. Explain JSP API ?
The JSP API contains only one package : javax.servlet.jsp
 It contains the following 2 interfaces:
  1. JspPage:
         This interface defines the two life cycle methods jspInit() and jspDestroy().
  1. HttpJspPage:
This interface  defines only one life cyle method _jspService() method.
      Every generated servlet for the jsps should implement either JspPage or HttpJspPage interface either directly or indirectly.
11.  What are the lifecycle phases of a JSP?
Life cycle of JSP contains the following phases:
1.    Page translation: -converting from .jsp file to .java file
2.    Page compilation: converting .java to .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.

  
12.  Explain the life-cycle mehtods in JSP?
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
.
13. Difference between _jspService() and other life cycle methods.
JSP contains three life cycle methods namely jspInit( ), _jspService() and jspDestroy(). In these, jspInit() and jspDestroy() can be overridden and we cannot override _jspService().
Webcontainer always generate _jspService() method with JSP content. If we are writing _jspService() method , then generated servlet contains 2 _jspService() methods which will cause compile time error.
To show this difference _jspService() method is prefixed with ‘_’ by the JSP container and the other two methods jspInit() and jspDestroy() has no special prefixes.
14 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.

15. What is the _jspService() method?
SThe _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.

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

17.  What JSP lifecycle methods can I override?
We can override jspInit() and jspDestroy() methods but we cannot override _jspService() method.

18.  How can I override the jspInit() and jspDestroy() methods within a JSP page?
By using JSP declation tag
<%!
        public void jspInit() {
                . . .
        }
%>
<%!    
        public void jspDestroy() {
                . . .  
        }
%>
19 . Explain about translation and execution of Java Server pages?

A java server page is executed within a Java container. A Java container converts a Java file into a servlet. Conversion happens only once when the application is deployed onto the web server. During the process of compilation Java compiler checks for modifications if any modifications are present it would modify and then execute it.

20 . Why is _jspService() method starting with an '_' while other life cycle methods do not?

_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.
21.  How to pre-compile JSP?
Add jsp_precompile as a request parameter and send a request to the JSP file. This will make the jsp pre-compile.
http://localhost:8080/jsp1/test.jsp?jsp_precompile=true
It causes excution of JSP life cycle until jspInit() method without executing _jspService() method.
22. The benefits of pre-compiling a JSP page?
It removes the start-up lag that occurs when a container must translate a JSP page upon receipt of the first request.
23.How many JSP scripting elements and explain them?
 Inside JSP four types of scripting elements are allowed.
1. Scriptlet     <%  any java code    %>
     Can be used to place java code.
2. declarative     <%! Java declaration  %>
    Can be used to declare class level variables and methods
3. expression:   <%=  java expression %>
      To print java expressions in the JSP
4. comment   <%--   jsp comment  --%>
24. What is a Scriptlet?
JSP scriptlet can be used to place java code.
Syntax:
<%
    Any java code
%>
The java code present in the scriptlet will be placed directly inside _jspService() method .
25. What is a JSP declarative?
JSP declarations are used to declare class variables and methods (both instance and static)  in a JSP page. These declations will be placed directly at class level in the generated servlet and these are available to the entire JSP.
 Syntax:
      <%!    This is my declarative  %>
    Eg:    <%!  int j = 10;  %>
26. How can I declare methods within my JSP page?
We can declare methods by using JSP declarative tag.

<%!
public int add(inti,intj){
return i+j;
}
%>

27. What is the difference b/w variable declared inside a declaration  and variable declared in scriplet ?
           
Variable declared inside declaration part is treated as a instance variable and will be placed directly at class level in the generated servlet.
<%!  int  k = 10;  %>
Variable declared in a scriptlet will be placed inside _jspService() method of generated servlet.It acts as local variable.
<%
   int k = 10;
%>
What is a Expression?

JSP Expression can be used to print expression to the JSP.
Syntax:
  
<%=  java expression %>

Eg:       <%=  new java.util.Date()  %>
 The expression in expression tag should not ends with semi-colon
       
 The expression value will become argument to the out.pritln() method in the generated servlet
28.What are the three  kinds of comments in JSP and what's the difference between them?

Three types of comments are allowed in JSP
    1. JSP Comment:
<%--  this is jsp comment  --%>
This is also known as hidden comment and it is visible only in the JSP and in rest of phases of JSP life cycle it is not visible.
    1. HTML Comment:
This is also known as template text comment or output comment. It is visible in all phases of JSP including source code of generated response.
    1. Java Comments.
With in the script lets we can use even java comments .
<%
 // single line java comment
/* this is multiline comment  */
%>
This type of comments also known as scripting comments and these are visible in the generated servlet also.
29. What is  output comment?
  The comment which is visible in the source of the response is called output comment.
  
30. What is a Hidden Comment?
    
 <%--  this is jsp comment  --%>
This is also known as JSP comment and it is visible only in the JSP and in rest of phases of JSP life cycle it is not visible.
31. 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
   true
32.  What are the JSP implicit objects?
Implicit objects are by default available to the JSP. Being JSP author we can use these and not required to create it explicitly.
  1. request
  2. response
  3. pageContext
  4. session
  5. application
  6. out
  7. config
  8. page
  9. exception
33. 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:
<%@ 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:
<%@ page isErrorPage="true" %>
In the error pages we can access exception implicit object.
           
34. 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 in the JSP.
<%@ page isThreadSafe="false" %>
The generated servlet can handle only one client request at time so that we can make JSP as thread safe. We can overcome data inconsistency problems by this approach.
The main limitation is it may affect the performance of the system. 
35.  What is the difference between ServletContext and PageContext?
 ServletContext: Gives the information about the container and it represents an application. PageContext: Gives the information about the Request and it can provide all other implicit JSP objects .
36 . Is there a way to reference the "this" variable within a JSP page?

Yes, there is. The page implicit object is equivalent to "this", and returns a reference to the generated servlet.
37 . Can you make use of a ServletOutputStream object from within a JSP page?

Yes . By using getOutputStream() method on response implicit object we can get it.
38 .What is the page directive is used to prevent a JSP page from automatically creating a session?

session object is by default available to the JSP. We can make it unavailable by using page directive as follows.
<%@ page session="false">

39. What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
            Synchronized keyword is recommended to use to get thread-safety.
40.  What are various attributes Of Page Directive ?
        Page directive contains the following 13 attributes.
  1. language
  2. extends
  3. import
  4. session
  5. isThreadSafe
  6. info
  7. errorPage
  8. isError page
  9. contentType
  10. isELIgnored
  11. buffer
  12. autoFlush
  13. pageEncoding
41 . Explain about autoflush?

This command is used to autoflush the contents. If a value of true is used it indicates to flush the buffer whenever it is full. In case of false it indicates that an exception should be thrown whenever the buffer is full. If you are trying to access the page at the time of conversion of a JSP into servlet will result in error.
42.  How do you restrict page errors display in the JSP page?

You first set "errorPage" attribute of PAGE directive  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, then the control will be automatically forward to error page.

43. What are the different scopes available fos JSPs ?
There are four types of scopes are allowed in the JSP.
  1. page - with in the same page
  2. request - after forward or include also you will get the request scope data.
  3. session - after senRedirect also you will get the session scope data. All data stored in session is available to end user till session closed or browser closed.
  4. application - Data will be available throughout the application. One user can store data in application scope and other can get the data from application scope.
44. when do use application scope?
If we want to make our data available to the entire application then we have to use application scope.
45.  What are the different scope valiues for the ?
           
The different scope values for are
1. page
2. request
3.session
4.application
46. How do I use a scriptlet to initialize a newly instantiated bean?     
 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.

value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>" / >
<%-- scriptlets calling bean setter methods go here --%>
47 . Can a JSP page instantiate a serialized bean?

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-INF/jspbeans directory for it to be located by the JSP engine.

48.How do we include static files within a jsp page ?
We can include static files in JSP by using include directive (static include)
<%@ include file=”header.jsp” %>
       The content of the header.jsp will be included in the current jsp at translation time. Hence this inclusion is also known as static include.
49.In JSPs how many ways are possible to perform inclusion?
       In JSP, we can perform inclusion in the following ways.
      
  1. By include directive:
     <%@ include file=”header.jsp” %>
       The content of the header.jsp will be included in the current jsp at translation time. Hence this inclusion is also known as static include.
  1. By include action:
 
The response of the jsp will be included in the current page response at request processing time(run time) hence it is also known as dynamic include.
  1. by using pageContext implicit object
<%
  
   pageContext.include(“/header.jsp”);
%>
This inclusion also happened at request processing time(run time).
  1. by using RequestDispatcher object
 <%
 RequestDispatcher rd = request.getRequestDispatcher(“/header.jsp”);
  Rd.incliude(request,response);
%>
50.In which situation we can use static include and dynamic include in JSPs ?
If the target resource ( included resource) won’t change frequently, then it is recommended to use static include.
   <%@ include file=”header.jsp” %>
If the target resource(Included page)  will change frequently , then it is recommended to use dynamic include.
 < jsp:include page=”header.jsp” />


 

Read more ...

March 06, 2010

How to Set Path Tomcat and Java Classpath in Your PC?

---------
|EXECUTION|
---------

(1)-------------------------------------------------------------------

-----------------
|install softwares|
-----------------

java 1.5/1.4

tomcat 5.5/5.0 --default port number-->8080(any 4 digit number)

oracle 9i


(2)-------------------------------------------------------------------

------------
|PATH setting|
------------

-->Right click on my computer-->Advanced-->Environment Variables-->
system variables->click 'NEW' and add the varible name and values

variable name - path
variable value - D:\j2sdk1.4.2_04\bin;
D:\oracle\ora92\bin----ok


variable name - classpath
variable value - D:\j2sdk1.4.2_04\jre\lib\rt.jar;
D:\j2sdk1.4.2_04\lib\tools.jar;
D:\Tomcat 5.5\common\lib\servlet-api.jar;


variable name - JAVA_HOME
variable value - D:\j2sdk1.4.2_04


variable name - CATALINA_HOME
varrable value - D:\Tomcat 5.5


(3)-------------------------------------------------------------------

------------------
|Project Deployment|
------------------

please paste your project in below path

-->tomcat5.5\webapps\.....[your appliction(project)]


(4)-------------------------------------------------------------------

------------------------------
|Creation of new user in oracle|
------------------------------

cmd1: create user username identified by password;
-------- --------

cmd2: grant resource,connect to username; Exit
--------

please paste your tables in newly created ORACLE account.


(5)-------------------------------------------------------------------

------------
|DSN Creation|
------------

-->Start-->settings-->control pannel-->Administrtive tools--> datasources(ODBC)-->system DSN-->add-->microsoft ODBC for oracle-->
finish-->OK


(6)-------------------------------------------------------------------

------------
|start tomcat|
------------

-->tomcat5.5\bin\tomcat5.exe(double click)


(7)-------------------------------------------------------------------

---------
|Execution|
---------

1.open Browser(internetexplorer)

2.http://localhost:8080/projectname(which is stored in web apps)

----------------------------------------------------------------------
Read more ...

My Favorite Site's List

#update below script more than 500 posts