You are on page 1of 13

Servlet

Servlet technology is used to create web application (resides at server side and generates
dynamic web page).

Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a request 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.

Servlets Tasks:

Servlets perform the following major tasks:

Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an applet or a custom HTTP client program.

Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands

Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response directly.

Send the explicit data (i.e., the document) to the clients (browsers). This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.

Send the implicit HTTP response to the clients (browsers). This includes telling the browsers
or other clients what type of document is being returned (e.g., HTML), setting cookies and
caching parameters, and other such tasks.

The basic terminology used in servlet are given below:

1. HTTP

2. HTTP Request Types

3. Difference between Get and Post method

4. Container

5. Server and Difference between web server and application server

6. Content Type

7. Introduction of XML

8. Deployment

1
1.HTTP (Hyper Text Transfer Protocol)
1. Http is the protocol that allows web servers and browsers to exchange data over the web.

2. It is a request response protocol.

3. Http uses reliable TCP connections bydefault on TCP port 80.

4. It is stateless means each request is considered as the new request. In other words,
server doesn't recognize the user bydefault.

2. Http Request Methods


Every request has a header that tells the status of the client. There are many request methods.
Get and Post requests are mostly used.

The http request methods are:

1. GET 2. POST 3. HEAD 4. PUT 5. DELETE 6. OPTIONS 7. TRACE

What is the difference between Get and Post?

GET POST

1) In case of Get request, only limited In case of post request, large amount of
amount of data can be sent because data is data can be sent because data is sent in
sent in header. body.

2) Get request is not secured because data is Post request is secured because data is
exposed in URL bar. not exposed in URL bar.

3) Get request can be bookmarked Post request cannot be bookmarked

4) Get request is idempotent. It means second Post request is non-idempotent


request will be ignored until response of first
request is delivered.

2
5) Get request is more efficient and used Post request is less efficient and used
more than Post less than get.

Container
It provides runtime environment for JavaEE (j2ee) applications.

It performs many operations that are given below:

1. Life Cycle Management

2. Multithreaded support

3. Object Pooling

4. Security etc.

Server
It is a running program or software that provides services.

There are two types of servers:

1. Web Server

2. Application Server

Web Server
Web server contains only web or servlet container. It can be used for servlet, jsp, struts,
jsf etc. It can't be used for EJB.

Example of Web Servers are: Apache Tomcat and Resin.

Application Server
Application server contains Web and EJB containers. It can be used for servlet, jsp,
struts, jsf, ejb etc.

Example of Application Servers are:

1. JBoss Open-source server from JBoss community.

2. Glassfish provided by Sun Microsystem. Now acquired by Oracle.

3. Weblogic provided by Oracle. It more secured.

4. Websphere provided by IBM.

3
Content Type
Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is a HTTP
header that provides the description about what are you sending to the browser.

There are many content types:

text/html text/plain application/msword application/vnd.ms-excel

application/jar application/pdf application/octet-stream application/x-zip

images/jpeg video/quicktime So on

Reading input Data (or) Form Data from the Browser (or)

Interface HttpServletRequest Methods

1. getParameter

public String getParameter(String name)

Returns the value of a request parameter as a String, or null if the parameter does not
exist.
Request parameters are extra information sent with the request.
For HTTP servlets, parameters are contained in the query string or posted form data.

2. getParameterValues

public String[] getParameterValues(String name)

Returns an array of String objects containing all of the values the given request
parameter has, or null if the parameter does not exist.

If the parameter has a single value, the array has a length of 1.

3. getParameterMap

public Map getParameterMap()

Returns a java.util.Map of the parameters of this request.

4. getParameterNames

public Enumeration getParameterNames()

Returns an Enumeration of String objects containing the names of the parameters


contained in this request.
if the request has no parameters, the method returns an empty Enumeration.

4
5. getQueryString

public String getQueryString()

Returns the query string that is contained in the request URL after the path.
This method returns null if the URL does not have a query string.

test1.html
1. getParameter

<form action="servlet6">
First Name : <input type = 'text' name = 'param' /><br>
Last Name : <input type = 'text' name = 'param' /> <br>
Skills :
<input type='checkbox' name='skills' value="java"/>JAVA
<input type='checkbox' name='skills' value="android"/>ANDROID<br>
Gender
<input type='radio' name='gender' value="male" >MALE</input>
<input type='radio' name="gender" value='female' />FEMALE</br><br>
<input type = 'submit' value = 'sumbit' />
</form>

Web.xml

<web-app>
<servlet>
<servlet-name>s1 </servlet-name>
<servlet-class>sashi.kumar.Servlet1 </servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1 </servlet-name>
<url-pattern>/servlet1 </url-pattern>
</servlet-mapping>
<web-app>

Servlet1.java

5
package sashi.kumar;

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

public class Servlet1 extends HttpServlet


{
public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
PrintWriter out = res.getWriter();
String s1 = req.getParameter("param");

out.println("<br> Parameter : " + s1); // Parameter : Sashi


}
}

2. getParameterMap

Servlet2.java

public class Servlet3 extends HttpServlet


{
protected void service(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{

PrintWriter out = res.getWriter();

Map map = req.getParameterMap();

String names[] = (String[]) map.get("param");


String[] skills = (String[]) map.get("skills");
String []gender = (String[])map.get("gender");

out.println("Names : " + Arrays.toString(names));


out.println("Skills : " + Arrays.toString(skills));
out.println("Gender : " + Arrays.toString(gender));

/* Names : [Sashi, Kumar]


Skills : [java, android]
Gender : [male] */

for(String name : names)


out.println("Name : " + name);

/* Name : Sashi
Name : Kumar */

6
for (String skill : skills)
out.println("Skill : " + skill);

/* Skill : java
Skill : android */

for (String gender1 : gender)


out.println("Gender : " + gender1);
// Gender : male
}
}

3. getParameterValues

public class Servlet2 extends HttpServlet {


protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
PrintWriter out = res.getWriter();

String values[] = req.getParameterValues("param");


String[] skills = req.getParameterValues("skills");
String []gender = req.getParameterValues("gender");

out.println("Values : " + Arrays.toString(values));


out.println("Skills : " + Arrays.toString(skills));

for (String g : gender )


{
out.println("Gener : " + g);
}
}
}
Output:
Values : [Kalai, Vani]
Skills : [java, android]
Gener : male

4. getParameterNames

public class Servlet5 extends HttpServlet


{
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
PrintWriter out = res.getWriter();

Enumeration names = req.getParameterNames();

7
String name;
String values[];

while (names.hasMoreElements())
{
name = (String) names.nextElement(); // To find out Property Name
out.println("Name : " +name);

values = req.getParameterValues(name);
// Finding out values for the particular name
out.println("Values : " + Arrays.toString(values));

}
}
}
Output:

Name : skills
Values : [java, android]
Name : param
Values : [Sashi, Kumar]
Name : gender
Values : [male]

5. getQueryString

public class Servlet4 extends HttpServlet


{
protected void service(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
PrintWriter out = res.getWriter();

String queryString = req.getQueryString();


out.println("Query String : " + queryString);

String keysAndValues[] = queryString.split("&");


out.println(keysAndValues :+Arrays.toString(keysAndValues));

for (String pair : keysAndValues)


{

String key = pair.substring(0,pair.indexOf("="));


String value = pair.substring(pair.indexOf("=")+1,pair.length());
out.println("Key :"+key+"; Value :"+value);
}
}
}

Output:

Query String : param=Sashi&param=Kumar&skills=java&skills=android&gender=male

8
keysAndValues : [param=Sashi, param=Kumar, skills=java, skills=android, gender=male]

Key :param; Value :Sashi


Key :param; Value :Kumar
Key :skills; Value :java
Key :skills; Value :android
Key :gender; Value :male

6. getinitParameter

public String getInitParameter(String name)

These constants are specific to the particular Servlets.


Here p1 and p2 are only for Servlet6.
This method is available inside ServletConfig interface.
Returns the parameter value for the specified parameter name.

Web.xml

<servlet>

<servlet-name>s6 </servlet-name>
<servlet-class>sashi.kumar.Servlet6 </servlet-class>

<init-param>
<param-name>p1 </param-name>
<param-value>1000 </param-value>
</init-param>

<init-param>
<param-name>p2 </param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</init-param>

</servlet>

<servlet-mapping>
<servlet-name>s6</servlet-name>
<url-pattern>/servlet6 </url-pattern>
</servlet-mapping>

Servlet6.java

public class Servlet6 extends HttpServlet


{
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException

9
{
PrintWriter out = res.getWriter();

String p1 = getInitParameter("p1");
String p2 = getInitParameter("p2");
/* ServletConfig config = getServletConfig();
String p1 = config.getInitParameter("p1");
String p2 = config.getInitParameter("p2");*/
out.println("P1 : " +p1);
out.println("P2 : " +p2);
}
}
Output:

P1 : 1000
P2 : oracle.jdbc.driver.OracleDriver

7. getinitParameterNames

public Enumeration getInitParameterNames()

Returns an enumeration of all the initialization parameter names.


This method is available inside ServletConfig interface.

Servlet6.java

// We dont need html file to Run this ...


// http://localhost:7070/app1/servlet6

package sashi.kumar;

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

public class Servlet6 extends HttpServlet


{
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
PrintWriter out = res.getWriter();

Enumeration names = getInitParameterNames();

String name;
String value;

while (names.hasMoreElements())
{

10
name = (String)names.nextElement();
value = getInitParameter(name);

out.println("name : "+name + " ; values : "+value);


}
}
}

Output :

name : p2 ; values : oracle.jdbc.driver.OracleDriver


name : p1 ; values : 1000

8. getInitParameter

public String getInitParameter(String name)


Returns the parameter value for the specified parameter name.
This method is available inside ServletContext interface.
Global Servlet constants can be accessed through this methods

web.xml

<servlet>
<servlet-name>s7 </servlet-name>
<servlet-class>sashi.kumar.Servlet7</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s7</servlet-name>
<url-pattern>/servlet7 </url-pattern>
</servlet-mapping>

<context-param>
<param-name>p3</param-name>
<param-value>Sashi Kumar </param-value>
</context-param>

<context-param>
<param-name>p4 </param-name>
<param-value>false</param-value>
</context-param>

Here p3 and p4 are global constants to all the servlets.

Servlet7.java

public class Servlet7 extends HttpServlet


{
protected void service(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
11
{
PrintWriter out = res.getWriter();

ServletContext context = getServletContext();

String p3 = context.getInitParameter("p3");
String p4 = context.getInitParameter("p4");

out.println("P3 : " + p3);


out.println("P4 : " + p4);
}
}

Output:

P3 : Sashi Kumar
P4 : false

7. getinitParameterNames

public Enumeration getInitParameterNames()

Returns the names of the context's initialization parameters.


This method is available inside ServletContext interface.
Global Servlet constants can be accessed through this methods.

Servlet9.java

public class Servlet9 extends HttpServlet


{
protected void service(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
PrintWriter out = res.getWriter();

ServletContext context = getServletContext();

Enumeration names = context.getInitParameterNames();

String name, value;


while (names.hasMoreElements())
{
name = (String) names.nextElement();
value = context.getInitParameter(name);

out.println("Name : "+ name + " ; " + value);


}
}
}

Output:

Name : p3 ; Sashi Kumar


12
Name : p4 ; false

13

You might also like