You are on page 1of 49

servlets

Servlets class-1

servlets:

servlets is technology used to write the programming a server side.

servlet is a object executed at server side.

servlet are used to design web applciation.

//servlets vs. CGI(comman gateway interface) :

CGI :

Here every requets one process is created.

if no of requests are increased then no of processes are incereased it effects on performace

servlets :

Here every requets one thread is created.

if no of requests are increased then no of threads are incereased but performace ig good because thread is light
weight.

There two types of servers

a. web servers

web container = servlet contianer + jsp engine

ex: jetty, IAS, upto tomcat 4.0...

b. application servers

applciation server = web container + EJB contianer

ex: tomcat ---- Apache

jboss ---- red hat

weblogic ---- oracle

websphere ---- IBM

galssfish ---- sun (oracle)

Download the tomcat9 :

https://tomcat.apache.org/download-90.cgi

32-bit/64-bit Windows Service Installer (pgp, sha512)

Tomcat installation process just check below points.

a. check the check boxes


host manager

example

b. Http port number by default tomcat will take 8080

so change the port any 4-digit number because oracle default port 8080

c. just give the tomcat username & password

user name : tomcat

password : tomcat

d. uncheck the check box

run apache tomcat

Once the installation completed the tomcat folder location is,

C:\Program Files\Apache Software Foundation\Tomcat 9.0

The tomcat contains 7-folders

bin : it contains binary executables used to start & stop the server.

start the server using tomcat9 executable file

after starting the server connect to server using below url

http://localhost:9999/

in server page we have hostmanger here we are deploying web application.

config : it contians configurations details of the server

To change the port number : server.xml

to change the username & password : tomcat-user.xml

to configure the connection pooling use context.xml

log : it contains log file track the error messages & server startup & ending time.

temp : contians temp files

webapps :

once the application is completed we have to deploy the apllication in webapps.

deploy the applicaiton means we have to place the apllication in web apps folder.
so the webapps folder contains group of web application.

work:

in jsp technology every jsp page internally converted to servet. That converted serlet executed we will get the
response.

the jsp converted to servlet & these converted servlets are stored in work folder.

lib:

This folder contians libraries (.jar)

The servlet predefined support in the form of jar file : servlet-api.jar

the jsp predefined support in java from of jar file : jsp-api.jar

The predefiend support jar files are present in lib folder.

The servlet predeinfed support in the form of three pacakges

a. javax.servlet

b. javax.servlet.http

c. javax.servlet.annotations

it is possible to open the .class file using java decompiler.

Servlet class-2

There are three ways to create a servlet.

a. implements Servlet

b. extends GenericServlet

c. extends HttpServlet

First Application:

//Servlet predefined support:

package javax.servlet;

import java.io.IOException;

public interface Servlet

{ void init(final ServletConfig p0) throws ServletException;

ServletConfig getServletConfig();

void service(final ServletRequest p0, final ServletResponse p1) throws ServletException, IOException;
String getServletInfo();

void destroy();

class MyServlet implements Servlet

{ must override 5 methods

life cycle methods: automatically called by server.

a. init() : servlet initializations

b. service() : to write the business logics

c. destory() : servlet destory.

This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are
known as life-cycle methods and are called in the following sequence:

init() : The servlet is constructed, then initialized with the init method.

service() : Any calls from clients to the service method are handled.

destory() : The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and
finalized.

In addition to the life-cycle methods, this interface provides the getServletConfig method, which the servlet can use to get
any startup information, and the getServletInfo method, which allows the servlet to return basic information about itself,
such as author, version, and copyright.

web application folder structure :

MyApp

|--->.html

|--->.jsp

|--->imags

|--->.js

|--->.css

|---> WEB-INF

|--->web.xml

|--->lib

|--->*.jar

|--->classes

|---> MyServlet1.class
|---> MyServlet2.class

|---> MyServlet3.class

//web.xml

it is mapping file between client to servlets

DD file : deployment descriptor : all deployed resoources information present in web.xml

Myservlet ----- To the servlet create the url then client can access the servlet using url.

to create the url use web.xml

To configure every servlet we need two tags :

<servlet>

<servlet-mapping>

<web-app>

<servlet>

<servlet-name>MyServlet</servlet-name>

<servlet-class>com.tcs.MyServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>MyServlet</servlet-name>

<url-pattern>/MyServlet</url-pattern>

</servlet-mapping>

</web-app>

public void service(ServletRequest req,ServletResponse res)throws ServletException,java.io.IOException

Called by the servlet container to allow the servlet to respond to a request.

This method is only called after the servlet's init() method has completed successfully.

Parameters:

req - the ServletRequest object that contains the client's request

res - the ServletResponse object that contains the servlet's response

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/
Servlets class-3

To specefy the response type,

response.setContentType("text/html");

the default response type is "text/html"

PrintWriter : used to add the data in response object

PrintWriter writer = response.getWriter();

once the application is completed configure the server & run the applciation.

http://localhost:8888/ServletFirstApp/MyServlet

http : hyper text transfer protocal

localhost : ip address

8888 : port number

ServletFirstApp : Project name

MyServlet : resource name

init(): this method executed only once when we sent first request.

when we send multiple request to the same servlet

1-req : init() service() : 3-sec + 2sec : 5sec

2-req : service() : 2sec

3-req : service() : 2sec

4-req : service() : 2sec

in above case the response time is changes between requets

To overcome above problem perfrom the servlet initialization during server startup use <load-on-startup> in web.xml

<servlet>

<servlet-name>MyServlet</servlet-name>

<servlet-class>com.tcs.MyServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>
<load-on-startup> is taking positive number which represents priority(0,1,2,3...). it must be positive number but if we give
negative number no error just it will ignore <load-on-startup> configurations.

//MyServlet.java

package com.tcs;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.Servlet;

import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

public class MyServlet implements Servlet {

public MyServlet() {

public void init(ServletConfig config) throws ServletException {

System.out.println("init() method");

public void destroy() {

System.out.println("destory() method");

public ServletConfig getServletConfig() {

System.out.println("getServletConfig() method");

return null;

public String getServletInfo() {

System.out.println("getServletInfo() method");

return null;

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {

System.out.println("Service() method");
//general setting

response.setContentType("text/html");

PrintWriter writer = response.getWriter();

writer.println("This is First Servlet Application......");

limitation of first Approach is we must implements 5-methods but generally we need only one method to write the logics.

Approach-2:

public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable{

Defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend HttpServlet instead.

interface Servlet

{ 5- abstract methods

abstract class GenericServlet implements Servlet

{ 4-methods default implementations are completed 1-abstract method service()

class MyServlet extends GenricServlet

{ here just override service() method.

//SecondServlet.java

package com.tcs;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

public class SecondServlet extends GenericServlet {

private static final long serialVersionUID = 1L;

public SecondServlet() {

super();

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter writer = response.getWriter();

writer.println("This is GenricServlet Example....");

//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"


xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">

<display-name>ServletFirstApp</display-name>

<servlet>

<servlet-name>MyServlet</servlet-name>

<servlet-class>com.tcs.MyServlet</servlet-class>

<load-on-startup>0</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>MyServlet</servlet-name>

<url-pattern>/MyServlet</url-pattern>

</servlet-mapping>
<servlet>

<description></description>

<display-name>SecondServlet</display-name>

<servlet-name>SecondServlet</servlet-name>

<servlet-class>com.tcs.SecondServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>SecondServlet</servlet-name>

<url-pattern>/SecondServlet</url-pattern>

</servlet-mapping>

</web-app>

servlet Day - 4

Approach-3 :

interface Servlet

{ 5-methods

abstract class GenericServlet implements Servlet

{ 4-impl completed 1-abstract method service()

abstract class HttpServlet extends GenericServet

{ all implementation are completed : service() implementation also completed

class myServlet extends HttServlet

{ override the required request method

doGet()

doPost()

doPut()

doDelete()

doTrace()

doOptions()

doHead()

Based on the client request the related method will be executed at server side.
if the client sends get request --- server side doGet() method

if the client sends post request --- server side doPost() method

Note : the default request type is get request.

The life cycle methods : init() service() destroy()

The server will call HttpServlet service() method, The HttpServlet contians two service() methods.

a. public service() :

public service() will call by server.

converting normal request types to Http request types.

after converting it is calling protected service by passing http types.

b. protected service()

it is identifying the request type then forwarding the request to corresponding method.

//internal implementations of HttoServlet service() methods.

public abstract class HttpServlet extends GenericServlet

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

final String method = req.getMethod();

if (method.equals("GET")) {

this.doGet(req, resp);

else if (method.equals("HEAD")) {

this.doHead(req, resp);

else if (method.equals("POST")) {

this.doPost(req, resp);

else if (method.equals("PUT")) {

this.doPut(req, resp);

else if (method.equals("DELETE")) {
this.doDelete(req, resp);

else if (method.equals("OPTIONS")) {

this.doOptions(req, resp);

else if (method.equals("TRACE")) {

this.doTrace(req, resp);

else {

String errMsg = HttpServlet.lStrings.getString("http.method_not_implemented");

final Object[] errArgs = { method };

errMsg = MessageFormat.format(errMsg, errArgs);

resp.sendError(501, errMsg);

public void service(final ServletRequest req, final ServletResponse res) throws ServletException, IOException {

HttpServletRequest request;

HttpServletResponse response;

try {

request = (HttpServletRequest)req;

response = (HttpServletResponse)res;

catch (ClassCastException e) {

throw new ServletException(HttpServlet.lStrings.getString("http.non_http"));

this.service(request, response); //calling the protected service by passsing the http types

ex:

package com.tcs;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class ThirdServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public ThirdServlet() {

super();

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {

response.setContentType("text/html");

PrintWriter writer = response.getWriter();

writer.println("This is DoGet() appliation....");

specefying the post :

To handle the post request we need html pages.

//form.html

<html>

<body>

<form method="post" action="./ThirdServlet">

click me post : <input type="submit" value="clickme">

</body>

</html>

we can send the request to servlet in differnet ways

a. we are typeing url sending request.

b. sending the request by clicking button


Servlet Day-5

//LoginApplication

//login.html

<html>

<body bgcolor='red'>

<form action="./login" method="get">

Name:<input type="text" name="uname"/><br/>

Password:<input type="password" name="upwd"/><br/>

<input type="submit" value="login"/>

</form>

</body>

</html>

a. Action tag url pattren send to server side.

b. method="get" : sending get request to server side.

c. <input type="text" name="uname"/> here "name" is logical name of the textfiled.

//LoginServlet.java

package com.tcs;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public LoginServlet() {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {
//general settings

response.setContentType("text/html");

PrintWriter writer = response.getWriter();

//Reading the data from request object sent by client

String username = request.getParameter("uname");

String password = request.getParameter("upwd");

//main business logics

if(username.equalsIgnoreCase("ratan") && password.equals("anu"))

{ writer.println("<body bgcolor='pink'><h1><center>Hi "+username+" Login


Success....</center></h1></body>");

else

{ writer.println("<body bgcolor='pink'><h1><center>Hi "+username+" Login


Fail....</center></h1></body>");

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {

doGet(request, response);

Note : The data from client browser is String by default.

this is url send to server side :

http://localhost:8888/LoginApplication/login.html

//welcome file configurations.

The first page of the web application is called welcome file. And we have to configure the the welcome file in web.xml

<welcome-file-list>

<welcome-file>login.html</welcome-file>

</welcome-file-list>

//forwarding request to html files


if(username.equalsIgnoreCase("ratan") && password.equals("anu"))

{ RequestDispatcher dispatcher = request.getRequestDispatcher("success.html");

dispatcher.forward(request, response);

else

{ RequestDispatcher dispatcher = request.getRequestDispatcher("fail.html");

dispatcher.forward(request, response);

//forward the request to some other websites

if(username.equalsIgnoreCase("ratan") && password.equals("anu"))

{ response.sendRedirect("http://www.nareshit.com");

else

{ response.sendRedirect("http://www.facebook.com");

RequestDispatcher vs. sendRedirect :

RequestDispatcher : this will work with in the server

sendRedirect : out side of server

Servlets class-6

//doGet() vs. doPost() :

doGet() :

a. Protected service() of HttpServlet will call get method.

b. this is default request type.

c. get url, not secure

http://localhost:8888/LoginApplication/LoginServlet?uname=ratan&upwd=anu

d. when we sent get request the protocal will create the "Request Format" with only header.

here no body field so the request body is append to haader field. so the requested data visisble in url.

e. using get() we can send the less request details to server side because it contians onnly header part.

f. it will cache the url so data is not secure.


doPost() :

a. Protected service() of HttpServlet will call post method.

b. this is not default request type. We have to specify using <form method="post">

c. post url, secure

http://localhost:8888/LoginApplication/LoginServlet

d. when we sent post request the protocal will create the "Request Format" with header & body fileds.

here body field avaialbel so the request body is append to body field. so the request body not visible in url

e. using POST() we can send the more request details to server side because it contians header & body part.

f. it will not cache the data.

There are two types of prototcals :

a. Transport protocal

HTTP , HTTPS

b. messageing protocal.

SOAP

HTTP protocal will take the request & create the connection based on ip addreess given in url.

Deployments

//Approach-1

the IDE will generate tomcat folder structure the location is,

E:\advjava9amonline\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps

in above location we will find Application tomcat folder structure so we can deploy this folders into tomcat webapps folder.

after deploy start the server access the application.

//Approach-2 war file creation.

create the war file using IDE then deploy in server console. Access the application.

//Servlet urls:

1. exact match method: here the servlet contians only one url so that we can the servlet using that url.

<servlet-mapping>

<servlet-name>MyServlet</servlet-name>

<url-pattern>/MyServlet</url-pattern>

</servlet-mapping>
http://localhost:9999/FirstApplciation/MyServlet Valid

http://localhost:9999/FirstApplciation/MyServlet1 Invalid

http://localhost:9999/FirstApplciation/MyServlet/MyServlet Invalid

2. directory match : /abc/*

<servlet-mapping>

<servlet-name>MyServlet</servlet-name>

<url-pattern>/abc/*</url-pattern>

</servlet-mapping>

http://localhost:8888/ServletFirstApp/abc/sdhf : valid

http://localhost:8888/ServletFirstApp/abc/abc : valid

http://localhost:8888/ServletFirstApp/xyz/abc : Invalid

http://localhost:8888/ServletFirstApp/abc/abc/xyz : valid

Note:In general in web applications, we will prefer to use directory match method to define an URL pattern when we have
a requirement to pass multiple numbers of requests to a particular server side resource.

3. extension match method:

<servlet-mapping>

<servlet-name>MyServlet</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

http://localhost:8888/ServletFirstApp/abc.do valid

http://localhost:8888/ServletFirstApp/abc/xyx.do valid

http://localhost:8888/ServletFirstApp/abc.dooo Invalid

*/

Registraction Application

//reg.html

<html>

<head>
<center>Registration</center>

</head>

<body>

<form method="post" action="./RegistrationServlet">

<pre>

Name <input type="text" name="uname"/>

Password <input type="password" name="upwd"/>

Qualification <input type="checkbox" name="uqual" value="BSC"/>BSC

<input type="checkbox" name="uqual" value="MCA"/>MCA

<input type="checkbox" name="uqual" value="M TECH"/>M TECH

Gender <input type="radio" name="ugen" value="MALE"/>MALE

<input type="radio" name="ugen" value="FEMALE"/>FEMALE

Technologies <select name="utech" size="3" multiple>

<option value="C">C</option>

<option value="C++">C++</option>

<option value="JAVA">JAVA</option>

</select>

Comments<input type="textarea" name="ucom" rows="5" cols="25"></textarea>

<input type="submit" value="Register"/>

</pre>

</form>

</body>

</html>

//RegistrationServlet.java

package com.tcs;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class RegistrationServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public RegistrationServlet() {

// TODO Auto-generated constructor stub

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {

response.setContentType("text/html");

PrintWriter writer = response.getWriter();

String uname = request.getParameter("uname");

String upwd = request.getParameter("upwd");

String[] uqual = request.getParameterValues("uqual");

String ugen = request.getParameter("ugen");

String[] utech = request.getParameterValues("utech");

String ucom = request.getParameter("ucom");

writer.println("<html>");

writer.println("<body bgcolor='lightgreen'>");

writer.println("<center><b><font size='6'>");

writer.println("Name....."+uname);

writer.println("<br><br>");

writer.println("Password......"+upwd);

writer.println("<br><br>");
writer.println("Qualification<br><br>");

for(String q:uqual)

{ writer.println(q);

writer.println("<br><br>");

writer.println("Gender...."+ugen);

writer.println("<br><br>");

writer.println("Technologies<br><br>");

for(String t:utech)

{ writer.println(t);

writer.println("<br><br>");

writer.println("Comments......"+ucom);

writer.println("<br><br>");

writer.println("Congratulations....."+uname);

writer.println("<br><br>U R Registration Success");

writer.println("</font></b></center></body></html>");

we can read the data from from page in three ways

a. getParameter() : it reads only one value.

b. getParameterValues() : it reads multiple values.

c. getParameternames() : it will get from page logical names.

Enumeration<String> e = request.getParameterNames();

while(e.hasMoreElements())

{ String s = e.nextElement();

writer.println(s+"-----"+request.getParameter(s)+"<br><br>");

}
//server startup process :

a. when we start the server , server identifies each & every web application create one object for every applicaion is
called

ServletContext.

b. server take the web.xml

a. loading : loads the xml into memory

b. parsing : xml tags validation : to parse it uses SAXParser

if any tag fail we will get error org.xml.sax.SAXParseException;

Parse error in application web.xml file at


[file:/E:/advjava9amonline/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/LoginApplication/WEB-
INF/web.xml]

in java we will get flexibility of modifications in two ways,

i. properties file

ii. xml files

<init-param> data</init-param> : it is specefic servlet

<context-param>data</context-param> : it is comman to entire web application(for all servlets).

c. reading

if any context-data in web.xml it will read that data placed in ServletContext object.

if any init-param-data in web.xml it will read that data placed in ServletConfig object.

c. in web.xml file any <load-on-startup> it will do the servlet initilization during server startup.

once the above steps are done server is ready to take the request.

//client side process

once the server started open the browser send the request to server then protocal will take request.

1. Protocol will establish virtual socket connection between client and server as part of the server IP address
and port number which we specified in the URL.

2. Protocol will prepare a request format having request header part and body part, where header part will
maintain request headers and body part will maintain request parameters provided by the user.

3. After getting the request format protocol will carry request format to the main server.
//server side process after taking request

server takes the request based on receiving the request from protocol main server will check whether the request
data is in well-formed format or not,, if it is in well-formed then the main server will bypass request to servlet container.

server takes this is complete url : http://localhost:8888/LoginApplication/LoginServlet

contianer will take : /LoginApplication/LoginServlet

Upon receiving the request from main server container will pick up application name and resource name from
request and check whether the resource is for any html page or Jsp page or an URL pattern for a servlet.

If the resource name is any html page or Jsp page then container will pick up them application folder and send
them as a response to client.

If the resource name is an URL pattern for a particular servlet available under classes folder then container will go
to web.xml file identifies the respective servlet class name on the basis of the URL pattern.

once the servlet is identified servlet container will perfrom servlet life cycle methods.

Servlet loading

Servlet instantiation

Servlet initialization
init(ServletConfig config)

Servlet request processing(generates response)


service(req,res)

disptach the response to client

Servlet deinstantiation
ServletConfig destroyed

Servlet unloading

//server stop

when we stop the server application unloading

when we stop the server the ServletContext object destroyed.


servlets day-9

//form.html

<html>

<body>

<a href="./FirstServlet">click here to get FirstServlet data</a><br>

<a href="./SecondServlet">click here to get SecondServlet data</a>

</body>

</html>

//FirstServlet.java

package com.tcs;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletConfig;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class FirstServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public FirstServlet() {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {

response.setContentType("text/html");

PrintWriter writer = response.getWriter();

ServletConfig config = getServletConfig();


String iparam1 = config.getInitParameter("apple");

String iparam2 = config.getInitParameter("mango");

ServletContext context = request.getServletContext();

String cparam1 = context.getInitParameter("username");

String cparam2 = context.getInitParameter("password");

writer.println("Init param-1 ...."+iparam1);

writer.println("<br>");

writer.println("Init param-2 ...."+iparam2);

writer.println("<br>");

writer.println("context param-1 ...."+cparam1);

writer.println("<br>");

writer.println("context param-2 ...."+cparam2);

writer.println("<br>");

//SecondServlet.java

package com.tcs;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletConfig;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class SecondServlet extends HttpServlet {

private static final long serialVersionUID = 1L;


public SecondServlet() {

// TODO Auto-generated constructor stub

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {

response.setContentType("text/html");

PrintWriter writer = response.getWriter();

ServletConfig config = getServletConfig();

String iparam1 = config.getInitParameter("iphone");

String iparam2 = config.getInitParameter("oneplus");

ServletContext context = request.getServletContext();

String cparam1 = context.getInitParameter("username");

String cparam2 = context.getInitParameter("password");

writer.println("Init param-1 ...."+iparam1);

writer.println("<br>");

writer.println("Init param-2 ...."+iparam2);

writer.println("<br>");

writer.println("context param-1 ...."+cparam1);

writer.println("<br>");

writer.println("context param-2 ...."+cparam2);

writer.println("<br>");

//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"


xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">

<display-name>ConfigContextApp</display-name>
<welcome-file-list>

<welcome-file>form.html</welcome-file>

</welcome-file-list>

<context-param>

<param-name>username</param-name>

<param-value>system</param-value>

</context-param>

<context-param>

<param-name>password</param-name>

<param-value>manager</param-value>

</context-param>

<servlet>

<description></description>

<display-name>FirstServlet</display-name>

<servlet-name>FirstServlet</servlet-name>

<servlet-class>com.tcs.FirstServlet</servlet-class>

<init-param>

<param-name>apple</param-name>

<param-value>10</param-value>

</init-param>

<init-param>

<param-name>mango</param-name>

<param-value>20</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>FirstServlet</servlet-name>

<url-pattern>/FirstServlet</url-pattern>

</servlet-mapping>

<servlet>

<description></description>

<display-name>SecondServlet</display-name>
<servlet-name>SecondServlet</servlet-name>

<servlet-class>com.tcs.SecondServlet</servlet-class>

<init-param>

<param-name>iphone</param-name>

<param-value>30000</param-value>

</init-param>

<init-param>

<param-name>oneplus</param-name>

<param-value>20000</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>SecondServlet</servlet-name>

<url-pattern>/SecondServlet</url-pattern>

</servlet-mapping>

</web-app>

we can send the request to server

a. we are typeing url

b. when we click the buttom

c. when we click the hyperlink

different ways to send get request to server:

a. when we type the url : by default request is get

b. <form> tag without method attribute

c. <form method="get">

d. hyper link request is get request.

to get the all init or context param data use below code:

ServletConfig config = getServletConfig();

Enumeration<String> e = config.getInitParameterNames();

while(e.hasMoreElements()){

String s = e.nextElement();

writer.println(s+"----"+config.getInitParameter(s));

writer.println("<br>");
}

ServletContext context = request.getServletContext();

Enumeration<String> e1 = context.getInitParameterNames();

while(e1.hasMoreElements()){

String s = e1.nextElement();

writer.println(s+"-----"+context.getInitParameter(s));

writer.println("<br>");

servlets day-10

observation-1: sendError

if(username.equalsIgnoreCase("ratan") && password.equals("anu"))

{ response.sendRedirect("http://www.nareshit.com");

else

{ response.sendError(808,"login fail try with valid details......");

observation-2: incluse vs. forward.

if(username.equalsIgnoreCase("ratan") && password.equals("anu"))

{ RequestDispatcher dispatcher = request.getRequestDispatcher("SuccessServlet");

dispatcher.forward(request, response);

else

{ writer.println("Login Fail....");

RequestDispatcher dispatcher = request.getRequestDispatcher("login.html");

dispatcher.include(request, response);

writer.println("Enter valid details to login.......");

}
SuccessServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.setContentType("text/html");

PrintWriter writer = response.getWriter();

writer.println("This is Success Servlet.......");

observation-3: forward vs. sendRedirect()

forward:

used to forward the request to next resource that resource must be present in same server.

it will work at server side.

it will give good performance.

the previous req,res objects are forward to next resource.

Note : servlet communication with in the server use forward.

sendRedirect():

used to forward the request to next resource that resource must be present in same or different
server.

it will work at client side : beacuse the client has to generate new request.

it required the netwrok calls.

it will create new req,res to server side.

Note: if we need the communication outside server use sendRedirect()

observation-4:Request Redirection

a. RR using hyperlinks.

just give the hyper link when we clink hyper link the request is redirected to some
other website.

b. RR using response headers.

client ----http--- server

ResponseFormat

header : www.anuit.com

body

c. RR using sendRedirect.

directly use the url to send the request to target web site.
if(username.equalsIgnoreCase("ratan") && password.equals("anu"))

//writer.println("<a href='http://facebook.com'>click the link to redirect req to fb</a>");

response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

response.setHeader("location","https://www.google.co.in");

//response.sendRedirect("http://www.nareshit.com");

else

{ response.sendError(808,"login fail try with valid details......");

Servlets day-11 Filter

preprocessing of request

client ---------f1--------f2------- servlet1

post processing of response

class MyFilter implements Filter

{ init(FilterConfig config)

doFilter(Req,Res) : write the logics here.

destory()

Note : The filter initialization is done automatically during server startup.

Filter fallows eager instantiation.

// Filter Mapping : To map the filter to servlet, the servlet url & filter url must be same.

<servlet>

url: /reg

<servlet-mapping>
<filter>

url: /reg

<filter-mapping>

<filter>

url: /reg

<filter-mapping>

ex:

//form.html

<html>

<body>

<form method="post" action="./RegServlet">

User name : <input type="text" name="uname"/><br>

user age : <input type="text" name="uage"/><br>

user address : <input type="text" name="uaddr"/><br>

<input type="submit" value="registration"/>

</form>

</body>

</html>

Note: Filter interface contains doFilter() method to write the logics.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws


IOException, ServletException

{ logics }

FilterChain continas foFilter() method to forward the request to next resource

public void doFilter(ServletRequest arg0, ServletResponse arg1) throws IOException,


ServletException

//MyFilter1.java

package com.tcs;
import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

public class MyFilter1 implements Filter {

public MyFilter1() {

public void destroy() {

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {

response.setContentType("text/html");

PrintWriter writer = response.getWriter();

int age = Integer.parseInt(request.getParameter("uage"));

if(age>20)

{ chain.doFilter(request, response);

else

{ writer.println("u r not eligible for mrg u age is below 20 years");

RequestDispatcher dispatcher = request.getRequestDispatcher("form.html");

dispatcher.include(request, response);

public void init(FilterConfig fConfig) throws ServletException {

System.out.println("filter1 init");
}

//MyFilter2.java

package com.tcs;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

public class MyFilter2 implements Filter {

public MyFilter2() {

public void destroy() {

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {

response.setContentType("text/html");

PrintWriter writer = response.getWriter();

String uaddr = request.getParameter("uaddr");

if(uaddr.equals("hyderabad"))

{ chain.doFilter(request, response);

else

{ writer.println("this application only for hyd person");

request.getRequestDispatcher("form.html").include(request, response);

}
public void init(FilterConfig fConfig) throws ServletException {

System.out.println("filter2 init");

//RegServlet.java

package com.tcs;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class RegServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public RegServlet() {

super();

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {

response.setContentType("text/html");

PrintWriter writer = response.getWriter();

String uname = request.getParameter("uname");

String uage = request.getParameter("uage");

String uaddr = request.getParameter("uaddr");

writer.println("************ U r registration success************");

writer.println("<br>");

writer.println("user name="+uname);

writer.println("<br>");

writer.println("<br>");

writer.println("user age="+uage);
writer.println("<br>");

writer.println("user naddress="+uaddr);

writer.println("<br>");

writer.println("user registration id=13456");

writer.println("<br>");

writer.println("we will find one girl for u soon.....keep smiling");

Servlets day-12 servlet with database connection

//CustomerDetails.html:

<html>

<body>

<form action="CustomerServlet" method="GET">

<p>First Name: <input type="text" name="firstName" /></p>

<p>Last Name:<input type="text" name="lastName" /></p>

<p>Mobile: <input type="text" name="mobile" /></p>

<p>E-Mail: <input type="text" name="email" /></p>

<p> Enter H.No. <input type="text" name="t1"></p>

<p> Enter Street <input type="text" name="t1"></p>

<p> Enter Area <input type="text" name="t1"></p>

<p><input type="submit" value="Register" /></p>

</form>

</body>

</html>

connections are two types :

physical conn

Here everytime the connection are recreated.

once the connection usage completed use con.close() : here the connection is destroyed.
here we are using DriverManager

logical conn

Here the pool contains 10 connection

once the connection usage completed use con.close() : here the connection not destroyed it is back pool.
Again the same conection used by other client.

Here we are using DataSource

https://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html

package com.tcs;

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.PreparedStatement;

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.sql.DataSource;

public class CustomerServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public CustomerServlet() {

// TODO Auto-generated constructor stub

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {

response.setContentType("text/html");
PrintWriter writer = response.getWriter();

String firstname = request.getParameter("firstName");

String lastname = request.getParameter("lastName");

String email = request.getParameter("email");

String mobile = request.getParameter("mobile");

String[] s = request.getParameterValues("t1");

StringBuffer sb = new StringBuffer();

for(String ss:s)

{ sb.append(ss+",");

String addr = sb.toString();

//connection creation logics

try{

/*Class.forName("oracle.jdbc.driver.OracleDriver");

Connection connection =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","ratan");

*/

//Connection connection = TestCon.dataSource.getConnection();

Context initContext = new InitialContext();

DataSource ds = (DataSource)initContext.lookup("java:/comp/env/mypool");

Connection connection = ds.getConnection();

PreparedStatement preparedStatement = connection.prepareStatement("insert into customer


values(?,?,?,?,?)");

preparedStatement.setString(1, firstname);

preparedStatement.setString(2, lastname);

preparedStatement.setString(3, email);

preparedStatement.setString(4, mobile);
preparedStatement.setString(5, addr);

int x = preparedStatement.executeUpdate();

if(x==1)

{ writer.println("data Inserted Successfully");

else

{ writer.println("data Insertion fail.....");

connection.close();

catch(Exception e)

{ e.printStackTrace();

//TestCon.java : this is third party vendor : apache

package com.tcs;

import org.apache.commons.dbcp.BasicDataSource;

public class TestCon {

static BasicDataSource dataSource=null;

static{

dataSource = new BasicDataSource();

dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:xe");

dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");

dataSource.setUsername("system");

dataSource.setPassword("ratan");

dataSource.setMaxActive(10);

//server side connection pooling


1) $TOMCAT_HOME\conf\context.xml

<?xml version='1.0' encoding='utf-8'?>

<Context path="">

<Resource name="mypool" type="javax.sql.DataSource" auth="Container" description="" maxActive="15" maxIdle="30"


maxWait="10000" username="system" password="manager"
factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory" driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:xe"/> </Context>

2) WEB\INF\web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

id="WebApp_ID" version="3.0">

<resource-ref>

<res-ref-name>mypool</res-ref-name>

<res-type>javax.sql.DataSource</res-type>

<res-auth>Container</res-auth>

</resource-ref>

</web-app>

3) servlet class

Context initContext = new InitialContext();

DataSource ds = (DataSource)initContext.lookup("java:/comp/env/mypool");

con = ds.getConnection();

Servlets day-13 Listenners

ServletContextEvent : ServletContextListener this listener contains methods.

ContextInititalized : when we start the server

ContextDestoryed : when we stop the server

ex-1 :
package com.tcs;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import javax.servlet.ServletContext;

import javax.servlet.ServletContextEvent;

import javax.servlet.ServletContextListener;

public class MyListener implements ServletContextListener {

public void contextDestroyed(ServletContextEvent event) {

System.out.println("contextDestroyed method Connection closed");

ServletContext context = event.getServletContext();

Connection connection = (Connection) context.getAttribute("conn");

try { connection.close();

catch (SQLException e) {

e.printStackTrace(); }

public void contextInitialized(ServletContextEvent event) {

System.out.println("contextInitialized method Connection creation");

try {

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",


"system",

"ratan");

ServletContext context = event.getServletContext();

context.setAttribute("conn", connection);

} catch (Exception e) { // TODO Auto-generated catch block

e.printStackTrace();

}
<html>

<body>

<form method="get" action="./MyServlet">

enter table name to Get Data : <input type="text" name="tname"/>

<input type="submit" value="submit">

</form>

</body>

</html>

package com.tcs;

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public MyServlet() {

super();

// TODO Auto-generated constructor stub

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

response.setContentType("text/html");

PrintWriter writer = response.getWriter();

String tname = request.getParameter("tname");

ServletContext context = request.getServletContext();

Connection connection = (Connection) context.getAttribute("conn");

try {

Statement statement = connection.createStatement();

ResultSet set = statement.executeQuery("select * from "+tname);

while(set.next())

{ writer.println(set.getString(1)+"---"+set.getString(2)+"---"+set.getString(3));

writer.println("<br><br>");

} catch (SQLException e) {

e.printStackTrace();

1) HttpSession Session Tracking Mechanism.

2) Coockies Session Tracking Mechanism.

3) URL-Rewriting Session Tracking Mechanism.

//foram1.html

user name :
HttpSession

age :
uname
next Servlet1 req,res
uage

qual

form2.html
desig

qualification :

desgination :

next Servlet2 req,res

form3.html

email :

mobile : Servlet print all details

display 4-session

2-request

step 1 : read the data from request object

step 2 : create the session object

step 3 : place the requested data in session object.

step 4 : forward request to next form.

//form1.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<body bgcolor="pink">

<center>

<form method="post" action="./FirstServlet">

Name : <input type="text" name="uname"/><br><br>

Age : <input type="text" name="uage"/><br><br>

<input type="submit" value="Next"/>

</form>

</center>

</body>

</html>
//form2.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<body bgcolor="pink">

<center>

<form method="post" action="./SecondServlet">

Qualification : <input type="text" name="uqual"/><br><br>

Designation : <input type="text" name="udesig"/><br><br>

<input type="submit" value="Next"/>

</form>

</center>

</body>

</html>

//form3.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<body bgcolor="pink">

<center>

<form method="post" action="./DisplayServlet">

Email : <input type="text" name="email"/><br><br>

Mobile : <input type="text" name="mobile"/><br><br>

<input type="submit" value="Display"/>

</form>

</center>

</body>

</html>

//FirstServlet.java

package com.tcs;

import java.io.IOException;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

@WebServlet("/FirstServlet")

public class FirstServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public FirstServlet() {

// TODO Auto-generated constructor stub

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {

String uname = request.getParameter("uname");

String uage = request.getParameter("uage");

HttpSession session = request.getSession();

session.setAttribute("uname", uname);

session.setAttribute("uage", uage);

RequestDispatcher dispatcher = request.getRequestDispatcher("form2.html");

dispatcher.forward(request, response);

//SecondServlet.java

package com.tcs;

import java.io.IOException;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

@WebServlet("/SecondServlet")

public class SecondServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public SecondServlet() {

super();

// TODO Auto-generated constructor stub

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {

String uqual = request.getParameter("uqual");

String udesig = request.getParameter("udesig");

HttpSession session = request.getSession(false); //locate the object

session.setAttribute("uqual", uqual);

session.setAttribute("udesig", udesig);

RequestDispatcher dispatcher = request.getRequestDispatcher("form3.html");

dispatcher.forward(request, response);

//DisplayServlet.java

package com.tcs;

import java.io.IOException;

import java.io.PrintWriter;
import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

@WebServlet("/DisplayServlet")

public class DisplayServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public DisplayServlet() {

super();

// TODO Auto-generated constructor stub

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {

response.setContentType("text/html");

PrintWriter writer = response.getWriter();

HttpSession session = request.getSession(false);

writer.println("*******Complete details*******");

writer.println("<br>");

writer.println("user name: "+session.getAttribute("uname"));

writer.println("<br>");

writer.println("user age: "+session.getAttribute("uage"));

writer.println("<br>");

writer.println("user qualification: "+session.getAttribute("uqual"));

writer.println("<br>");

writer.println("user designation: "+session.getAttribute("udesig"));

writer.println("<br>");

writer.println("user mobile: "+request.getParameter("mobile"));

writer.println("<br>");

writer.println("user email: "+request.getParameter("email"));


writer.println("<br>");

session.invalidate();

You might also like