0% found this document useful (0 votes)
8 views30 pages

Lecture 3.3

The document provides a comprehensive guide on configuring a Java project using servlets, including Servlet Config and Servlet Mapping. It outlines the steps to create a dynamic web project in Eclipse, add necessary libraries, and deploy the project on a Tomcat server. Additionally, it explains the use of ServletConfig and ServletContext interfaces, along with examples of servlet chaining and initialization parameters.

Uploaded by

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

Lecture 3.3

The document provides a comprehensive guide on configuring a Java project using servlets, including Servlet Config and Servlet Mapping. It outlines the steps to create a dynamic web project in Eclipse, add necessary libraries, and deploy the project on a Tomcat server. Additionally, it explains the use of ServletConfig and ServletContext interfaces, along with examples of servlet chaining and initialization parameters.

Uploaded by

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

INSTITUTE : UIE

DEPARTMENT : CSE
Bachelor of Engineering (Computer Science
& Engineering)
PROJECT BASED LEARNING IN JAVA WITH LAB
(22CSH-359/22ITH-359)

TOPIC OF PRESENTATION:
Configuring project using servlet, Servlet
Config and Servlet Mapping (CO 5)
DISCOVER . LEARN .
EMPOWER
Lecture Objectives

In this lecture, we will


discuss:
•Configuring project using
servlet, Servlet Config and
Servlet Mapping

2
Creating Servlet Example in
Eclipse

3
Eclipse is an open-source ide for developing JavaSE and JavaEE (J2EE)
applications. You can download the eclipse ide from the eclipse website
http://www.eclipse.org/downloads/.

You need to download the eclipse ide for JavaEE developers.

Creating servlet example in eclipse ide, saves a lot of work to be done. It is easy
and simple to create a servlet example.

Let's see the steps, you need to follow to create the first servlet example.
•Create a Dynamic web project
•create a servlet
•add servlet-api.jar file
•Run the servlet
1) Create the dynamic web project:
For creating a dynamic web project click on File Menu -> New -> Project..-> Web ->
dynamic web project -> write your project name e.g. first -> Finish.

2) Create the servlet in eclipse IDE:


For creating a servlet, explore the project by clicking the + icon -> explore the Java
Resources -> right click on src -> New -> servlet -> write your servlet name e.g.
Hello -> uncheck all the checkboxes except doGet() -> next -> Finish.

3) add jar file in eclipse IDE:


For adding a jar file, right click on your project -> Build Path -> Configure Build Path
-> click on Libraries tab in Java Build Path -> click on Add External JARs button ->
select the servlet-api.jar file under tomcat/lib -> ok.

4) Start the server and deploy the project:


For starting the server and deploying the project in one step, Right click on your
project -> Run As -> Run on Server -> choose tomcat server -> next -> addAll ->
finish.
How to configure tomcat server in Eclipse ? (One time Requirement)
If you are using Eclipse IDE first time, you need to configure the tomcat server First.
For configuring the tomcat server in eclipse IDE, click on servers tab at the bottom
side of the IDE -> right click on blank area -> New -> Servers -> choose tomcat then
its version -> next -> click on Browse button -> select the apache tomcat root
folder previous to bin -> next -> addAll -> Finish.

For more details refer to the Link:

https://www.javatpoint.com/creating-servlet-in-eclipse-ide
ServletConfig and ServletContext

7
ServletConfig interface

• Provided to a servlet upon initialization by the web container

• Simple read only interface to configuration details


– String getInitParameter(String name)
– Enumeration getInitParameterNames()
– String getServletName ()

• Can also access ServletContext

8
Demo for using ServletConfig

• Consider an html form “first.html” which accepts the user name

• A servlet “Second.java” takes in this parameter and displays it on the


web page

Where did this


value come from?

9
Demo for using ServletConfig (Contd.).

• Let us take a look at Second.java servlet code

import java.io.*;
import javax.servlet.*;
import
javax.servlet.http.*;
public class Second
extends HttpServlet {

String homeName;
ServletConfig config;

public void init() {


//get the initialization
parameters
//Returns this servlet's ServletConfig object
config = getServletConfig();

/*Returns a String containing the value of the named initialization


parameter, 10
or null if the parameter does not exist. */
Demo for using ServletConfig (Contd.).

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();

String urname = req.getParameter("name");

out.println("<h2>" + homeName + "</h2>");


out.println("<hr>");
out.println("Hello! " + urname);
}
}

11
Demo for using ServletConfig (Contd.).

Web.xml

<web-app>
<servlet>
<servlet-name>Second</servlet-name>
<servlet-class>Second</servlet-class>
<init-param>
<param-name>homeName</param-name>
<param-value>Welcome to www.simple.com</param-value>
</init-param>

</servlet> The init parameter values ar e


<servlet-mapping> configured in the web.xml
<servlet-name>Second</servlet-name> deployment descriptor file
<url-pattern>/Second</url-pattern>
</servlet-mapping>
</web-app>

12
Database Example for using ServletConfig
• The init() method can also be used to perform set up operation such as
setting up a database connection

public class DBConfigParamServlet extends HttpServlet {


Connection con;
PreparedStatement st;
Statement stmt;
ResultSet rs;
ServletConfig config;
public void init() {
config = getServletConfig(); //Returns this servlet's ServletConfig object
String driver = config.getInitParameter("driverName");
String url = config.getInitParameter("urlName");
try {
Class.forName(driver);
con = DriverManager.getConnection(url, "scott", "tiger");
System.out.println("Connected by using init parameters..");
} catch (Exception e) { System.out.println("Error
in connection.."); }
}
……doGet()…{} }
13
Database Example for using … (Contd.).

<web-app>
<servlet>
<servle
t-
name>
DBCon
figPara
mServl
et</
servlet-
name>
<servle
t-
class>
DBCon
figPara
mServl
et</
servlet- 14
class>
Discussion

• What is the advantage of setting up a database


connection by reading init parameter values?

15
ServletContext interface

• Allows a servlet to communicate with the servlet container

• Access container-managed resources, dispatch requests, write to


logs

• Defines a set of methods that a servlet uses to communicate with its


servlet container
– For example, to get the MIME type of a file, dispatch requests, or
write to a log file

• There is one context per "web application" per Java Virtual Machine

• ServletContext object is contained within ServletConfig object, which


the servlet container provides the servlet when the servlet is
initialized

16
Servlet Context Methods

• Resources such as index.html can be accessed through web server


or by servlet
– Servlet uses request.getContextPath() to identify its context
path, for example: /app
– Servlet uses getResource() and
getResourceAsStream(request.getContextPath() + “/index.html”)

• To retrieve context-wide initialization parameters, servlet uses


getInitParameter() and getInitParameterNames()

• To access a range of information about the local environment, shared


with other servlets in same servlet context, servlet uses getAttribute(),
setAttribute(), removeAttribute(), getAttributeNames()

17
Demo for using ServletContext
• Use of ServletContext for web application initialization: Suppose
there is a need to include a contact email of webmaster or an admin
on few web pages of a website

• In the web.xml:
<servlet>
<servlet-name>ContextParamServlet</servlet-name>
<servlet-class>ContextParamServlet</servlet-class>
</servlet>
<context-param>
<param-name>Email</param-name>
<param-value>[email protected]</param-value>
</context-param>

• In the servlet code:

ServletContext context = getServletContext();


out.println(context.getInitParameter("Email"));

18
Checkpoint

• In which tag is the <context-param> tag defined


in web.xml file?

19
Demo for using ServletContext
• Use of ServletContext for web application initialization: Suppose
there is a need to include a contact email of webmaster or an admin
on few web pages of a website

• In the web.xml:
<servlet>
<servlet-name>ContextParamServlet</servlet-name>
<servlet-class>ContextParamServlet</servlet-class>
</servlet>
<context-param>
<param-name>Email</param-name>
<param-value>[email protected]</param-value>
</context-param>

• In the servlet code:

ServletContext context = getServletContext();


out.println(context.getInitParameter("Email"));

20
Servlet Chaining

21
Servlet Chaining: RequestDispatcher Interface

Used in order to FORWARD or INCLUDE a request from one servlet to


another
Servlet/JSP the RequestDispatcher interface provides two methods.

1. RequestDispatcher.forward(request,response)
2. RequestDispatcher.include(request,response)

Both these methods take ServletRequest and ServletResponse object


as an argument

22
Servlet Chaining: forward (request,response)

ServletContext ctx=getServletContext();
RequestDispatcher
dis=ctx.getRequestDispatcher(“/servlet/AnotherServl
et”);
dis.forward(request,response);

23
Servlet Chaining: forward (request, response)

Client Request Request passing

Client Servlet1 Servlet2

Response Generation

24
Servlet Chaining: include (request, response)

ServletContext ctx=getServletContext();
RequestDispatcher
dis=ctx.getRequestDispatcher(“/servlet/AnotherServl
et”);
dis.include(request,response);

25
Servlet Chaining: include (request, response)

Client Request Request Passing

Client Servlet1 Servlet2

Response Generation Output back to the


Requester

26
Demo for Servlet Chaining

• This example demonstrates chaining in servlets where output


of the
• first servlet act as a input to the second servlet.
– first.html – a form containing a text field and a submit button
– FirstServlet.java - accepts user name and
forwards it to

• SecondServlet
– SecondServlet.java - Extracts the username value which is set in FirstServlet

27
Summary:

In this session, you were able to :


• Configuring project using servlet, Servlet
Config and Servlet Mapping
References:
Books:
1. Balaguruswamy, Java.
2. A Primer, E.Balaguruswamy, Programming with Java, Tata McGraw Hill
Companies
3. John P. Flynt Thomson, Java Programming.

Video Lectures :
https://youtu.be/ewiOaDitBBw
Reference Links:
1. http://docs.oracle.com/cd/B31017_01/web.1013/b28959/sess ions.htm
2. http://www.tutorialspoint.com/jsp/jsp_cookies_handling.htm
3. http://www.javatpoint.com/sonoojaiswal/servletconfig
4. https://www.javatpoint.com/creating-servlet-in-eclipse-ide
THANK YOU

You might also like