Ajava - IV Unit
Ajava - IV Unit
2 marks:
1. What are servlets?
Servlets are small programs that execute on the server side of a web connection. Servlets
dynamically extend the functionality of a web server. They can respond to requests from web
clients, typically browsers, by generating dynamic content.
2. List the drawbacks of CGI programs.
• It was expensive in terms of processor and memory resources to create a separate process for each
client request.
• CGI programs were not platform-independent.
3. List the advantages of servlet.
• Performance is significantly better. Servlets execute within the address space of a web server.
• Servlets are platform-independent because they are written in Java.
• Java security manager enforces a set of restrictions to protect the resources on a server machine.
• Full functionality of the Java class libraries is available to a servlet.
4. With syntax write the purpose of getParameter() method.
String getParameter(String pname) - Returns the value of the parameter named pname.
5. What is the purpose of extending the GenericServlet class in t servlet, and what methods
does it provide by default?
The GenericServlet class provides implementations of the basic life cycle methods for a servlet.
GenericServlet implements the Servlet and ServletConfig interfaces. In addition, a method to
append a string to the server log file is available. The signatures of this method are shown here:
void log(String s)
void log(String s, Throwable e)
Here, s is the string to be appended to the log, and e is an exception that occurred.
6. Explain the role of the ServletRequest and ServletResponse objects in the service() method.
The ServletRequest interface enables a servlet to obtain information about a client request. The
ServletResponse interface enables a servlet to formulate a response for a client.
7. What is ServletConfig Interface? Mention any 2 methods.
The ServletConfig interface allows a servlet to obtain configuration data when it is loaded. The
methods declared by this interface are summarized here:
ServletContext getServletContext( ) Returns the context for this servlet.
String getServletName( ) String getServletName( )
8. What is the purpose and significance of the getWriter() method in the context of generating
an HTTP response in a servlet?
It returns a PrintWriter that can be used to write character data to the response. An
IllegalStateException is thrown if getOutputStream( ) has been previously invoked on this object.
10. What is the role of the getServletConfig() and getServletInfo() methods in the Servlet
interface.
The getServletConfig( ) method is called by the servlet to obtain initialization parameters. A servlet
developer overrides the getServletInfo( ) method to provide a string with useful information (for
example, author, version, date, copyright). This method is also invoked by the server.
11. Differentiate between the getInitParameter(String param) and getInitParameterNames()
methods in the ServletConfig interface.
Returns the value of the initialization parameter named
String getInitParameter(String param)
param.
Enumeration<String>
Returns an enumeration of all initialization parameter names.
getInitParameterNames( )
12. What is the purpose and usage of the getAttribute(String attr) and setAttribute(String
attr, Object val) methods in the ServletContext interface.
Object getAttribute(String attr) Returns the value of the server attribute named
attr.
void setAttribute(String attr, Object val) Sets the attribute specified by attr to the value
passed in val.
14. What is the usage of readLine(byte[] buffer, int offset, int size)method in the
ServletInputStream class?
The readLine() method is provided to read bytes from the stream. It is shown here:
int readLine(byte[ ] buffer, int offset, int size) throws IOException
Here, buffer is the array into which size bytes are placed starting at offset. The method returns the
actual number of bytes read or –1 if an end-of-stream condition is encountered.
15. What's the specific purpose of ServletOutputStream and ServletInputStream?
The ServletInputStream class extends InputStream. It is implemented by the servlet container and
provides an input stream that a servlet developer can use to read the data from a client request.
The ServletOutputStream class extends OutputStream. It is implemented by the servlet container
and provides an output stream that a servlet developer can use to write data to a client response.
16. List classes that are provided in the javax.servlet.http package.
Cookie Allows state information to be stored on a client machine.
HttpServlet Provides methods to handle HTTP requests and responses.
HttpSessionEvent Encapsulates a session-changed event.
HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a session value.
17. Write the usage of any two methods described in the HttpServletResponse interface.
void addCookie(Cookie cookie) Adds cookie to the HTTP response.
boolean containsHeader(String field) Returns true if the HTTP response header contains a
field named field.
26. What is the main purpose of the JDBC to ODBC (Type 1) driver?
The main purpose of the JDBC to ODBC (Type 1) driver is to provide a bridge that allows Java
applications to connect to databases that support the Open Database Connectivity (ODBC) standard.
This driver acts as an intermediary between JDBC and ODBC, translating JDBC calls into ODBC
calls, thereby enabling the use of ODBC drivers to access databases.
27. Differentiate between Type 3 and Type 4 JDBC drivers. Which one is considered to be the
fastest way to communicate SQL queries to the DBMS?
Type 3 Driver (Java Protocol) Type 4 Driver (Database Protocol)
Uses a middleware server Connects directly to the database
Converts SQL to JDBC format first, then into the
Translates SQL directly to DBMS format
format required by the DBMS.
Generally slower Generally faster
28. What is the difference between the executeQuery() and executeUpdate() methods of a
Statement object in JDBC?
executeQuery(): This method returns the ResultSet object that contains rows, columns and metadata
that represent data requested by the query. This method is used to execute only the 'SELECT' query
of SQL.
executeUpdate(): This method is used to execute the queries that contain INSERT, DELETE and
UPDATE statements. It returns integer indicating the number of rows that were updated by the
query.
29. Briefly explain what a ResultSet object represents in JDBC.
ResultSet object contains data requested by the query. It also contains methods that are used to copy
data from the ResultSet into a Java collection of objects or variable(s) for further processing. Data
in a ResultSet object is logically organized into a virtual table consisting of rows and columns.
30. What is the main advantage of using a PreparedStatement object over a Statement object
in JDBC?
PreparedStatement objects are pre-compiled by the database when they are first created. When you
execute the same PreparedStatement multiple times with different data, the database can reuse this
plan, leading to faster execution compared to Statement objects where the query is recompiled each
time.
31. How do PreparedStatement objects handle dynamic values in SQL queries?
PreparedStatement objects handle dynamic values in SQL queries by using placeholders (also
known as parameter markers) denoted by question marks (?) within the SQL statement. These
placeholders are then substituted with actual values using setter methods provided by the
PreparedStatement class. This approach ensures that the SQL statement remains constant while
allowing the values to change dynamically.
32. What are the different parameters used by CallableStatement object?
IN A parameter whose value is unknown when the SQL statement is created. You bind
values to IN parameters with the setXXX() methods.
OUT A parameter whose value is supplied by the SQL statement it returns. You retrieve values
from the OUT parameters with the getXXX() methods.
INOUT A parameter that provides both input and output values. You bind variables with the
setXXX() methods and retrieve values with the getXXX() methods.
2. Develop a basic servlet program that displays a welcome message to the user.
HelloServlet.java
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("Welcome!");
pw.close();
}}
web.xml
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet/HelloServlet</url-pattern>
</servlet-mapping>
6. Write a Java servlet named FormProcessorServlet that can handle HTTP POST requests
containing form data. The servlet should: Read Parameters: Extract the names and values of
parameters submitted from the form. Process Data: Access the specific parameter values for
fields like "name" and "email" (assuming those are the form field names). Generate
Response: Create an HTML response that displays the submitted data back to the user in a
user-friendly format.
Index.html
<html> <head><title>Form</title></head>
<body> <center>
<form method="post" action="http://localhost:8081/sample/a">
<table> <tr> <td> <b>Employee</td>
<td><input type="textbox" name="e" size="25" value=""></td> </tr>
<tr> <td> <b>Email</td>
<td><input type="email" name="p" size="50" value=""></td> </tr>
</table>
<input type="submit" value="Submit">
</form> </center> </body> </html>
Web.xml
<web-app> <servlet>
<servlet-name>FormProcessorServlet</servlet-name>
<servlet-class>Form ProcessorServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FormProcessorServlet</servlet-name>
<url-pattern>/a</url-pattern>
</servlet-mapping> </web-app>
formProcessorServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Form ProcessorServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String name request.getParametert(“e”);
String email = request.getParameter("p");
response.setContentType("text/html");
Print Writer pw = response.getWriter(); pw.println("<html><body>");
pw.println("<b>Name of the Employee is: </b>" + name + "<br>");
pw.println("<b>Email of the Employee is: </b>" + email);
pw.println("</body></html>");
pw.close();
}
7. Explain the following methods of HttpServletRequest interface with their syntax
i. getCookies ii. getMethod iii. getPathInfo iv. getSession
Cookie[ ] getCookies( ) Returns an array of the cookies in this request.
String getMethod( ) Returns the HTTP method for this request.
String getPathInfo( ) Returns any path information that is located after the servlet path
and before a query string of the URL.
HttpSession getSession( ) Returns the session for this request. If a session does not exist,
one is created and then returned.
HttpSession If new is true and no session exists, creates and returns a session
getSession(boolean new) for this request. Otherwise, returns the existing session for this
request.
8. With an example, Explain the purpose and behavior of the doGet() method in a servlet
class.
The doGet( ) method is overridden to process any HTTP GET requests that are sent to this servlet. It
uses the getParameter( ) method of HttpServletRequest to obtain the selection that was made by the
user. A response is then formulated.
index.html
<html> <body> <center>
<form action="http://localhost:8080/servlets-examples/servlet/ColorGetServlet">
<b>Color:</b>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select> <br><br>
<input type=submit value="Submit">
</form> </body> </html>
ColorGetServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<b>The selected color is: ");
pw.println(color);
pw.close();
}}
9. With an example, Explain the purpose and behavior of the doPost() method in a servlet
class.
The doPost( ) method is overridden to process any HTTP POST requests that are sent to this servlet.
It uses the getParameter( ) method of HttpServletRequest to obtain the selection that was made by
the user. A response is then formulated.
index.html
<html> <body> <center>
<form method="post"action="http://localhost:8080/servlets-examples/servlet/ColorPostServlet">
<b>Color:</b>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select> <br><br>
<input type=submit value="Submit">
</form> </body> </html>
ColorPostServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color"); //Get the selected color from the requested parameter
response.setContentType("text/html"); //Set the response content type
PrintWriter pw = response.getWriter(); //Get PrintWriter object
pw.println("<b>The selected color is: "); //Write HTML repsonse
pw.println(color);
pw.close(); //Close PrintWriter
}}
10. What are the different methods involved in the process of session management in servlets?
Explain their purpose.
getSession(boolean create): This method retrieves or creates an HttpSession object associated with
the current request. If no session exists and `create` is set to `true`, a new session will be created. If
`create` is set to `false` and no session exists, `null` is returned.
Example: HttpSession session = request.getSession(true); // create a session if none exists
setAttribute(String name, Object value): Binds an object to a specific name in the session. The
name parameter specifies the name under which the object will be stored and value indicates the
object to be associated with the name.
getAttribute(String name): Retrieves an object associated with a given name from the session. The
name parameter specifies the name under which the object was bound to the session. It returns the
object bound to the specified name, or null if no object is associated with that name.
removeAttribute(String name): Removes an object associated with a given name from the session.
The name parameter specifies the name of the object to be removed. It returns None(void method).
getAttributeNames(): This method retrieves an enumeration of all attribute names currently bound
to the session. It returns an Enumeration object containing the names of all attributes in the session.
11. How cookies can be handled using servlet.
The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state
information. Cookies are valuable for tracking user activities. For example, 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 he or she visits the store.
A servlet can write a cookie to a user‟s machine via the addCookie( ) method of the
HttpServletResponse interface. The data for that cookie is then included in the header of the HTTP
response that is sent to the browser. The names and values of cookies are stored on the user’s
machine. Some of the information 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
• The domain and path of the cookie
The expiration date determines when this cookie is deleted from the user’s machine. If an expiration
date is not explicitly assigned to a cookie, it is deleted when the current browser session ends.
Otherwise, the cookie is saved in a file on the user‟s machine.
The domain and path of the cookie determine when it is included in the header of an HTTP request.
If the user enters a URL whose domain and path match these values, the cookie is then supplied to
the Web server. Otherwise, it is not.
There is one constructor 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.
12. Explain why JSP is a compelling choice for web development compared to the Common
Gateway Interface (CGI).
Java Server Pages often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But JSP offers several advantages in comparison with the CGI.
• Performance is significantly better because JSP allows embedding Dynamic Elements in HTML
Pages itself instead of having separate CGI files.
• JSP are always compiled before they are processed by the server unlike CGI/Perl which requires
the server to load an interpreter and the target script each time the page is requested.
• Java Server Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to
all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
• JSP pages can be used in combination with servlets that handle the business logic, the model
supported by Java servlet template engines.
13. Explain the key steps involved in how a web server processes a JSP request and generates
a web page.
• As with a normal page, browser (client) 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. This code 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.
• Apart 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. This output is further passed on to the
web server by the servlet engine inside an HTTP response.
• The web server forwards the HTTP response to our browser in terms of static HTML content.
• Finally, the web browser handles the dynamically-generated HTML page inside the HTTP
response exactly as if it were a static page.
14. Explain the key stages involved in the lifecycle of a Java Server Page (JSP).
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:
• Parsing the JSP.
• Turning the JSP in to a servlet.
• Compiling the servlet.
JSP Initialization
When a container loads a JSP it invokes the jspInit() method before servicing any requests.
Typically, initialization is performed only once we generally initialize database connections, open
files, and create lookup tables in the jspInit method. If we need to perform JSP-specific
initialization, override the jspInit() method:
Public void jspInit(){ //Initializationcode... }
JSP Execution
This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine
invokes the _jspService() method in the JSP.
The _jspService() method of a JSP is invoked on request basis. This is responsible for generating
the response for that request and this method is also responsible for generating responses to all
seven of the HTTP methods, i.e., GET, POST, DELETE, etc.
JSP Cleanup
The destruction phase of the JSP lifecycle represents when a JSP is being removed from use by a
container. The jspDestroy() method is the destroy method. Override jspDestroy when you need to
perform any cleanup, such as releasing database connections or closing open files. The jspDestroy()
method has the following form:
public void jspDestroy() { //Yourcleanupcodegoeshere. }
15. Write short note on JSP directives and JSP Actions.
JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@directive attribute="value"%>
There are three types of directive tag:
Directive Description
<%@ page... %> Defines page-dependent attributes, such as scripting language, error
page and buffering requirements.
<%@ include... %> Includes a file during the translation phase.
<%@ taglib... %> Declares a tag library, containing custom actions, used in the page
JSP Actions
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or
generate HTML for the Java plugin. There is only one syntax for the Action element, as it conforms
to the XML standard:
<jsp:action_name attribute="value"/>
Action elements are basically predefined functions. Following table lists out the JSP Actions:
Syntax Purpose
jsp:include Includes a file at the time the page is requested.
jsp:useBean Finds or instantiates a JavaBean.
jsp:setProperty Sets the property of a JavaBean.
jsp:getProperty Inserts the property of a JavaBean into the output.