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

My Favorite Site's List

#update below script more than 500 posts