Jsp18 07/10/2008

What is the difference between JSP and Servlets ?

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.

What is difference between custom JSP tags and beans?

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

What is servlet mapping?

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

Can we use the constructor, instead of init(), to initialize servlet?

Yes. But you will not get the servlet specific things from constructor. 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 ServletConfig or ServletContext.

How many JSP scripting elements are there and what are they?

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

Jsp17 07/10/2008

What is a translation unit?

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

How is JSP used in the MVC model?

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

What are context initialization parameters?

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

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

Jsp16 07/10/2008

How do I have the JSP-generated servlet subclass my own custom servlet
class, instead of the default?

One should be very careful when having JSP pages extend custom servlet
classes as opposed to the default one generated by the JSP engine.
In doing so, you may lose out on any advanced optimization that may
be provided by the JSP engine. In any case, your new superclass has
to fulfill the contract with the JSP engine by:
Implementing the HttpJspPage interface, if the protocol used is HTTP,
or implementing JspPage otherwise Ensuring that all the methods in the
Servlet interface are declared final Additionally, your servlet
superclass also needs to do the following:

The service() method has to invoke the _jspService() method
The init() method has to invoke the jspInit() method
The destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may
throw a translation error.
Once the superclass has been developed, you can have your JSP extend it
as follows:

<%@ page extends="packageName.ServletName" %>

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.

<%@ page import="java.util.*" %>
ServletConfig cfg =null;
public void jspInit(){
ServletConfig cfg=getServletConfig();
for (Enumeration e=cfg.getInitParameterNames();
e.hasMoreElements();) {
String name=(String)e.nextElement();
String value = cfg.getInitParameter(name);

Can we implement an interface in a JSP?


What is the difference between ServletContext and PageContext?

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

How do I mix JSP and SSI #include?

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

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
<%@ include="data.inc" %>
The is used for including non-JSP files.

Jsp15 07/10/2008

What are the common mechanisms used for session tracking?

SSL sessions
URL- rewriting

What is preinitialization of a servlet?

A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

What is the difference between HttpServlet and GenericServlet?

A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1).
Both these classes are abstract.

What is the difference between ServletContext and ServletConfig?

ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized

ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet

Jsp14 07/10/2008

What are the different scope valiues for the ?
The different scope values for are
1. page
2. request

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. <%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server

How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values?

You could make a simple wrapper function, like

String blanknull(String s) {
return (s == null) ? \"\" : s;

then use it inside your JSP form, like

" >

What is the difference b/w variable declared inside a declaration part and variable declared in scriplet part?

Variable declared inside declaration part is treated as a global variable.that means after convertion jsp file into servlet that variable will be in outside of service method or it will be declared as instance variable.And the scope is available to complete jsp and to complete in the converted servlet class.where as if u declare a variable inside a scriplet that variable will be declared inside a service method and the scope is with in the service method.

Is there a way to execute a JSP from the comandline or from my own application?

There is a little tool called JSPExecutor that allows you to do just that. The developers (Hendrik Schreiber & Peter Rossbach ) aim was not to write a full blown servlet engine, but to provide means to use JSP for generating source code or reports. Therefore most HTTP-specific features (headers, sessions, etc) are not implemented, i.e. no reponseline or header is generated. Nevertheless you can use it to precompile JSP for your website

Jsp13 07/10/2008

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

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

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

<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression

What is a declration?
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 %>

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 tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.

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

Jsp12 07/10/2008

How to overwrite the init and destroy method in a jsp page.

We can overwrite the init method in a jsp page by using declaration tag in our JSP page.

Where do we use hidden variables and url rewriting? and what is the difference between them?

Both hidden variable and URL rewriting are used for session tracking. The only advantage in hidden variable is that the URL looks neat. In URL rewriting, each and every variable is added to the URL (called GET parameters).Example: profile.jsp?name=dilip+surname=iyer

What is the difference between session and cookie ?

Sessions are stored in the server side whereas cookies are stored in the client side2. There is a limit to the number of cookies that can be stored with respect to session

What is the difference betweeen JSP forward and servlet forward methods?

JSP forward forwards the control to another resource available in the same web application on the same container..where as Servlet forward forwards the control to another resource available in the same web application or different web app on the same container.

What is difference between getAttribute() and getParameter()?

GetAttribute() returns an object so when ever we use a getAttribute() we have to cast the return type that is we have to convert it to the required type like string or int.
getParameter always returns a string.one more difference is where this 2 methods are used...getAttribute is used to get the values from the session and getParameter is used to get the values from the form.(html or a jsp file).

Jsp11 07/10/2008

What is the architecture of JSP?

Java Server Pages (JSP) are normally used for developing Enterprise Applications and this is called as JEE - Java Enterprise Edition.
JEE is an open standard based platform for developing, deploying and managing n-tier, web enabled, component based enterprise applications.
1. MVC(Model-View-Container) / Model 2 Architecture: The most commonly used architecture for web applications is the Model 2 Architecture-Model is a component that holds the data (JavaBean)-View is a component that takes care of the presentation (JSP)-Controller is a component that controls and co-ordinates all the activities (Servlet)Advantages of MVC architecture:-MaintainabilityThe business logic and presentation logic are separatedThe architecture is well known-Reusability-SecurityAs all the requests are routed through a single point, the Controller can take care of security instead of each page taking care of the security

What is the diff. between declaring members in JSP and declaring in jspinit() method ?

Declaring a variable in JSP means it will have a scope of page while declaring it in jspInit() means its scope gets end with init() method only.

What is the use of extends in jsp. If we want to import a class in same jsp file how can we do it?

Extends="package.class" The fully qualified name of the superclass of the Java class file this JSP file will be compiled to. Use this attribute cautiously, as it can limit the JSP container"s ability to provide a specialized superclass that improves the quality of the compiled file. import="{package.class | package.* }, ..." A comma-separated list of Java packages that the JSP file should import. The packages (and their classes) are available to scriptlets, expressions, and declarations within the JSP file. If you want to import more than one package, you can specify a comma-separated list after import or you can use import more than once in a JSP file.

What is the default scope of jsp tags?
Page scope is the default scope for jsp tags.

When many Users are browsing the same application at the same time and they click the "Submit" button will many objects be created for each and every User?

When we implement SingleThread Model one object will be created for every request, otherwise only one object will be created irrespective of the number of requests.

Jsp10 07/10/2008

What is jsp:use bean. What are the scope attributes & difference between these attributes?

The element locates or instantiates a JavaBeans component.
first attempts to locate an instance of the bean. If the bean does not exist, instantiates it from a class or serialized template. The body of a element often contains a element that sets property values in the bean. The body tags are only processed if instantiates the bean. If the bean already exists, the body tags have no effect.

What are Custom tags. Why do you need Custom tags. How do you create Custom tag?

The most recent version of the JSP specification defines a mechanism for extending the current set of JSPtags.
It does this by creating a custom set of tags called a tag library. That is what the taglib points to.
The taglib directive declares that the page uses custom tags, uniquely names the tag library defining them, and associates a tag prefix that will distinguish usage of those tags.
The syntax of the taglibdirective is as follows:
<%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %>

What is the difference between include directive & jsp:include action?

Difference between include directive and
1. provides the benifits of automatic recompliation,smaller class size ,since the code corresponding to the included page is not present in the servlet for every included jsp page and option of specifying the additional request parameter.
2.The also supports the use of request time attributes valus for dynamically specifying included page which directive does not.
3.the include directive can only incorporate contents from a static document.
4. can be used to include dynamically generated output eg. from servlets.
5.include directive offers the option of sharing local variables,better run time efficiency.
6.Because the include directive is processed during translation and compilation,it does not impose any restrictions on output buffering.

What is the difference between servlet session and jsp session?

Nothing, Since a JSP at the end becomes a Servlet. The session handling capabilities are the same for a JSP as well as Servlets.

Why should we setContentType() in servlet ?what is the use of that method?

To intimate the browser that which type of content is coming as response,Depending upon the contentType browser treats with the response.

Jsp9 07/10/2008

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:<%//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);%>

Is there a way I can set the inactivity lease period on a per-session basis?

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 thesession has been created.For example:<%session.setMaxInactiveInterval(300);%>would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.

How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default?

One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSPengine.In any case, your new superclass has to fulfill the contract with the JSP engine by: Implementingthe HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final.Additionally, your servlet superclass also needs to do the following:The service() method has to invoke the _jspService() methodThe init() method has to invoke the jspInit() methodThe destroy() method has to invoke jspDestroy()If any of the above conditions are not satisfied, the JSP engine may throw a translation error. Once the superclass has been developed, you can have your JSP extend it as follows:<%@ page extends="packageName.ServletName" %>

How do you pass control from one JSP page to another?

Use the following ways to pass control of a request from one servlet to another or one jsp to another.· The RequestDispatcher object ‘s forward method to pass the control.· The response.sendRedirect method

How do you restrict page errors display in the JSP page?

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

    Jsp Sets


    July 2008

    RSS Feed