0% found this document useful (0 votes)
28 views18 pages

Ass 3

The document provides information about servlets and servlet life cycle. It asks several questions and provides explanations. It first asks about the differences between doGet() and doPost() methods and explains servlets. It then explains the servlet life cycle in 5 steps - (1) servlet class is loaded, (2) instance is created, (3) init method is invoked, (4) service method is invoked, and (5) destroy method is invoked. It describes each step and shows the servlet states. The document also discusses deployment descriptors with an example web.xml file and explains session tracking mechanisms like cookies, URL rewriting, and hidden form fields. It asks about ServletContext and

Uploaded by

yashthummar003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views18 pages

Ass 3

The document provides information about servlets and servlet life cycle. It asks several questions and provides explanations. It first asks about the differences between doGet() and doPost() methods and explains servlets. It then explains the servlet life cycle in 5 steps - (1) servlet class is loaded, (2) instance is created, (3) init method is invoked, (4) service method is invoked, and (5) destroy method is invoked. It describes each step and shows the servlet states. The document also discusses deployment descriptors with an example web.xml file and explains session tracking mechanisms like cookies, URL rewriting, and hidden form fields. It asks about ServletContext and

Uploaded by

yashthummar003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Assignment-3

UNIT-3
◆Answer the following Question:
1) What are the major differences between doGet() and doPost()?
Explain with examples.

2) What is Servlet? Explain the servlet life cycle in detail.


Java Servlets are programs that run on a Web or Application
server and act as a middle layer between a requests coming
from a Web browser or other HTTP client and databases or
applications on the HTTP server.
Using Servlets, you can collect input from users through web
page forms, present records from a database or another
source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs
implemented using the Common Gateway Interface (CGI). But
Servlets offer several advantages in comparison with the CGI.

The web container maintains the life cycle of a servlet instance.


Let's see the life cycle of the servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

Life cycle of a servlet


As displayed in the above diagram, there are three states of a
servlet: new, ready and end. The servlet is in new state if
servlet instance is created. After invoking the init() method,
Servlet comes in the ready state. In the ready state, servlet
performs all the tasks. When the web container invokes the
destroy() method, it shifts to the end state.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The
servlet class is loaded when the first request for the servlet is
received by the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after
loading the servlet class. The servlet instance is created only
once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after
creating the servlet instance. The init method is used to
initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface. Syntax of the init method is
given below:
public void init(ServletConfig config) throws ServletException
,IOException

4) service method is invoked


The web container calls the service method each time when
request for the servlet is received. If servlet is not initialized, it
follows the first three steps as described above then calls the
service method. If servlet is initialized, it calls the service
method. Notice that servlet is initialized only once. The syntax
of the service method of the Servlet interface is given below:

public void service(ServletRequest request, ServletResponse


response)
throws ServletException, IOException
5) destroy method is invoked
The web container calls the destroy method before removing
the servlet instance from the service. It gives the servlet an
opportunity to clean up any resource for example memory,
thread etc. The syntax of the destroy method of the Servlet
interface is given below:
public void destroy()
https://www.javatpoint.com/life-cycle-of-a-servlet
3) Difference between GenericServlet and HttpServlet.
4) Explain the steps for implementing MVC with Requestdispatcher.
The RequestDispatcher interface provides the facility of
dispatching the request to another resource it may be html,
servlet or jsp. This interface can also be used to include the
content of another resource also. It is one of the way of servlet
collaboration.
There are two methods defined in the RequestDispatcher
interface.
Methods of RequestDispatcher interface
The RequestDispatcher interface provides two methods. They
are:

1) public void forward(ServletRequest request,ServletResponse


response)throws
ServletException,java.io.IOException:Forwards a request
from a servlet to another resource (servlet, JSP file, or HTML
file) on the server.
2) public void include(ServletRequest request,ServletResponse
response)throws
ServletException,java.io.IOException:Includes the content of
a resource (servlet, JSP page, or HTML file) in the response.
Example of RequestDispatcher interface
In this example, we are validating the password entered by the
user. If password is servlet, it will forward the request to the
WelcomeServlet, otherwise will show an error message: sorry
username or password error!. In this program, we are cheking
for hardcoded information. But you can check it to the
database also that we will see in the development chapter. In
this example, we have created following files:
1. index.html file: for getting input from the user.
2. Login.java file: a servlet class for processing the response. If
password is servet, it will forward the request to the
welcome servlet.
3. WelcomeServlet.java file: a servlet class for displaying the
welcome message.
4. web.xml file: a deployment descriptor file that contains the
information about the servlet.
5) What is a Deployment Descriptor? Explain with Example.
The deployment descriptor is an xml file, from which Web
Container gets the information about the servet to be invoked.
The web container uses the Parser to get the information from
the web.xml file. There are many xml parsers such as SAX, DOM
and Pull.
There are many elements in the web.xml file. Here is given
some necessary elements to run the simple servlet program.

web.xml file
<web-app>

<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

</web-app>
Description of the elements of web.xml file
There are too many elements in the web.xml file. Here is the
illustration of some elements that is used in the above web.xml
file. The elements are as follows:
<web-app> represents the whole application.
<servlet> is sub element of <web-app> and represents the
servlet.
<servlet-name> is sub element of <servlet> represents the
name of the servlet.
<servlet-class> is sub element of <servlet> represents the class
of the servlet.
<servlet-mapping> is sub element of <web-app>. It is used to
map the servlet.
<url-pattern> is sub element of <servlet-mapping>. This pattern
is used at client side to invoke the servlet.

6) What is a Session? Explain different ways of session tracking


Mechanism.
Session simply means a particular interval of time. Session
Tracking is a way to maintain state (data) of an user. It is also
known as session management in servlet.
Http protocol is a stateless so we need to maintain state using
session tracking techniques. Each time user requests to the
server, server treats the request as the new request. So we
need to maintain the state of an user to recognize to particular
user.
HTTP is stateless that means each request is considered as the
new request. It is shown in the figure given below:
Session Tracking tracks a user’s requests and maintains their
state. It is a mechanism used to store information on specific
users and in order to recognize these user’s requests when
they connect to the web server.
HTTP is a stateless protocol where each request to the server is
treated like a new request. However, there are ways to
maintain the data for a particular user in order to serve them
specific content.
There are several ways to track user sessions including cookies,
URL rewriting, and hidden form fields.
1. Cookies
A cookie is a unique ID assigned to clients when they first visit a
website. Whenever this client connects to the server again, it
will send the cookie that was given earlier by the server. The
server will then recognize that it is the same user.
2. Hidden form fields
Hidden form fields are used to insert information, e.g., a unique
ID when sending a request to the server. These fields are not
directly visible to the user, but each time a request is sent to
the server, the unique ID is also sent as a part of the request,
enabling the server to recognize the client.
3. URL rewriting
URL rewriting adds a unique session ID in the URL itself when it
sends a request to the server. Since the session ID is part of the
URL, it is directly visible to users.
7) Explain ServletContext and ServletConfig with examples.
In Java, ServletContext and ServletConfig are important interfaces
that are part of the Java Servlet API. They are used in the
development of web applications to provide configuration
information and access to the environment in which the servlet is
running.

1. **ServletContext:**
ServletContext represents a servlet's view of the web application
within which the servlet is running. It's unique for each web
application and is used to communicate with the servlet container.
ServletContext is mainly used for sharing resources across different
parts of the web application.

Here's an example of how ServletContext is used:

```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class MyServlet extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// Get the ServletContext


ServletContext context = getServletContext();
// Set a specific attribute in the ServletContext
context.setAttribute("myAttribute", "Hello, ServletContext!");

// Retrieving the attribute from ServletContext in another


servlet
// ExampleServlet.java
}
}
```

2. **ServletConfig:**
ServletConfig represents the configuration of a specific servlet in a
web application. It's created by the web container for each servlet
and used to pass initialization information to the servlet. It allows the
servlet to access information such as initialization parameters.

Here's an example of how ServletConfig is used:

```java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class MyServlet extends HttpServlet {


private String myParam;
public void init(ServletConfig config) throws ServletException {
super.init(config);
// Get initialization parameter from web.xml
myParam = config.getInitParameter("myParam");
}

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
// Use myParam in the servlet logic
// ...
}
}
```

In both cases, ServletContext and ServletConfig are used in the


development of Java web applications to manage and configure the
behavior of servlets. While ServletContext is for communication with
the servlet container and sharing resources across the web
application, ServletConfig is for passing initialization information to
the servlet.
8) Difference between forward() and sendRedirect() method.
9) Discuss any seven common Status codes. And how to send status
Code?
The following are the most useful HTTP status codes that might
be sent from a Servlet. For a more complete list, see the HTTP
protocol, and the Wikipedia entry on HTTP status codes. Some
of the codes not included in this list are either rarely used
generally, or make very little sense from the point of view of a
Servlet.

1. Status code 301 SC_MOVED_PERMANENTLY


Indicates a permanent redirection. Sending this code tells the
client that "the location of this resource has now changed", and
that the client should use a new URL in the future. If you send
this code, you should also set the Location response header
with the new location:
String newURL = res.encodeRedirectURL("...");
res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY
);
res.setHeader("Location", newURL);

At least some search engines appear to take notice of this


redirection, but of course some may not. Note the call to
encodeRedirectURL()1, which will make sure that any request
parameters are preserved.
2. Status code 307 SC_TEMPORARY_REDIRECT
This code is sometimes called a temporary redirect. Like the
previous code, it indicates that the resource is at a different
URL. A browser should instead request the provided URL, but,
for example, a search engine shouldn't permanently update its
database with the new URL. A more convenient way of sending
this code is to use the special method on HttpServletResponse:
String newURL = res.encodeRedirectURL("...");
res.sendRedirect(newURL);

3. Status code 400 SC_BAD_REQUEST


This code is useful if you parse parts of the URL or requeset
parameters in order to decide on your Servlet's response. If the
client sends parameters that are invalid in some way, you can
send this response code.
4. Status code 403 SC_FORBIDDEN
This code may be useful for more "serious" denials of requests,
for example if the user is in the wrong territory. Usually, for a
"not logged in" message to the user, you would want to return
a normal, "friendly" response.
5. Status code 404 SC_NOT_FOUND
Useful if your Servlet is dynamically interpreting the URL and
returning page content accordingly. On the other hand, when
the user requests a normal static page that isn't found (i.e.
when not going through your Servlet), most web servers such
as Apache will automatically return the 404 response code, plus
a default or customised response page.
10) What is Cookie? Differentiate session cookies with
persistent cookies.
A cookie is a small piece of information that is persisted
between the multiple client requests.
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.
By default, each request is considered as a new request. In
cookies technique, we add cookie with response from the
servlet. So cookie is stored in the cache of the browser.
After that if request is sent by the user, cookie is added
with request by default. Thus, we recognize the user as the
old user.

In Java web development, cookies are small pieces of data that


are sent from a web server to a user's web browser and are
typically used to store information about the user or their
interaction with the website. There are two main types of
cookies: session cookies and persistent cookies. Let's
differentiate between these two types of cookies in the context
of advanced Java web development:

1. Session Cookies:
- Session cookies are also known as transient cookies.
- They are stored temporarily in the user's browser memory
(RAM) during the user's visit to a website.
- Session cookies are often used to store temporary
information about the user's session, such as a session ID or
user authentication status.
- These cookies are automatically deleted when the user
closes their web browser or when the session expires (e.g., due
to inactivity).
- In Java web applications, you can create session cookies
using Java Servlets or frameworks like JavaServer Faces (JSF).
The `HttpSession` object is commonly used to manage session
data.

Example in Java Servlets:


```java
HttpSession session = request.getSession();
session.setAttribute("username", "john_doe");
```

2. Persistent Cookies:
- Persistent cookies are also known as stored cookies or long-
term cookies.
- They are stored on the user's device even after the user
closes their web browser.
- Persistent cookies have an expiration date set by the server,
and they can persist for a specified duration, even across
multiple sessions and browser restarts.
- These cookies are often used to remember user
preferences, login credentials, or other user-specific data.
- In Java web applications, you can create persistent cookies
using the `javax.servlet.http.Cookie` class.

Example in Java Servlets:


```java
Cookie cookie = new Cookie("username", "john_doe");
cookie.setMaxAge(3600); // Cookie expires in 1 hour
response.addCookie(cookie);
```

To summarize, the key difference between session cookies and


persistent cookies in advanced Java web development lies in
their lifespan and purpose. Session cookies are short-lived and
are typically used to store temporary session-related data,
while persistent cookies are long-lived and are used to store
data that should persist across sessions. It's essential to choose
the right type of cookie based on your application's
requirements for data retention and user experience.

You might also like