Académique Documents
Professionnel Documents
Culture Documents
A: A comment that is sent to the client in the viewable page source.The JSP
engine handles an output comment as uninterpreted HTML text, returning the
comment in the HTML output sent to the client. You can see the comment by
viewing the page source from your Web browser.
JSP Syntax
<!-- comment [ <%= expression %> ] -->
Example 1
<!-- This is a commnet sent to client on
<%= (new java.util.Date()).toLocaleString() %>
-->
You can use any characters in the body of the comment except the closing --
%> combination. If you need to use --%> in your comment, you can escape it
by typing --%\>.
JSP Syntax
<%-- comment --%>
Examples
<%@ page language="java" %>
<html>
<head><title>A Hidden Comment </title></head>
<body>
<%-- This comment will not be visible to the colent in the page source --%>
</body>
</html>
TOP
Q: What is a Expression?
A: 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
TOP
Q: What is a Declaration?
A: A declaration declares one or more variables or methods for use later in the
JSP source file.
Q: What is a Scriptlet?
A: 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.
TOP
• exception
TOP
1. page
2. request
3.session
4.application
TOP
<%
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
%>
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 >
Q: 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?
A: You could make a simple wrapper function, like
<%!
String blanknull(String s) {
return (s == null) ? \"\" : s;
}
%>
Q: How can I enable session tracking for JSP pages if the browser has
disabled cookies?
A: We know that session tracking uses cookies by default to associate a session
identifier with a unique user. If the browser does not support cookies, or if
cookies are disabled, you can still enable session tracking using URL
rewriting. URL rewriting essentially includes the session ID within the link
itself as a name/value pair. However, for this to be effective, you need to
append the session ID for each and every link that is part of your servlet
response. Adding the session ID to a link is greatly simplified by means of of
a couple of methods: response.encodeURL() associates a session ID with a
given URL, and if you are using redirection, response.encodeRedirectURL()
can be used by giving the redirected URL as input. Both encodeURL() and
encodeRedirectedURL() first determine whether cookies are supported by
the browser; if so, the input URL is returned unchanged since the session ID
will be persisted as a cookie.
Consider the following example, in which two JSP files, say hello1.jsp and
hello2.jsp, interact with each other. Basically, we create a new session within
hello1.jsp and place an object within this session. The user can then traverse
to hello2.jsp by clicking on the link present within the page. Within
hello2.jsp, we simply extract the object that was earlier placed in the session
and display its contents. Notice that we invoke the encodeURL() within
hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the
session ID is automatically appended to the URL, allowing hello2.jsp to still
retrieve the session object. Try this example first with cookies enabled. Then
disable cookie support, restart the brower, and try again. Each time you
should see the maintenance of the session across pages. Do note that to get
this example to work with cookies disabled at the browser, your JSP engine
has to support URL rewriting.
hello1.jsp
<%@ page session=\"true\" %>
<%
Integer num = new Integer(100);
session.putValue("num",num);
String url =response.encodeURL("hello2.jsp");
%>
<a href=\'<%=url%>\'>hello2.jsp</a>
hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is " + i.intValue());
%>
Q: What is the difference b/w variable declared inside a declaration part
and variable declared in scriplet part?
A: 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.
[ Received
from
Neelam
Gangadhar] TOP
Response has already been commited error. What does it mean? - This error show
only when you try to redirect a page after you already have written something in your
page. This happens because HTTP specification force the header to be set up before
the lay out of the page can be shown (to make sure of how it should be displayed,
content-type=”text/html” or “text/xml” or “plain-text” or “image/jpg”, etc.) When you
try to send a redirect status (Number is line_status_402), your HTTP server cannot
send it right now if it hasn’t finished to set up the header. If not starter to set up the
header, there are no problems, but if it ’s already begin to set up the header, then your
HTTP server expects these headers to be finished setting up and it cannot be the case
if the stream of the page is not over… In this last case it’s like you have a file started
with <HTML Tag><Some Headers><Body>some output (like testing your variables.)
Before you indicate that the file is over (and before the size of the page can be setted
up in the header), you try to send a redirect status. It s simply impossible due to the
specification of HTTP 1.0 and 1.1
1. 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
JSP engine admin screen or associated properties file. However, if your JSP
engine supports the Servlet 2.1 API, you can manage the inactivity lease
period on a per-session basis. This is done by invoking the
HttpSession.setMaxInactiveInterval() method, right after the session has been
created. For example:
2. <%
3. session.setMaxInactiveInterval(300);
4. %>
would reset the inactivity period for this session to 5 minutes.
The inactivity interval is set in seconds.
5. 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:
6. <%
7. //creating a cookie
8. Cookie mycookie = new Cookie("aName","aValue");
9. response.addCookie(mycookie);
10. //delete a cookie
11. Cookie killMyCookie = new Cookie("mycookie", null);
12. killMyCookie.setMaxAge(0);
13. killMyCookie.setPath("/");
14. response.addCookie(killMyCookie);
15. %>
16. How does a servlet communicate with a JSP page? - The following code
snippet shows how a servlet instantiates a bean and initializes it with FORM
data posted by a browser. The bean is then placed into the request, and the call
is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher
for downstream processing.
17. public void doPost (HttpServletRequest request, HttpServletResponse
response) {
18. try {
19. govi.FormBean f = new govi.FormBean();
20. String id = request.getParameter("id");
21. f.setName(request.getParameter("name"));
22. f.setAddr(request.getParameter("addr"));
23. f.setAge(request.getParameter("age"));
24. //use the id to compute
25. //additional bean properties like info
26. //maybe perform a db query, etc.
27. // . . .
28. f.setPersonalizationInfo(info);
29. request.setAttribute("fBean",f);
30. getServletConfig().getServletContext().getRequestDispatcher
31. ("/jsp/Bean1.jsp").forward(request, response);
32. } catch (Exception ex) {
33. . . .
34. }
35. }
The JSP page Bean1.jsp can then process fBean, after first
extracting it from the default request scope via the useBean
action.
jsp:useBean id="fBean" class="govi.FormBean" scope="request"
/ jsp:getProperty name="fBean" property="name"
/ jsp:getProperty name="fBean" property="addr"
/ jsp:getProperty name="fBean" property="age"
/ jsp:getProperty name="fBean" property="personalizationInfo" /
36. 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:
o The service() method has to invoke the _jspService() method
o The init() method has to invoke the jspInit() method
o 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" %>
37. 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
38. <%!
39. String blanknull(String s) {
40. return (s == null) ? "" : s;
41. }
42. %>
43. then use it inside your JSP form, like
44. <input type="text" name="shoesize" value="<%=blanknull(shoesize)%
>" >
45. How can I get to print the stacktrace for an exception occuring within my
JSP page? - By printing out the exception’s 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. The following snippet
demonstrates how you can print a stacktrace from within a JSP error page:
46. <%@ page isErrorPage="true" %>
47. <%
48. out.println(" ");
49. PrintWriter pw = response.getWriter();
50. exception.printStackTrace(pw);
51. out.println(" ");
52. %>
53. 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.
54. <%@ page import="java.util.*" %>
55. <%!
56. ServletConfig cfg =null;
57. public void jspInit(){
58. ServletConfig cfg=getServletConfig();
59. for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();)
{
60. String name=(String)e.nextElement();
61. String value = cfg.getInitParameter(name);
62. System.out.println(name+"="+value);
63. }
64. }
65. %>
66. How can my JSP page communicate with an EJB Session Bean? - The
following is a code snippet that demonstrates how a JSP page can interact with
an EJB session bean:
67. <%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account" %>
68. <%!
69. //declare a "global" reference to an instance of the home interface of the
session bean
70. AccountHome accHome=null;
71. public void jspInit() {
72. //obtain an instance of the home interface
73. InitialContext cntxt = new InitialContext( );
74. Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
75. accHome =
(AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
76. }
77. %>
78. <%
79. //instantiate the session bean
80. Account acct = accHome.create();
81. //invoke the remote methods
82. acct.doWhatever(...);
83. // etc etc...
84. %>
RequestDispatcher description.
RequestDispatcher defines an object that receives requests from the client and sends
them to any resource (such as a servlet, HTML file, or JSP file) on the server. The
servlet container creates the RequestDispatcher object, which is used as a wrapper
around a server resource located at a particular path or given by a particular name.
• ServletContext.getRequestDispatcher(String path)
• ServletContext.getNamedDispatcher(String name)
• ServletRequest.getRequestDispatcher(String path)
forward should be called before the response has been committed to the client (before
response body output has been flushed). If the response already has been committed,
this method throws an IllegalStateException. Uncommitted output in the response
buffer is automatically cleared before the forward.
public class Dispatcher extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) {
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/banner");
if (dispatcher != null) dispatcher.include(request, response);
}
}
Includes the content of a resource (servlet, JSP page, HTML file) in the response. In
essence, this method enables programmatic server-side includes. The
ServletResponse object has its path elements and parameters remain unchanged
from the caller's. The included servlet cannot change the response status code or set
headers; any attempt to make a change is ignored.
package javax.servlet;
}
The include method of the RequestDispatcher interface may be called at ANY time.
The target servlet of the include method has access to all aspects of the request object,
but its use of the response object is more limited. It can only write information to the
ServletOutputStream or Writer of the response object and commit a response by
writing content past the end of the response buffer, or by explicitly calling the
flushBuffer method of the ServletResponse interface. It CANNOT set headers or call
any method that affects the headers of the response. Any attempt to do so must be
ignored.
The forward method of the RequestDispatcher interface may be called by the calling
servlet ONLY when NO output has been committed to the client. If output data exists in
the response buffer that has not been committed, the content must be cleared before
the target servlet's service method is called. If the response has been committed, an
IllegalStateException must be thrown.
The path elements of the request object exposed to the target servlet must reflect the
path used to obtain the RequestDispatcher. The only exception to this is if the
RequestDispatcher was obtained via the getNamedDispatcher method. In this
case, the path elements of the request object must reflect those of the original request.
Before the forward method of the RequestDispatcher interface returns, the response
content MUST be sent and committed, and closed by the servlet container.
The ServletContext and ServletRequest methods that create RequestDispatcher
objects using path information allow the optional attachment of query string
information to the path. For example, a Developer may obtain a RequestDispatcher
by using the following code:
Parameters specified in the query string used to create the RequestDispatcher take
precedence over other parameters of the same name passed to the included servlet.
The parameters associated with a RequestDispatcher are scoped to apply only for the
duration of the include or forward call.
Additional request-scoped attributes.
Except for servlets obtained by using the getNamedDispatcher method, a servlet that
has been invoked by another servlet using the include method of RequestDispatcher
has access to the path by which it was invoked.
The following request attributes must be set:
• javax.servlet.include.request_uri
• javax.servlet.include.context_path
• javax.servlet.include.servlet_path
• javax.servlet.include.path_info
• javax.servlet.include.query_string
These attributes are accessible from the included servlet via the getAttribute method
on the request object and their values must be equal to the request URI, context path,
servlet path, path info, and query string of the INCLUDED servlet, respectively. If the
request is subsequently included, these attributes are replaced for that include.
If the included servlet was obtained by using the getNamedDispatcher method, these
attributes MUST NOT be set.
Except for servlets obtained by using the getNamedDispatcher method, a servlet that
has been invoked by another servlet using the forward method of RequestDispatcher
has access to the path of the ORIGINAL request.
The following request attributes must be set:
• javax.servlet.forward.request_uri
• javax.servlet.forward.context_path
• javax.servlet.forward.servlet_path
• javax.servlet.forward.path_info
• javax.servlet.forward.query_string
The values of these attributes must be equal to the return values of the
HttpServletRequest methods getRequestURI, getContextPath, getServletPath,
getPathInfo, getQueryString respectively, invoked on the request object passed to
the first servlet object in the call chain that received the request from the client.
These attributes are accessible from the forwarded servlet via the getAttribute method
on the request object. Note that these attributes must always reflect the information in
the original request even under the situation that multiple forwards and subsequent
includes are called.
If the forwarded servlet was obtained by using the getNamedDispatcher method,
these attributes must not be set.
The program compiles properly but at runtime it will give "Main method not
public." message.
Pass by reference means, passing the address itself rather than passing the
value. Pass by value means passing a copy of the value.
hashCode()
Or
What gives java it’s “write once and run anywhere” nature?
All Java programs are compiled into class files that contain bytecodes. These byte
codes can be run in any platform and hence java is said to be platform
independent.
Expain the reason for each keyword of public static void main(String
args[])?
public- main(..) is the first method called by java environment when a program is
executed so it has to accessible from java environment. Hence the access
specifier has to be public.
static: Java environment should be able to call this method without creating an
instance of the class , so this method must be declared as static.
void: main does not return anything so the return type must be void
The argument String indicates the argument type which is given at the command
line and arg is an array for string given during command line.
What are the differences between == and .equals() ?
Or
Or
Or
What would you use to compare two String variables - the operator ==
or the method equals()?
Or
How is it possible for two String objects with identical values not to be
equal under the == operator?
The == operator compares two objects to determine if they are the same object
in memory i.e. present in the same memory location. It is possible for two String
objects to have the same value, but located in different areas of memory.
Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This
driver includes its own implementation of a TCP/IP version of Oracle’s Net8
written entirely in Java, so it is platform independent, can be downloaded to a
browser at runtime, and does not require any Oracle software on the client side.
This driver requires a TCP/IP listener on the server side, and the client connection
string uses the TCP/IP port address, not the TNSNAMES entry for the database
name.
What is the difference between final, finally and finalize? What do you
understand by the java final keyword?
Or
What is final, finalize() and finally?
Or
What is finalize() method?
Or
What is the difference between final, finally and finalize?
Or
What does it mean that a class or member is final?
Global variables are globally accessible. Java does not support globally accessible
variables due to following reasons:
* The global variables breaks the referential transparency
* Global variables creates collisions in namespace.
Example
int i = 1000;
Example
long i = 700.20;
The Java Virtual Machine is software that can be ported onto various hardware-
based platforms
What do you understand by downcasting?
The process of Downcasting refers to the casting from a general to a more
specific type, i.e. casting down the hierarchy
What are Java Access Specifiers?
Or
What is the difference between public, private, protected and default
Access Specifiers?
Or
What are different types of access modifiers?
Access specifiers are keywords that determine the type of access to the member
of a class. These keywords are for allowing privileges to parts of a program such
as functions and variables. These are:
• Public: accessible to all classes
• Protected: accessible to the classes within the same package and any
subclasses.
• Private: accessible only to the class to which they belong
• Default: accessible to the class to which they belong and to subclasses within
the same package
A static variable is associated with the class as a whole rather than with specific
instances of a class. Each object will share a common copy of the static variables
i.e. there is only one copy per class, no matter how many objects are created
from it. Class variables or static variables are declared with the static keyword in
a class. These are declared outside a class and stored in static memory. Class
variables are mostly used for constants. Static variables are always called by the
class name. This variable is created when the program starts and gets destroyed
when the programs stops. The scope of the class variable is same an instance
variable. Its initial value is same as instance variable and gets a default value
when its not initialized corresponding to the data type. Similarly, a static method
is a method that belongs to the class rather than any object of the class and
doesn't apply to an object or even require that any objects of the class have been
instantiated.
Static methods are implicitly final, because overriding is done based on the
type of the object, and static methods are attached to a class, not an object. A
static method in a superclass can be shadowed by another static method in a
subclass, as long as the original method was not declared final. However, you
can't override a static method with a non-static method. In other words, you can't
change a static method into an instance method in a subclass.
The String array is empty. It does not have any element. This is unlike C/C++
where the first element by default is the program name. If we do not provide any
arguments on the command line, then the String array of main method will be
empty but not null.
How can one prove that the array is not null but empty?
Print array.length. It will print 0. That means it is empty. But if it would have been
null then it would have thrown a NullPointerException on attempting to print
array.length.
Yes. While starting the application we mention the class name to be run. The JVM
will look for the main method only in the class whose name you have mentioned.
Hence there is not conflict amongst the multiple classes having main method.
Static variable are loaded when classloader brings the class to the JVM. It is not
necessary that an object has to be created. Static variables will be allocated
memory space when they have been loaded. The code in a static block is
loaded/executed only once i.e. when the class is first initialized. A class can have
any number of static blocks. Static block is not member of a class, they do not
have a return statement and they cannot be called directly. Cannot contain this or
super. They are primarily used to initialize static fields.
Can I have multiple main methods in the same class?
No the program fails to compile. The compiler says that the main method is
already defined in the class.
JVM is an abstract computing machine like any other real computing machine
which first converts .java file into .class file by using Compiler (.class is nothing
but byte code file.) and Interpreter reads byte codes.
Add two variables and assign the value into First variable. Subtract the Second
value with the result Value. and assign to Second variable. Subtract the Result of
First Variable With Result of Second Variable and Assign to First Variable.
Example:
Does JVM maintain a cache by itself? Does the JVM allocate objects in
heap? Is this the OS heap or the heap maintained by the JVM? Why
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but
references to those objects are on the STACK.
Phantom memory is false memory. Memory that does not exist in reality.
A static method can be synchronized. If you do so, the JVM will obtain a lock on
the java.lang. Class instance associated with the object. It is similar to saying:
synchronized(XYZ.class) {
Example:
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
Output:
Hello
World
Garbage collection is one of the most important features of Java. The purpose of
garbage collection is to identify and discard objects that are no longer needed by
a program so that their resources can be reclaimed and reused. A Java object is
subject to garbage collection when it becomes unreachable to the program in
which it is used. Garbage collection is also called automatic memory management
as JVM automatically removes the unused variables/objects (value is null) from
the memory. Every class inherits finalize() method from java.lang.Object, the
finalize() method is called by garbage collector when it determines no more
references to the object exists. In Java, it is good idea to explicitly assign null into
a variable when no more in use.
In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused
objects, but there is no guarantee when all the objects will garbage collected.
Garbage collection is an automatic process and can't be forced. There is no
guarantee that Garbage collection will start immediately upon request of
System.gc().
It is a daemon thread.
An object’s finalize() method cannot be invoked by the garbage collector while the
object is still reachable. However, an object’s finalize() method may be invoked by
other objects.
Does garbage collection guarantee that a program will not run out of
memory?
Garbage collection does not guarantee that a program will not run out of memory.
It is possible for programs to use up memory resources faster than they are
garbage collected. It is also possible for programs to create objects that are not
subject to garbage collection.