Chapter 5
Chapter 5
Chapter 5
Chapter – 05 Marks: 20
Introduction:
The discussion of networking focuses on both sides of a client-serverrelationship. The
client requests that some action be performed and the serverperforms the action and responds
to the client. This request-response model ofcommunication is the foundation for the highest-
level views of networking in Java—servlets and JavaServer Pages (JSP). A servlet extends
the functionality of a server,such as a Web server. Packages javax.servlet and
javax.servlet.http provide theclasses and interfaces to define servlets. Packages
javax.servlet.jsp andjavax.servlet.jsp.tagext provide the classes and interfaces that extend the
servletCapabilities for JavaServer Pages. Using special syntax, JSP allows Web-
pageimplementers to create pages that use encapsulated Java functionality and even to
Write script lets of actual Java code directly in the page.
Java has primarily been a language used to implement browser side program,also
known as applets, when it comes to the web. However with the java Servlets APIthe power of
the Java can be applied to server side software as well. Servlets aresmall programs that
execute on the server side of a Web connection. Just as appletsdynamically extend the
functionality of a Web browser, servlet dynamically extend thefunctionality of a Web server.
There is that a Servlet run on the server and willrespond to a request from the client either in
the form of HTML pages. Servlet are thejava counterpart to non-java dynamic web content
technologies such as PHP, ASP and.Net.
5.1Servlets:
The Servlet is small programming unit area of the code that can be executedwhen it’s
called. The Servlets are server side components and resides within theserver only, so the
performance of server can be increased. And these can accept theclient request from browser
and process it and generating the response for sendingto the requested client.
“A Servlet is a Web component, managed by a container that generatesdynamic
content. Servlets are small, platform-independent Java classes compiled toan architecture-
neutral byte code that can be loaded dynamically into and run by aWeb server”
Servlets are programs that run on a web server and build web pages Dynamically
Servlets run on server to accept request and send back the response
1
Advance Java Programming (17625)
2
Advance Java Programming (17625)
3
Advance Java Programming (17625)
4
Advance Java Programming (17625)
Servlet container:
Differences between Servlets and Applets:
Sno Servlets Applets
1. Server side component and improves that functionality Browser side component that
improves functionality
2. Executes within server space Executes in the browser.
3. Process the client request and response. These are not like.
4. These are not embedding in html.These are embedding programs.
5. Servlets can create dynamic web pages. These are unable to creating web pages
dynamically.
Development Phase:
In this phase will describe about the creation of the servlet class. Every Servletshould
implement the Servlet interface either directly or indirectly,i.e., we can extendeither
javax.servlet.GenericServlet class which implements Servlet interface or wecan extend
javax.servlet.http.HttpServlet class which extend GenericServlet classServlet API: - The
collection of classes and interface is required to build, compile andrun the servlets are called
Servlet API. These all are contains in two packages asfollows.
5
Advance Java Programming (17625)
The servlet packages define two abstract classes that implement the interfaceServlet—
class GenericServlet (from the package javax.servlet) and class HttpServlet(From the
package javax.servlet.http). These classes provide default implementationsof all the Servlet
methods. Most servlets extend either Generic- Servlet or HttpServletand override some or all
of their methods.
Servlets extend class HttpServlet, which defines enhanced processingcapabilities for servlets
that extend the functionality of a Web server. The key methodin every servlet is service,
which receives both a ServletRequest object and aServletResponse object. These objects
provide access to input and output streamsthat allow the servlet to read data from the client
and send data to the client. Thesestreams can be either byte based or character based. If
problems occur during theexecution of a servlet, either ServletExceptions or IOExceptions
are thrown to indicatethe problem.
// Example of a Servlet file name is FirstServlet.java
importjavax.servlet.*;
import java.io.*;
public class FirstServlet extends GenericServlet
{
public void service(ServletRequestrq,ServletResponsersp)
throwsServletException,IOException
{
PrintWriter pw = rsp.getWriter();
rsp.setContentType("text/html");
pw.write("<html><body><h2 align=center ");
pw.write("style=background:orange>THIS IS MY");
pw.write(" FIRST SERVLET PROGRAM</h2>");
pw.write("</body></html>");
}
}
First, note that it imports the javax.servlet package. This package contains theclasses
and interfaces required to build servlets. You will learn more about these laterin this chapter.
Next, the program defines HelloServlet as a subclass ofGenericServlet. The GenericServlet
class provides functionality that makes it easy tohandle requests and responses.
6
Advance Java Programming (17625)
For example:
javac –classpath “C:\Program Files\Apache Software Foundation\Tomcat
5.5\common\lib\servlet-api.jar” FirstServlet.javaor the alternative is to set the classpath in
environment variable as “C:\Program Files\ApacheSoftware Foundation\Tomcat
5.5\common\lib\servlet-api.jar” can be complied directlyThis command will generate the
Class file.
Deployment Phase:
After completion of the Development Phase Deployment Phase come into
actionwhich follows following steps:
1. The Creation of a Directory Structure suitable for your application
2. The Creation of the Deployment Descriptor ( web.xml )
Create the following Directory Structure:
7
Advance Java Programming (17625)
8
Advance Java Programming (17625)
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
</web-app>
Servlets are initialized by method init. Method in it is called exactly once in a
servlet’s lifetime, before any client requests are accepted. Method in it takesServletConfig
argument and throws a ServletException. The argument provides theservlet with information
about its initialization parameters (i.e., parameters notassociated with a request, but passed to
the servlet for initializing the servlet’s state).These parameters are specified in the web.xml
deployment descriptor file as part of aservlet element. Each parameter appears in an
initparam element of the followingform:
<init-param>
<param-name>parameter name</param-name>
<param-value>parameter value</param-value>
</init-param>
Servlets can obtain initialization parameter values by invoking
ServletConfigcmethodgetInitParameter, which receives a string representing the name of
thecparameter.For Example in above web.xml user in param name and saicse is value
thencString value=getServletConfig().getInitParameter(“user”);Now it will returns the value
of user parameter as “saicse” assigned to thetring value.
Running Phase:
This running phase involves calling the servlet in their context path by URLpattern specified
in the web.xml file.
To run our FirstServlet use the following URL
http://127.0.0.1:8080/MyApp/FirstServlet
This URL pattern is having 5 components
1. Protocol
2. Server IP Address
3. Port Number at which exchange of the data takes place
4. Context
5. Requested File path
9
Advance Java Programming (17625)
1. Protocol:
The Web Server offers many protocols. The HTTP (Hypertext Transfer Protocol)that
forms the basis of the World Wide Web uses URLs (Uniform Resource Locators) tolocate
resources on the Web Server. The communication model defined by HTTP formsthe
foundation for all web application design. A basic understanding of HTTP is key
todeveloping applications that fit within the constraints of the protocol, no latter whichserver-
side technology you use.
2. Server IP Address:
The server localhost (IP address 127.0.0.1) is a well-known host name oncomputers
that support TCP/IP-based networking protocols such as HTTP. This hostname can be used to
test TCP/IP applications on the local computer.We have to specifyhe IP Address of the
System at which Tomcat server is running on the LAN.
3. Port Number:
The Tomcat server awaits requests from clients on port 8080. This portnumber must
be specified as part of the URL to request a servlet running in Tomcatbecause it is the place
where the Exchange of the data takes place.
4. Context Path:
Within the container, each web application is represented by a servlet context.The
servlet context is associated with a unique URI path prefix called the context path,as shown
10
Advance Java Programming (17625)
Integration:-
Servlets are developed in Java and can therefore take advantage of all otherJava
technologies, such as JDBC for database access, JNDI for directory access, RMIfor remote
resource access, etc. Starting with Version 2.2, the servlet specification ispart of the Java 2
Enterprise Edition (J2EE), making servlets an important ingredientof any large-scale
enterprise application, with formalized relationships to otherserverside technologies such as
Enterprise JavaBeans.
Efficiency:
Servlets execute in a process that is running until the servlet-based application is shut
down. Each servlet request is executed as a separate thread in thispermanent process.
11
Advance Java Programming (17625)
Scalability:
By virtue of being written in Java and the broad support for servlets, a
servletbasedapplication is extremely scalable. You can develop and test the application on
aWindows PC using the standalone servlet reference implementation, and deploy it
onanything from a more powerful web server.
12
Advance Java Programming (17625)
5.2 HttpServletResponse:
1. void addCookie( Cookie cookie )
Used to add a Cookie to the header of the response to the client.The Cookie’s maximum age
and whether Cookies are enabled on the client determine if Cookies are stored on the client.
2. ServletOutputStreamgetOutputStream()
Obtains a byte-based output stream for sending binary data to the client.
3. PrintWritergetWriter()
Obtains a character-based output stream for sending text data to the client.
4. void setContentType( String type )
Specifies the MIME type of the response to the browser. The MIME type helps the browser
determine how to display the data (or possibly what other application to execute to process
the data). For example, MIME type "text/html" indicates that the response is an HTML
document, so the browser displays the HTML page.
HttpServletRequest:
1. String getParameter( String name )
Obtains the value of a parameter sent to the servlet as part of a get or post
request. The name argument represents the parameter name.
2. Enumeration getParameterNames()
Returns the names of all the parameters sent to the servlet as part of a
post request.
3. String[] getParameterValues( String name )
For a parameter with multiple values, this method returns an array of
strings containing the values for a specified servlet parameter.
13
Advance Java Programming (17625)
4. Cookie[] getCookies()
Returns an array of Cookie objects stored on the client by the server.
Cookie objects can be used to uniquely identify clients to the servlet.
5. HttpSessiongetSession( boolean create )
Returns an HttpSession object associated with the client’s currentbrowsing session. This
method can create an HttpSession object (trueargument) if one does not already exist for the
client. HttpSession objectsare used in similar ways to Cookies for uniquely identifying
clients.
ServletContext:
Defines a set of methods that a servlet uses to communicate with its servletcontainer,
for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is
one context per "web application" per Java Virtual Machine. (A "webapplication" is a
collection of servlets and content installed under a specific subset ofthe server's URL
namespace such as /MyApp.)In the case of a web application marked "distributed" in its
deploymentdescriptor, there will be one context instance for each virtual machine. In
thissituation, the context cannot be used as a location to share global information(because the
information won't be truly global). Use an external resource like adatabase instead.
ServletContextvsServletConfigServletContext
1. Contains details for a web application containing several Servlets
2. It is one per application
3. It defines a set of methods that a servlet uses to communicate with its
container or Servlets within application
4. Context wide parameters are specified within <context-param> elements of the
web.xml. they are available to all the servlets within that application using the
methodsgetServletContext().getInitParameter(“param_name”);
ServletConfig:
1. A servlet configuration object used by a servlet container to pass informationto a servlet
during initialization.
2. It is one per servlet.
3. Initialization parameters for individual servlet are specified within <init-param>sub-
elements of the <servlet> element in web.xml.
getServletConfig().getInitParameter(“param_name”);
14
Advance Java Programming (17625)
Cookies:
Creates a cookie, a small amount of information sent by a servlet to a Webbrowser,
saved by the browser, and later sent back to the server. A cookie's value canuniquely identify
a client, so cookies are commonly used for session management.The Cookie class
encapsulates a cookie. A cookie is stored on a client andcontains state information. Cookies
are valuable for tracking user activities. Forexample, assume that a user visits an online store.
A cookie can save the user’s name,address, and other information. The user does not need to
enter this data each time heor she visits the store. A servlet can write a cookie to a user’s
machine via theaddCookie( ) method of the HttpServletResponse interface. The data for that
cookie isthen included in the header of the HTTP response that is sent to the browser.A
cookie has a name, a single value, and optional attributes such as a comment,path and domain
qualifiers, a maximum age, and a version number. Some Webbrowsers have bugs in how they
handle the optional attributes.
15
Advance Java Programming (17625)
The names and values of cookies are stored on the user’s machine. Some of
theinformation that is saved for each cookie includes the following:
The name of the cookie
The value of the cookie
The expiration date of the cookie (setMaxAge(intsecs))
The comment of the Cookie ( setComment())
The expiration date determines when this cookie is deleted from the user’s machine. Ifan
expiration date is not explicitly assigned to a cookie, it is deleted when the currentbrowser
session ends. otherwise, the cookie is saved in a file on the user’s machine.the cookie is then
supplied to the Web server. Otherwise, it is not. There is oneconstructor for Cookie. It has the
signature shown here:Cookie(String name, String value)
Here, the name and value of the cookie are supplied as arguments to the constructor.
There are two common ways to trigger a chain of servlets for an incoming request.
First, you can tell the server that certain URLs should be handled by an explicitly specified
chain. Or, you can tell the server to send all output of a particular content type through a
specified servlet before it isreturned to the client, effectively creating a chain on the fly.
When a servlet converts one type of content into another, the technique is called filtering.
16
Advance Java Programming (17625)
Servlet chaining can change the way you think about web content creation. Here are some of
the things you can do with it:
17
Advance Java Programming (17625)
BufferedReader in = req.getReader();
18
Advance Java Programming (17625)
}
}
This servlet overrides both the doGet() and doPost() methods. This allows it to
work in chains that handle either type of request. The doGet() method contains the core
logic, while doPost() simply dispatches to doGet(), using the same technique as the Hello
example.
Inside doGet(), the servlet first fetches its print writer. Next, the servlet calls
req.getContentType() to find out the content type of the data it is receiving. It sets its
output type to match, or if getContentType() returned null, it realizes there is no incoming
data to deblink and simply returns. To read the incoming data, the servlet fetches a
BufferedReader with a call to req.getReader(). The reader contains the HTML output
from the previous servlet in the chain. As the servlet reads each line, it removes any instance
of BLINK or /BLINK with a call to replace() and then returns the line to the client (or
19
Advance Java Programming (17625)
perhaps to another servlet in the chain). Note that the replacement is case-sensitive and
inefficient; a solution to this problem that uses regular expressions is included in
A more robust version of this servlet would retrieve the incoming HTTP headers and pass on
the appropriate headers to the client (or to the next servlet in the chain). and explain the
handling and use of HTTP headers. There’s no need to worry about it now, as the headers
aren’t useful for simple tasks like the one we are doing here.
JSP Overview:
JavaServer Pages (JSP) is a server-side programming technology that enables the creation of
dynamic, platform-independent method for building Web-based applications.
JavaServer Pages (JSP) is a technology for developing web pages that support dynamic
content which helps developers insert java code in HTML pages by making use of special
JSP tags, most of which start with <% and end with %>.
JSP is a specification and not a product.Hence developers can develop variety of applications
and add up to performance and quality of software products.It is essential component of
J2EE.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a
user interface for a Java web application. Web developers write JSPs as text files that
combine HTML or XHTML code, XML elements, and embedded JSP actions and
commands.
Using JSP, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a database
or registering user preferences, accessing JavaBeans components, passing control between
pages and sharing information between requests, pages etc.
20
Advance Java Programming (17625)
JSP pages can be used in combination with servlets that handle the business logic, the model
supported by Java servlet template engines.
Problems on Servlets:
Servlets need a special "servlet container" to run servlets.
Advantages in JSP:
In JSP we can directly embed java code into html code but in servlet is not possible.
In jsp implicit objects are presents which is we can implement directly into jsp pages but in
servlet there are no implicit objects.
Anatomy Of JSP Page JSP page is simply a web page which contains JSP elements and
Template text.The below figure is a example of JSP page with JSP elements and Template
text Template text can be any text like HTML, WML, XML, or even plain text.When a JSP
page request is processed, the template text and dynamic content generated by the JSP
elements are merged, and the result is sent as the response to the browser.
JSP Architecture:
The web server needs a JSP engine ie. Container to process JSP pages. The JSP
container is responsible for intercepting requests for JSP pages. This tutorial makes use of
Apache which has built-in JSP container to support JSP pages development. A JSP container
works with the Web server to provide the runtime environment and other services a JSP
21
Advance Java Programming (17625)
needs. It knows how to understand the special elements that are part of JSPs. Following
diagram shows the position of JSP container and JSP files in a Web Application.
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP
engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements and
all JSP elements are converted to Java code that implements the corresponding dynamic
behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes it.
During execution, the servlet produces an output in HTML format, which the servlet engine
passes to the web server inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML
content.
22
Advance Java Programming (17625)
Finally web browser handles the dynamically generated HTML page inside the HTTP
response exactly as if it were a static page.
All the above mentioned steps can be shown below in the following diagram:
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists
and whether the modification date on the JSP is older than the servlet. If the JSP is older than
its generated servlet, the JSP container assumes that the JSP hasn't changed and that the
generated servlet still matches the JSP's contents. This makes the process more efficient than
with other scripting languages (such as PHP) and therefore faster. So in a way, a JSP page is
really just another way to write a servlet without having to be a Java programming wiz.
Except for the translation phase, a JSP page is handled exactly like a regular servlet.
23
Advance Java Programming (17625)
The three major phases of JSP life cycle are very similar to Servlet Life Cycle and
they are as follows:
1. JSP Compilation:
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to
compile the page. If the page has never been compiled, or if the JSP has been modified since
it was last compiled, the JSP engine compiles the page. The compilation process involves
three steps:
a) Parsing the JSP.
24
Advance Java Programming (17625)
1. Name the class that can be used to get the cookies from the client browser
A. HttpServletResponse. C. SessionContext.
B. HttpServletRequest. D. SessionConfig.
ANSWER: B
2. Which of the following is not a server-side technology?
A. Servlets. C. DHTML.
B. Java Server Pages. D. CGI.
ANSWER: C
3. Name the class that includes the getSession method that is used to get the HttpSession
object.
A. HttpServletResponse. C. SessionContext.
B. HttpServletRequest. D. SessionConfig.
ANSWER: A
4. The method getWriter returns an object of type PrintWriter. This class has println
methods to generate output. Which of these classes define the getWriter method?
A. HttpServletRequest. C. ServletConfig.
B. HttpServletResponse. D. ServletContext.
ANSWER: B
5. To send text output in a response, the following method of HttpServletResponse may be
used to get the appropriate Writer/Stream object. Choose the correct option.
A. getStream. C. getBinaryStream.
B. getOutputStream. D. getWriter.
ANSWER: D
6. Which method returns names of the request parameters as Enumeration of String objects
A. getParameter. C. getParameterValues.
B. getParameterNames. D. getParameterVal.
ANSWER: B
7. Servlets classes specific to your application are placed in which directory on the
TOMCAT Server?
A. /lib/. B. /WEB-INF/classes/.
25
Advance Java Programming (17625)
C. /classes. D. /WEB-INF/lib/.
ANSWER: B
8. Servlet becomes thread safe by implementing the javax.servlet.
SingleThreadModelinterface_________________
A. as every request is handled by separate instances of the Servlet.
B. as a single thread serves all the client requests.
C. as all the requests are serialized.
D. a first to-be loaded servlet and is loaded by the server during startup.
ANSWER: A
9. Where the session data will store?
A. Session buffer. C. Session memory.
B. Session Disk. D. Session objects.
ANSWER: D
10. How do you debug the Servlet?
A. Through servlet log(). C. Through servlet ().
B. Through servlet run(). D. Through servlet log().
ANSWER: D
11. How do you handle DataBase access and in which method of the servlet do you like to
createconnection.
A. void(). C. init().
B. paint(). D. repaint().
ANSWER: C
12. The major difference between servlet and CGI is
A. Servlets are thread based and CGI is process based.
B. Servlets executes slower compared to CGI.
C. Servlet has no platform specific API, where as CGI has.
D. All of the above.
ANSWER: A
13. Which method is used to specify before any lines that uses the PintWriter?
A. setPageType(). C. setContentType().
B. setContextType(). D. setResponseType()
ANSWER: A
14. Which of the following are the session tracking techniques?
26
Advance Java Programming (17625)
A. URL rewriting, using session object, using response object, using hidden fields.
B. URL rewriting, using session object, using cookies, using hidden fields.
C. URL rewriting, using servlet object, using response object, using cookies.
D. URL rewriting, using request object, using response object, using session object.
ANSWER: A
15. To get the servlet environment information.
A. ServletConfig object is used. C. ServletContext object is used.
B. ServletException object is used. D. ServletContainer object is used.
ANSWER: C
16. The getSession() method with 'true' as its parameter [ getSession(true) ] it will return the
appropriatesession object when
A. the session is completed
B. the session object is passed to another method
C. the session does not exists
D. the session is existing
ANSWER: D
17. The method forward (request, response) will
A. return back to the same method from where the forward was invoked.
B. not return back to the same method from where the forward was invoked and the web
pagesnavigation continues.
C. Both A and B are correct.
D. None of the above.
ANSWER: A
18. A servlet maintain session in
A. Servlet container. C. Servlet request heap.
B. Servlet context. D. Servlet response heap.
ANSWER: B
19. The life cycle of a servlet is managed by
A. servlet context.
B. servlet container.
C. the supporting protocol (such as http or https).
D. all of the above.
ANSWER: B
27
Advance Java Programming (17625)
20. How many ServletContext objects are available for an entire web application?
A. One each per servlet. C. One each per response.
B. One each per request. D. Only one.
ANSWER: D
21. Theinclude( ) method of RequestDispatcher.
A. sends a request to another resource like servlet, jsp or html.
B. includes resource of file like servlet, jsp or html.
C. appends the request and response objects to the current servlet.
D. None of the above.
ANSWER: B
22. Dynamic interception of requests and responses to
A. transform the information is done by servlet container.
B. servlet config.
C. servlet context.
D. servlet filter.
ANSWER: C
23. EJB systems performance tuning is the responsibility of
A. Bean Provider C. Application Assembler
B. EJB Deployer D. Tool Vendor
ANSWER: B
24. Java Servlets are efficient and powerful solution for creating .......................for the web.
A) dynamic content C) hardware
B) static content D) both and b
ANSWER: A
25. Filters were officially introduced in the servlet ........................ specification.
A) 2.1 C) 2.2
B) 2.3 D) 2.4
ANSWER: B
26. ..................... is the first phase of the servlet life cycle.
A) Initialization C) Destruction
B) Service D) Both a and b
ANSWER: A
28
Advance Java Programming (17625)
27. The service phase of the servlet life cycle represents all interactions with requests until
the servlet is ......................
A) created C) initiated
B) running D) destroyed
ANSWER: D
28. JSP is not governed by the ................... defined by the Java 2 specifications.
A) syntax and semantics C) Jakarta tomcat
B) rules and regulation D) compiler
ANSWER: A
29. JSP embeds in ................ in ......................
A) Servlet, HTML
B) HTML, Java
C) HTML, Servlet
D) Java, HTML
Answer: Java, HTML
30. State true or false for the following statements in Java.
i) Java beans slow down software development process.
ii) Java Servlets do not have built in multithreading feature.
A) i-false, ii-false C) i-true, ii-false
B) i-false, ii-true D) i-true, ii-true
Answer: i-false, ii-false
31. State whether true or false.
i) init( ) of servlet is called after a client request comes in
ii) Servlets are ultimately converted into JSP
A) i-false, ii-false C) i-true, ii-false
B) i-false, ii-true D) i-true, ii-true
Answer:i-false, ii-false
32. Java Servlet
i) is key component of server side java development
ii) is a small pluggable extension to a server that enhances functionality
iii) runs only in Windows Operating System
iv) allows developers to customize any java enabled server
A) i, ii & iii are ture
29
Advance Java Programming (17625)
30
Advance Java Programming (17625)
D) Secure
ANSWER: C) Robust
39. In the following statements identify the disadvantages of CGI?
A) If number of clients increases, it takes more time for sending response
B) For each request, it starts a process and Web server is limited to start processes
C) It uses platform dependent language e.g. C, C++, perl
D) All mentioned above
ANSWER: D) All mentioned above
40. Servlet technology is used to create web application?
A) True
B) False
ANSWER: A) True
41. In HTTP Request Which Asks for the loopback of the request message, for testing or
troubleshooting?
A) PUT
B) OPTIONS
C) DELETE
D) TRACE
ANSWER: D) TRACE
42. In HTTP Request method Get request is secured because data is exposed in URL bar?
A) True
B) False
ANSWER: B) False
43. In the HTTP Request method which is non-idempotent?
A) GET C) BOTH A & B
B) POST D) None of the above
ANSWER: B) POST
44. Give the examples of Application Server from the following?
A) Apache C) JBoss
B) Tomcat D) Weblogic
E) Both C & D
ANSWER: E) Both C & D
31
Advance Java Programming (17625)
32
Advance Java Programming (17625)
B) ServletContext
C) Both A & B
D) None of the above
ANSWER: B) ServletContext
51. An attribute in servlet is an object that can be set, get or removed from one of the
following scopes?
A) session scope
B) request scope
C) application scope
D) All mentioned above
ANSWER: D) All mentioned above
52. How many techniques are used in Session Tracking?
A) 4
B) 3
C) 2
D) 5
ANSWER: A) 4
53. Which cookie it is valid for single session only; it is removed each time when user closes
the browser?
A) Persistent cookie
B) Non-persistent cookie
C) Both A & B
D) None of the above
ANSWER: B) Non-persistent cookie
54. Which object of HttpSession can be used to view and manipulate information about a
session, such as the?
A) session identifier
B) creation time
C) last accessed time
D) All mentioned above
ANSWER: D) All mentioned above
55. Which methods are used to bind the objects on HttpSession instance and get the objects?
A) setAttribute
33
Advance Java Programming (17625)
B) getAttribute
C) Both A & B
D) None of the above
ANSWER: C) Both A & B
56. Which class provides stream to read binary data such as image etc. from the request
object?
A) ServltInputStream
B) ServletOutputStream
C) Both A & B
D) None of the above
ANSWER: A) ServltInputStream
57. These methods doGet(),doPost(),doHead,doDelete(),deTrace() are used in?
A) Genereic Servlets
B) HttpServlets
C) Both A & B
D) None of the above
ANSWER: B) HttpServlets
58. Sessions is a part of the SessionTracking and it is for maintaining the client state at server
side?
A) True
B) False
ANSWER: A) True
59. In Session tracking which method is used in a bit of information that is sent by a web
server to a browser and which can later be read back from that browser?
A) HttpSession
B) URL rewriting
C) Cookies
D) Hidden form fields
ANSWER: C) Cookies
60. Using mail API we cannot send mail from a servlet?
A) True
B) False
ANSWER: B) False
34
Advance Java Programming (17625)
35
Advance Java Programming (17625)
36
Advance Java Programming (17625)
37
Advance Java Programming (17625)
D) 7
ANSWER: B) 9
77. In JSP page directive which attribute defines the MIME(Multipurpose Internet Mail
Extension) type of the HTTP response?
A) import
B) Content Type
C) Extends
D) Info
ANSWER: B) Content Type
78. The Jsp include directive is used to include the contents of any resource it may be?
A) jsp file
B) html file
C) text file
D) All mentioned above
ANSWER: D) All mentioned above
79. In JSP how many ways are there to perform exception handling?
A) 3
B) 2
C) 4
D) 5
ANSWER: B) 2
80. In JSP Action tags which tags are used for bean development?
A) jsp:useBean
B) jsp:setPoperty
C) jsp:getProperty
D) All mentioned above
ANSWER: D) All mentioned above
81. In JSP Action tags which is used to include the content of another resource it may be jsp,
html or servlet?
A) jsp:include
B) jsp:forward
C) jsp:plugin
38
Advance Java Programming (17625)
D) jsp:papam
ANSWER: A) jsp:include
82. A bean encapsulates many objects into one object, so we can access this object from
multiple places?
A) True
B) False
ANSWER: A) True
83. In JSP action tags Which are used for developing web application with Java Bean?
A) jsp:useBean
B) jsp:setProperty
C) jsp:getProperty
D) Both B & C
ANSWER: D) Both B & C
84. Model View Controller in JSP which represents the state of the application i.e. data. It can
also have business logic?
A) Model
B) View
C) Controller
D) None of the above
ANSWER: A) Model
85. Seperation of business logic from JSP this is the advantage of?
A) Custom Tags in JSP
B) JSP Standard Tag Library
C) Both A & B
D) None of the above
ANSWER: A) Custom Tags in JSP
86. JSPs eventually are compiled into Java servlets, you can do as much with JSPs as you can
do with Java servlets?
A) True
B) False
ANSWER: A) True
87. Which is the Microsoft solution for providing dynamic Web content?
A) ASP
39
Advance Java Programming (17625)
B) JSP
C) Both A & B
D) None of the above
ANSWER: A) ASP
88. In which attribute specifies a JSP page that should process any exceptions thrown but not
caught in the current page?
A) The ErrorPage Attribute
B) The IsErrorPage Attribute
C) Both A & B
D) None of the above
ANSWER: A) The ErrorPage Attribute
89. JSP’s provide better facilities for separation of page code and template data by mean of
Java beans, EJBs and custom tag libraries?
A) True
B) False
ANSWER: A) True
90. The ASP and JSP technologies are quite similar in the way they support the creation of
Dynamic pages, using HTML templates, scripting code and components for business
logic?
A) True
B) False
ANSWER: A) True
91. CGI is a set of rules that works as an __________________
a. Interface between web server
b. External programs on the web server
c. Both a & b
d. None of these
Answer: c
92. __________ are created dynamically in response to user request:
a. Virtual Documents
b. `Dynamic document
c. Both of these
d. None if these
40
Advance Java Programming (17625)
41
Advance Java Programming (17625)
42
Advance Java Programming (17625)
Important MCQ
A.FlowLayout B.BorderLayout
C.GridLayout D.NullLayout
Q.2 The method setLabel can be used with what type of Object ?
A.DoubleField. B.int.
C.TextField. D. String
Q.3 The Swing Component classes that are used in Encapsulates a mutually
exclusive set of buttons?
A. AbstractButton B.ButtonGroup
C.Jbutton D.ImageIcon
A.Graphics B.Applet
C.Container D. Component
each other.
A. BorderLayout B. BoxLayout
C.CardLayout D. OverlayLayout
C.BorderLayout D.BoxLayout
Q. 7 ________ displays a message that alerts the user and waits for the user to
43
Advance Java Programming (17625)
A. mb.addMenuItem(mu) B. mb.addItem(mu)
A. ActionEvent B.ComponentEvent
A.Datagrams. B. Sockets
44
Advance Java Programming (17625)
by the socket.
A. getInetAddress() B.LocalPort()
C.getPort() D.getLength()
A.50 B.60
C.70 D.80
Q. 17 Which of the following methods are needed for laoding a database driver
in JDBC?
applications?
A.Type-4 B.Type-1
C.Type-3 D.Type -2
be used.
A. executeQuery() B.executeDeleteQuery()
C.executeUpdate() D.executeDelete
Q. 20 Which JDBC driver Type (s) can be used in either applet or servelt code?
Q. 21 Name the class that can be used to get the cookies from the client
browser
A. HttpServletResponse B. HttpServletRequest
C. SessionContext. D.SessionConfig.
C. DHTML D. CGI
A. getParameter B.getParameterNames
C. getParameterValues D.getParameterVal
Q.24 Servlets classes specific to your application are palced in which directory
A. /lib/ B./WEB-INF/classes/.
C./classes D./WEB-INF/lib/
A.mu.addMenuItem(mi) B.mu.add(mi)
46
Advance Java Programming (17625)
Q. 29 When two or more objects are added as listeners for the same event,
Q. 32 The URL connection classes are good enough for simple programs that
A.FTP B.TCP
C.HTTP D.UDP
47
Advance Java Programming (17625)
datagram ?
A.InetAddressgetAddress() B.intgetPort()
architecture?
Q. 37 Which kind of driver converts JDBC calls into calls on the client API for
ThreadModelinterface ___________
48
Advance Java Programming (17625)
A. URL rewriting ,using session object, using response object, using hidden
fields.
B. URL rewriting, using session object, using cookies, using hidden fields
C. URL rewriting , using servlet object, using response object, using cookies.
D. URL rewriting , using request object, using response object , using session object
Q. 41 State true or false for the following statements in Java
TextField(10);
importjava.awt.
public staticvoidmain
(String argv[]
49
Advance Java Programming (17625)
s. set Size(300,200);
A. s.setBackgraound(Color.pink): B. s.setColor(PINK);
C. s.Background(pink); D. s.color = Color.pink
extends Frame
pack() ; setVisible(true);
( Stringargs []
}
50
Advance Java Programming (17625)
</applet>*/
{
public void init ()
{
addMouseListener
(
new Mouse Adapter()
{
inttopX, bottom Y;
public void Mousepressed ( Mouseevent me)
topX = me.getX();
bottom = me.getY();
);
51
Advance Java Programming (17625)
importjava.applet.*;
importjava.awt. Event.*;
implementsActionListener
TextField t1,t2,t3;
t1 = new TextField(5);
t2 = new TextField(5);
b1.addActionListener(this);
b2.addActionListener(this)
b3.addAction Listener;
52
Advance Java Programming (17625)
b4.addAction Listener;
{ ______________________________________________//expected here
if (e.getSourc() ==b1)
int n1=Integer.parseInt(t1.getText());
int n2=Integer.parseInt(t2.getText());
t3.setText(Integer.toString(n3));
if (e.getSourc() ==b2)
int n1=Integer.parseInt(t1.getText());
int n2=Integer.parseInt(t2.getText());
t3.setText(Integer.toString(n3));
if (e.getSourc() ==b3)
int n1=Integer.parseInt(t1.getText());
int n2=Integer.parseInt(t2.getText());
t3.setText(Integer.toString(n3));
if (e.getSourc() ==b4)
int n1=Integer.parseInt(t1.getText());
53
Advance Java Programming (17625)
int n2=Integer.parseInt(t2.getText());
t3.setText(Integer.toString(n3));
following code
importjava.awt. *;
54
Advance Java Programming (17625)
Q. 49 correct the following code to add " this is top " as shown in figure below
importjava.awt.*;
55
Advance Java Programming (17625)
importjava.awt. Container;
importjava.awt. Font;
importjava.awt. Gridlayout;
importjava.awt. Jbutton;
importjava.awt. JFrame;
{
public static void main ( String [] args )
A.http B.https
C.www D.com
{
public static void main ( String [] args )
}
}
A.1 B.0
{
public static void main (String ar[])
57
Advance Java Programming (17625)
{
String url ="jdbc: odbc:mydsn";
Class.forName ( "sun.jdbc.odbc.jdbcOdbcDriver");
ResultSetrs =executeQuery("select * from login ");
while ( rs.next())
System.outprintIn (rs.getString(1));
}
}
catch(Exception ee)
System .outprintIn(ee);
{
System.outprintln(rs.getInt(1) + " " + rs. getString(2));
}
A.deletes the record B. retrieve the record
class Test
58
Advance Java Programming (17625)
try{
While (rs.next())
importjava.sql.*;
try{
59
Advance Java Programming (17625)
________________________________________________
while (rs.next())
database.
classMysqlCon
try {
60
Advance Java Programming (17625)
ResultSetrs = _____________________________________________________
while (rs.next())
catch (Exception e )
System.out.println(e);
A.sun.jdbc.odbc.JdbcOdbcDriver
}
61
Advance Java Programming (17625)
{
res. set content type ( "text/html"); String dta = req. get Parameter ("data"); PrintWriter
pw = res. getWriter ();
cookiecookie = new Cookie ( "My cookies " data) ;
cookie.setMaxAge(1); req.addCookie (cookie);
pw. print In ("<b> Information collected by cookie. </b><br>");
pw. print In ("<b> value of cookie : <b>"+cookie.get Value () +" <br>");
pw. print In ("<b> version of cookie : <b>"+cookie.get Versions () +" <br>"); pw. print
In ("<b>MaxAgeof cookie : <b>"+cookie.getMaxAge () +" <br>"); pw. print In ("<b>
my cookie : <b>" has been set to ");
62
Advance Java Programming (17625)
}
}
a. cookie cookie = new Cookie (MyCooke", data) ; req.addCookie (coookie);
b.cookie cookie = new Cookie ("MyCooke", data) ; req.addCookie (coookie);
c.cookie cookie = new Cookie ("MyCooke", data) ; res.addCookie (coookie);
d.cookie cookie = new Cookie ("MyCooke", data) ; res.addCookie (coookie);
Q. 60 select the proper code for mapping of welcome servlet
<param -name>Gramin</param-value>
</context-param>
</web-app>
a.<servlet><servlet-name>WelcomeServlet</servlet-name></servlet>
b. <servlet><<servlet-name>WelcomeServlet</servlet-name><servlet-
nameWelcomeServlet</servlet-class>
c. <servlet-mapping><servlet-nameWelcomeServlet./servlet-class><url-
pattern>/WelcomeServlet</servlet-class></servlet-mapping>
d. <servlet-name>WelcomeServlet</servlet-class></servlet-mapping>
Q. 61 following servlet read parameters passed through the html page. Write
importjava.util.&;
importjavax.servlet.*;
throwsServletException, IOException
63
Advance Java Programming (17625)
PrintWriter pw = res.getWriter();
Enumeration E= reg.getPaarameterNames();
strignpaname =(string)e.nextElecment();
pw .printIn (pvalue);
pw. close();
<html><head><title><title>
charset= UTF-8">
underlined line
64
Advance Java Programming (17625)
import java.io.*;
importjavax. Servlet.*;
importjavax.servlet. Http.*;
else
pw. close () ;
65
Advance Java Programming (17625)
66
Advance Java Programming (17625)
Set - 2
Q. 1 Which method exectues only once
A. star() method B.init() method
C.stop() method D.destroy()method
Q. 2 The general form to set a specific type of layout manager is
A. void setLayout(LayoutManager 1m)
B. Void setLayout(LayoutManager 1m)
C. void setLayout(layoutManager 1m)
D. Void setLayout(LayoutManager 1m)
Q. 3 Which h costructor creates a TextArea with 10 rows and 20 columns ?
A. new TextArea(new Rows(10),new columns(20)).
B.new TextArea(20 , 10 )
C. new TextArea(10 , 20 )
D. new TextArea(200 )
Q.4 You want to construct a text area that is 80 character-widths wide and 10
character-heights tall. What code do you use ?
A. new TextArea( 80,10) B. new TextArea( 10,80)
c. new TextArea( 40,80) D. new TextArea( 80,40)
Q. 5 Which of the following components allow multiple selections ?
A. Combo box. B. Radio buttons.
C. Choice. D. List
Q.6 What is the difference between a TextArea and a TextField?
A. A TextArea can handle multiple lines of text
B. A textarea can be used for output
C. TextArea is not a class
D. TextArreas are used for displaying graphics
Q. 7 Which of these package is used for graphical user interface ?
A. java.applet B.java.awt
C.java.awt. Image D. java.io
Q. 8Which method is used to set the text of a Label object?
A.setText() B. setLabel()
C. setTextLabel () D. setLabelText()
Q. 9 The ________ interface is used to handle button events:
A. ContainerListener B. ItemListener
C. ActionListener D. WindowListener
67
Advance Java Programming (17625)
Q. 10 Which of these methods can e used to obtain the command name for
invokingActionEvent object?
A.getCommand() B. getActionCommand()
C.getActionEvent() D. getActioneEventCommand()
Q.11 FocusEvent is subclass of which of these calsses ?
A. ComponenEvent B.ContainerEvent
C.ItemEvent D.InputEvent
Q. 12 Which of these are integer constants of TexEventclass ?
A. TEXT_CHANGED B.TEXT_FORMAT_CHANGED
C.TEXT_VALUE_CHANGED D.TEXT_SIZE_CHANGED
Q. 13 If sockets have been invalidated _____________ are used to send and
receive data.
A. IP stream. B. TCP
C. UDP. D.I/O stream
Q. 14 Which of these class is necessary to implement datagrams?
A.DatagramPacket B.DatagramSocket
C. Both of metioned D. None of the mentioned
Q. 15 Which of these method of DatagramPacket is used to obtain the byte
array of data contained in a datagram?
A. getDat() B.getBytes()
C.getArray() D.recieveBytes()
Q. 16 Which of these method of Datagram Packet is used to find the length of
byte array ?
A. getnumber() B.length()
C. Length() D.getLength ()
Q. 17 Why do you need the JDBC API?
A. ODBC is not appropriate for direct use from the Java programming language
because it uses a C intterface
B. A literal translation of the ODBC C API into a Java API would not be
dresirable
C. ODBC is hard to learn
D. All mentioned above
Q. 18 A JDBC technology -based driver ("JDBC driver") makes it possible to
do ?
A.Establish a connection with a data source
B. Send queries and update statements to the data source
68
Advance Java Programming (17625)
69
Advance Java Programming (17625)
70
Advance Java Programming (17625)
Q. 38 in which the result set generally does not show changes to the
underlying database that are made while it is open. The membership,
order, and column values of ows are typically fixed when the result set is
created?
A. TYPE_FORWARD_ONLY B.TYPE_SCROLL_INSENSITIVE
C.TYPE_SCROLL_SENSITIVE D.ALL MENTIONED ABOVE
Q. 39 The method getWriter returns an object of type PrintWriter. This class
hasprintln methods to generate output. Which of these classes define
the get Writer method ?
A. HttpServletRequest B. httpServletResponse
C.ServletConfig. D.ServletContext
Q. 40 State whether true or false
i) init() of servlet is called after a client request comes in
ii) Servlets are ultimately converted into JSP
A. i-false, ii-false B. i-false, ii-true
C.i-true, ii-false D.i-true , ii-true
Q. 41 In the following statements identify the disadvantages of CGI?
A.If number of clients increases, it takes more time for sending response
B. For each request, it starts a process and Web server is limited to start
processes
C. It uses platform dependent language e.g. C,C++,perl
D. All mentioned above
Q. 42 Import java.awt.*:
Import java.awt.event.*;
Importjava. Applet.*;
public class Pral extends Applet implements ActionListener
{
String s; Label a ;
Button b;
TextArea t;
public void init ()
{
a = nw Label ( Enter Address: ",LabelLEFT);
b = new Button ("OK");
t= new TextArea( 5,20);
add (a);
add(t ) add (b);
b. add ActionListener(this);
}
public void actionPerformed (ActionEventae)
71
Advance Java Programming (17625)
{
if (ae.getSource()==b)
{
repaint();
}
}
public void paint ( Graphics gr )
{
s=t.getText(0; gr.drawString ("User Address is : " +s,150,150);
}
}
/*<applet code = Pral width = 400 height = 300 ></applet>*/
A. Add(a);,add(f);,add(b);,b.addListner(this)
B. add(f);,add(b);,b.addListner(this)
C. Add(a);,add(f);,b.addListner(this)
D. Add(a);,add(f);,add(b);
Q. 43 import java. Awt .*:
Button b;
Choice c ;
List l ;
TextField t1;
TextArea t2;
Labellb,l1,h;
CheckboxGroup cg;
b=new Buttoon("Submit");
c=new Choice () ;
72
Advance Java Programming (17625)
add(lb);
add(t1);
add(l);
add(c);
add(l1);
add(t2);
add(h);
add(pc);
add(ss);
add(cgm);
add(b);
l.add("ME");
l.add("CO");
l.add("CE");
l.add("IF");
}
73
Advance Java Programming (17625)
Q. 44 import java.awt.*;
importjava.awt. Event.*;
importjavax.swing.*;
b1.addActionListener(this);
cp.add(b1);
b2.addActionListener(this);
cp.add(b2);
JRadioButton("Green"); b3.addActionListener(this);
cp.add(b3);
74
Advance Java Programming (17625)
String S;
s= ae.getActionCommand();
if (s=="Red") cp.setBackground(Color.red);
cp.setBackground(Color.green);
75
Advance Java Programming (17625)
A.F.SetVisible(true); B. F.SetVisible();
C.F.SetLayout(true); D. SetVisible(true)
importjava.awt.event.*;
TextFieldtf; Aevent ()
tf.setBounds(60,50,170,20);
add ( b);
add(tf);
setSize(3600,300);
setLayout(null);
setVisible (true);
tf.setText("Welcome");
newAEvent();
76
Advance Java Programming (17625)
A. b.addActionListener() B. b.add()
C.b.addListener(0 D.b.ActionListener ()
A.Applet B. ComponentEvent
C. Event D. InputEvent
A. MouseDragged() B. MousePressed()
A.ActionEvent B.ComponentEvent
C.AdjustmentEvent D.WindowEvent
Q. 50 Which of the following are valid return types, for listener methods ?
class networking
system.out print(obj.getHost());
77
Advance Java Programming (17625)
A. sanfoundry B.sanfoundry.com
class networking
system.out print(obj.getHost());
A.126 B.127
Q. 53 Write a java code to access id, age, first from table given below
78
Advance Java Programming (17625)
(sql);while (rs.next())
{
int id = rs. getInt("id");
int age = rs. getInt ("age");
String first= rs.getstring ("first");
String last = rs.getstring ("last")
//Displayvalues System.out . print ("ID: "+id ) ;
System.out .print (",Age: " + age);
System.out .print (",First : " + first) ;
System.out .print (",Last :" + last) ;
79
Advance Java Programming (17625)
B. PreparedStatementpstmt = null;
try{
String SQL = "Update
Employees SET age = ? WHERE id = ? ";
pstmt = conn.prepareStatement (SQL);
… }
catch (SQLException e )
{ …
}
finally {
pstmt. Close ();
}
C. PreparedStatementpstmt = null;
try {
String SQL = "Update
Employees SET age = ? WHERE id = ? ";
pstmt = conn.
prepareStatement (SQL);
… }
catch (SQLException e )
80
Advance Java Programming (17625)
{ …
} finally
{
pstmt. Close ();
}
D.both a and c
classjJDBCMetaData
try{
// Execute the query ResultSetrs = stmt. executeQuery ( "SELECT * FROM Cust " );
81
Advance Java Programming (17625)
<=md.getColumnCount () ;
(inti = 1;
// Close the result set, statement and the connection rs. close ();
stmt. close () ;
catch ( SQLException se )
catch ( Exception e )
{
82
Advance Java Programming (17625)
A. Type -1 B. Type-4
C.Type-3 D. Type-2
A.prepareStatement B.prepareCall
is used
A. 4k B. 8k
C. 2k D.1k
83
Advance Java Programming (17625)
C. Container D. cleat
response.setContentType("text/html");
_________________________________________..___________________________
String out.println("<html>");
out.println("<body>");
}
Output
A. request.getParameter(?username");
B. Request.getParameter ("password")
C. Both A & B
84