Nearby lessons

29 of 34

Servlet - Examples: Directory Structure & web.xml

📌 What You Will Learn
  • See complete runnable servlet programs
  • Understand the output of each program
  • Copy and deploy programs in Tomcat

Web application directory structure, web.xml configuration, init parameters, welcome files, and error pages.

UNIT-2: Directory Structure and Deployment of Web Application

Objective:

Construct File and Directory Structure of web application that may contain

  • Static Content
  • JSP Pages
  • Servlet classes
  • Deployment Descriptor
  • Tag Libraries
  • Jar Files
  • Java Class Files

advapps2A

Name of Application *.htmlStaticPublicly

OR *.jpg Context Accessable

*.css Resources

Context Root

:::

:::

*.jsp

WEB-INF

web.xml

classes

*.class

lib

*.jar

tags

*.tld

*.tag

Servlet Specification defines a standard structure for web applications so that every web server

can provide support for that structure irrespective of vendor.

Total static information we have to place within the context root directly. All resources present in

context root are publicly accessable resources. ie any person can access these resouces directly by

its name.Hence we cannot place secured resouces within the context root directly.

http://localhost:7777/advapps1C/login.html

For every web application we have to maintain WEB-INF Folder. All the secured resources we have

to place in this folder and these are not publicly accessable resources. If any person trying to

access these resouces directly by its name then we will get 404 status code.

http://localhost:7777/advapps1B/WEB-INF/web.xml ==>404

For every web application, we have to maintain one special xml file named with web.xml. It is also

known as Deployment Descriptor. Web container will use this web.xml to get our servlets

information.Hence this web.xml acts as GUIDE to web container.

We have to place this web.xml in WEB-INF folder directly.

Within the WEB-INF, we have to create classes folder to place all .class files.(Both Servlet classes

and normal java classes)

Within the WEB-INF, we have to maintain lib folder to place all required .jar files(like

ojdbc6.jar,log4j.jar etc)

Note:

if we place our class files in classes folder and lib folder, we are not required to set classpath

explicitly, b'z web container always searches in these locations by default.

Note:

For the required .class file web container will search first in classes folder and if it is not available

then only it will search in lib folder.i.e classes present in classes folder will get more priority than

classes present in lib folder.

All Tag libraries we have to place inside WEB-INF either directly or indirectly.

ResourseLocation
1) Static Context1) Within the Context Root directly
2) JSP Pages2) Within the Context Root directly. If JSP is

secured then we have to place inside WEB-INF

Example01
JCode Cell
1 
2 Directory Structure of web application
3 web.xml
4 war file
5 Directory Structure of web application:
6

UNIT-2: Directory Structure and Deployment of Web Application

Q. In how many places we can place our servlet in web application?

There are 3 places

Example02
JCode Cell
1 
2 Servlet Classes 3) Inside Classes Folder
3 Deployment Descriptor (web.xml) 4) Inside WEB-INF directly
4 Tag Libraries 5) Within WEB-INF either directly OR indirectly
5 JAR Files 6) Inside lib Folder
6 Java Class Files 7) Inside Classes Folder
7

UNIT-2: Directory Structure and Deployment of Web Application

Deployment Descriptor: (web.xml)

Objective:

Describe the purpose and syntax of the following deployment descriptor elements?

1.<error-page>

2.<init-param>

3.<mime-mapping>

4.<servlet>

5.<servlet-mapping>

6.<servlet-class>

7.<servlet-name>

8.<welcome-file>

Deployment Descriptor(DD) is an XML File named with web.xml,should be placed in WEB-INF

directly.

Web container uses this web.xml to get web application deployment information. i.e web.xml acts

as GUIDE to web container.

web.xml provides declarative mechanism for customizing our web application without touching

the source code(with the help of initialization parameters).

For every web application we have to maintain exactly one web.xml and should be placed in WEB-

INF folder directly.

Anatomy of web.xml:

Example03
JCode Cell
1 
2 Inside classes folder(.class)
3 Inside lib folder(.jar )
4 Anywhere we can place but we have to set classpath explicitly.
5

UNIT-2: Directory Structure and Deployment of Web Application

until servlet 2.3 version,web.xml is validated by using DTDs where order is important.Hence until

Servlet 2.3V the order of these top level tags is important.

But from Servlet 2.4V onwards web.xml is validated by using Schemas where order is not

important.Hence from servlet 2.4 Version onwards we can take these top level tags in any order.

Among these 27 top level tags , no tag is mandatory.Hence the following are valid web.xml files

<web-app>OR <web-app/>

</web-app>

1.<servlet>:

We can use <servlet> tag to declare servlets in web.xml.

<servlet> tag contains the following 9 child tags...

Example04
JCode Cell
1 
2 <web-app> Around 27
3 <description> Top Level
4 <display-name> Tags
5 <servlet>
6 <servlet-mapping>
7 <welcome-file-list>
8 <error-page>
9 <mime-mapping>
10 <context-param>
11 <security-constraint>
12 <jsp-config>
13 <session-config>
14 <filter>
15 <filter-mapping>
16 <listener>
17 ...
18 </web-app>
19

UNIT-2: Directory Structure and Deployment of Web Application

The order of these 9 tags is important and we should not change.

Among these 9 tags the following 2 tags are mandatory.

<servlet-name>

<servlet-class> or <jsp-file>

<servlet-name>:

According to Servlet specification there are 3 names are possible for every servlet.

Example05
JCode Cell
1 
2 <servlet> 9 Child Tags
3 <description>
4 <display-name>
5 <icon>
6 <servlet-name>
7 <servlet-class> or <jsp-file>
8 <init-param>
9 <load-on-startup>
10 <run-as>
11 <security-role-ref>
12 </servlet>
13

UNIT-2: Directory Structure and Deployment of Web Application

  • Original Name OR Developer's Name specified by <servlet-class>
  • Deployer's Name OR Logical Name specified by <servlet-name> tag
  • End User's Name speficied by <url-pattern>

The main advantages of Logical Name are:

  • We can achieve security because we are not highlighting our internal naming conventions to the

end user.

2.Without effecting end user we can change our internal naming conventions.

3.We can map same servlet with different url-patterns

Note:

Within web.xml Logical Name is always unique.

Within the servlet we can get Logical Name by using getServletName() method of ServletConfig

interface.

Example06
JCode Cell
1 
2 <web-app> Deployer's Name OR Logical
3 <servlet> Name
4 <servlet-name>DemoServlet</servlet-name>
5 <servlet-class>FirstServlet</servlet-class>
6 </servlet> Original Name OR Developer's Name
7
8 <servlet-mapping>
9 <servlet-name>DemoServlet</servlet-name>
10 <url-pattern>/test</url-pattern> End User's Name
11 </servlet-mapping>
12 </web-app>
13

UNIT-2: Directory Structure and Deployment of Web Application

Note:

All methods of ServletConfig interface are by default available in our servlet.Hence within our

servlet we can call these methods directly.

<servlet-class>:

By using this tag,we can specify the original name of servlet(Developer's name)

Web container will create object for this class only.Hence compulsary it should be concrete class

but not abstract class or interface.

Example07
JCode Cell
1 
2 public class FirstSevlet extends HttpServlet
3 {
4 public void doGet(..)...
5 {
6 PrintWriter out = resp.getWriter();
7 String name=getServletName();
8
9 out.println("<h1>Logical Name:"+name+"</h1>");
10 }
11 }
12

Demo Program

|--WEB-INF

|--date.jsp

|--web.xml

http://localhost:7777/advapps2B/test==>valid

http://localhost:7777/advapps2B/WEB-INF/date.jsp==>404

Servlet Initialization Parameters(<init-param>):

If the value of the variable will change frequently then those values are not recommended to

hard-code within the servlet class.

The problem in this approach is, If there is any change in the value, to reflect that change,we have

to recompile,rebuild and redeploy application, and sometimes even server restart also

required,which creates big business impact to the client.

Such type of variables we have to configure in web.xml by using <init-param> tag.

The advantage in this approach is if there is any change in the value, to reflect that change just

redeployment is enough,which won't create big business impact to the client.

We can declare servlet initialization parameters in web.xml as follows...

Example08
JCode Cell
1 
2 <h1>Now Server Time is :
3 <%=new java.util.Date()%>
4 </h1>web.xml:
5 <web-app>
6 <servlet>
7 <servlet-name>FirstJSP</servlet-name>
8 <jsp-file>/WEB-INF/date.jsp</jsp-file>
9 <init-param>
10 </init-param>
11 </servlet>
12 <servlet-mapping>
13 <servlet-name>FirstJSP</servlet-name>
14 <url-pattern>/test</url-pattern>
15 </servlet-mapping>
16 </web-app>advapps2B
17

Demo Program

We can declare any number of init parameters but for each parameter one <init-param> tag.

Within the servlet we can access servlet initialization parameters by using ServletConfig object.

ServletConfig interface defines the following methods to access these parameters inside servlet.

Example09
JCode Cell
1 
2 <web-app>
3
4 <servlet>
5 <servlet-name>FirstServlet</servlet-name>
6 <servlet-class>FirstServlet</servlet-class>
7 <init-param>
8 <param-name>user</param-name>
9 <param-value>scott</param-value>
10 </init-param>
11 <init-param>
12 <param-name>pwd</param-name>
13 <param-value>tiger</param-value>
14 </init-param>
15 </servlet>
16
17 </web-app>
18

Demo Program

Returns the value associated with specified parameter.

Returns null if the specified paramter is not avaialble.

Example10
JCode Cell
1 
2 public String getInitParameter(String pname)
3

Demo Program

Returns all initialization parameter names.

If the specified servlet does not contain any initialization parameters then this method returns

empty enumeration object but not null.

GenericServlet implements ServletConfig interface and hence GenericServlet provides

implementation for the above 2 methods.Within our servlet we can call these methods directly.

Example11
JCode Cell
1 
2 public Enumeration getInitParameterNames()
3

Demo Program to print all Servlet Initialization Parameters

Example12
JCode Cell
1 
2 <web-app>
3 <servlet>
4 <servlet-name>DemoServlet</servlet-name>
5 <servlet-class>InitializeParameterDemoServlet</servlet-class>
6 <init-param>
7 <param-name>PhoneNumber</param-name>
8 <param-value>9848012345</param-value>
9 </init-param>
10 <init-param>
11 <param-name>MailId</param-name>
12 <param-value>durgaocjp@gmail.com</param-value>
13 </init-param>
14 <init-param>
15 <param-name>UserName</param-name>
16 <param-value>scott123</param-value>
17 </init-param>
18 </servlet>
19 <servlet-mapping>
20 <servlet-name>DemoServlet</servlet-name>
21 <url-pattern>/test</url-pattern>
22 </servlet-mapping>
23 </web-app>
24

InitializeParameterDemoServlet.java

eption,IOException

Example13
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import java.util.*;
6 public class InitializeParameterDemoServlet extends HttpServlet
7 {
8 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletExc
9

InitializeParameterDemoServlet.java

h> </tr>");

Example14
JCode Cell
1 
2 {
3 PrintWriter out = resp.getWriter();
4 out.println("<center><h1>Intialization Parameters</h1></center><hr>");
5 Enumeration e = getInitParameterNames();
6 out.println("<table border=2><tr><th>Parameter Name</th><th>Parameter Value</t
7

InitializeParameterDemoServlet.java

Example15
JCode Cell
1 
2 while (e.hasMoreElements())
3 {
4 String pname = (String)e.nextElement();
5 String pvalue = getInitParameter(pname);
6

InitializeParameterDemoServlet.java

advapps2C

|-WEB-INF

|-web.xml

|-classes

|-InitializeParameterDemoServlet.class

Demo Program to print total number of employees from the database by Servlet

Example16
JCode Cell
1 
2 out.println("<tr><td>"+pname+"</td><td>"+pvalue+"</td></tr>");
3 }
4 out.println("</table>");
5 out.println("</body></html>");
6 }
7 }
8

Initialization Parameters

Example17
JCode Cell
1 
2 <web-app>
3 <servlet>
4 <servlet-name>FirstServlet</servlet-name>
5 <servlet-class>FirstServlet</servlet-class>
6 <init-param>
7 <param-name>user</param-name>
8 <param-value>scott</param-value>
9 </init-param>
10 <init-param>
11 <param-name>pwd</param-name>
12 <param-value>tiger</param-value>
13 </init-param>
14 </servlet>
15 <servlet-mapping>
16 <servlet-name>FirstServlet</servlet-name>
17 <url-pattern>/test</url-pattern>
18 </servlet-mapping>
19 </web-app>
20

FirstServlet.java

eption,IOException

Example18
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import java.sql.*;
6 public class FirstServlet extends HttpServlet
7 {
8 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletExc
9

FirstServlet.java

",user,pwd);

Example19
JCode Cell
1 
2 {
3 String user=getInitParameter("user");
4 String pwd=getInitParameter("pwd");
5 PrintWriter out = resp.getWriter();
6 try{
7 Class.forName("oracle.jdbc.OracleDriver");
8 Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE
9

FirstServlet.java

advapps2CB

|-WEB-INF

|-web.xml

|-lib

|-ojdbc6.jar

|-classes

|-FirstServlet.class

Note:

Servlet initialization parameters are key-value pairs where both key and value are String type.

From the servlet we can access these parameters but we cannot modify. i.e we have only getter

methods but not setter methods. Hence Servlet initialization parameters are considered as

deployment time constants.

Example20
JCode Cell
1 
2 Statement st =con.createStatement();
3 ResultSet rs =st.executeQuery("select count(*) from employees");
4 while(rs.next())
5 {
6 int count=rs.getInt(1);
7 out.println("<h1>The number of employees:"+count+"</h1>");
8 }
9 }
10 catch(Exception e)
11 {
12 e.printStackTrace();
13 }
14 }
15 }
16

ServletConfig (I)

<load-on-startup>:

usually servlet class loading,instanitation and execution of init() method will takes place at the

time of first request. It increases processing time of first request when compared with remaining

requests.

To overcome this problem, we should go for <load-on-startup>

If we configured <load-on-startup> then these steps will be performed at the time of server start

up or at application deployment.

Example21
JCode Cell
1 
2 public String getServletName()
3 public String getInitParameter()
4 public Enumeration getInitParamterNames()
5 public ServletContext getServletContext()
6

ServletConfig (I)

The main advantage of <load-on-startup> is all requests will be processed with uniform response

time.

The main disadvantage of <load-on-startup> is, creating servlet object at the beginning may effect

performance and causes memory problems.

The servlet whose <load-on-startup> value is less, that servlet will be loaded first.

If 2 servlets having same <load-on-startup> value or if the <load-on-startup> value is negative then

we cannot expect order of loading. It is web server vendor dependent.

Demo Program to demonstrate <load-on-startup>:

Example22
JCode Cell
1 
2 <web-app>
3 <servlet>
4 ....
5 <load-on-startup>10</load-on-startup>
6 </servlet>
7 ..
8 </web-app>
9

FirstServlet.java

IOException

Example23
JCode Cell
1 
2 import javax.servlet.*;
3 import java.io.*;
4 public class FirstSevlet extends GenericServlet
5 {
6 static
7 {
8 System.out.println("FirstServlet Loading..");
9 }
10 public FirstSevlet()
11 {
12 System.out.println("FirstServlet Instantiation..");
13 }
14 public void init(ServletConfig config) throws ServletException
15 {
16 System.out.println("FirstServlet init method execution..");
17 }
18 public void service(ServletRequest req, ServletResponse resp) throws ServletException,
19
Output

    FirstServlet Loading..
    FirstServlet Instantiation..
    FirstServlet init method execution..
          

FirstServlet.java

Example24
JCode Cell
1 
2 {
3 PrintWriter out = resp.getWriter();
4 out.println("<h1>FirstServlet:Writing servlet by extending GS is very easy</h1>");
5 System.out.println("service method called..");
6 }
7 }
8
Output

    <h1>FirstServlet:Writing servlet by extending GS is very easy</h1>
    service method called..
          

SecondServlet.java

IOException

Example25
JCode Cell
1 
2 import javax.servlet.*;
3 import java.io.*;
4 public class SecondServlet extends GenericServlet
5 {
6 static
7 {
8 System.out.println("SecondServlet Loading..");
9 }
10 public SecondServlet()
11 {
12 System.out.println("SecondServlet Instantiation..");
13 }
14 public void init(ServletConfig config) throws ServletException
15 {
16 System.out.println("SecondServlet init method execution..");
17 }
18 public void service(ServletRequest req, ServletResponse resp) throws ServletException,
19
Output

    SecondServlet Loading..
    SecondServlet Instantiation..
    SecondServlet init method execution..
          

SecondServlet.java

web.xml:

Example26
JCode Cell
1 
2 {
3 PrintWriter out = resp.getWriter();
4 out.println("<h1>SecondServlet:Writing servlet by extending GS is very easy</h1>");
5 System.out.println("service method called..");
6 }
7 }
8
Output

    <h1>SecondServlet:Writing servlet by extending GS is very easy</h1>
    service method called..
          

SecondServlet.java

advapps2D

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-SecondServlet.class

<servlet-mapping>:

By using this tag, we can map a servlet with <url-pattern>.

Up to Servlet 2.4 version within <servlet-mapping>, a single servlet can map to exactly one <url-

pattern>

But from Servlet 2.5V onwards we can map servlet with multiple url patterns. i.e we can take

mulitple <url-pattern> tags inside <servlet-mapping>.

Example27
JCode Cell
1 
2 <web-app>
3 <servlet>
4 <servlet-name>FirstSevlet</servlet-name>
5 <servlet-class>FirstSevlet</servlet-class>
6 <load-on-startup>20</load-on-startup>
7 </servlet>
8 <servlet>
9 <servlet-name>SecondServlet</servlet-name>
10 <servlet-class>SecondServlet</servlet-class>
11 <load-on-startup>10</load-on-startup>
12 </servlet>
13 <servlet-mapping>
14 <servlet-name>FirstSevlet</servlet-name>
15 <url-pattern>/test</url-pattern>
16 </servlet-mapping>
17 </web-app>
18

SecondServlet.java

It is invalid in Servlet 2.4V but valid in Servlet 2.5V.

According to Servlet specification there are 4 types of url-patterns are possible.

  • Exact match url-pattern

eg: /test

  • Longest Path Prefix url-pattern or directory match url-pattern

eg: /test/test/*

  • url-pattern by extension

eg: *.do

  • Default url-pattern

eg: /

Q.Which of the following are valid url-patterns ?

Example28
JCode Cell
1 
2 <servlet-mapping>
3 <servlet-name>DemoServlet</servlet-name>
4 <url-pattern>/test</url-pattern>
5 <url-pattern>/hello</url-pattern>
6 <url-pattern>/demo</url-pattern>
7 </servlet-mapping>
8

SecondServlet.java

*Web container always gives the precedence in the following order

  • Exact Match UP
  • Longest Path Prefix UP
  • UP by extension
  • Default UP

Demo Program to demonistrate different types of url-patterns and priority order:

Example29
JCode Cell
1 
2 /test
3 /test/*/test
4 /test/test/*
5 *.task
6 /
7 /test/test/*.do
8

FirstServlet.java

eption,IOException

Example30
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 public class FirstServlet extends HttpServlet
6 {
7 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletExc
8

FirstServlet.java

Example31
JCode Cell
1 
2 {
3 PrintWriter out = resp.getWriter();
4 out.println("<h1>Hi ...This is First Servlet</h1>");
5 }
6 }
7
Output

    <h1>Hi ...This is First Servlet</h1>
          

SecondServlet.java

eption,IOException

Example32
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 public class SecondServlet extends HttpServlet
6 {
7 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletExc
8

SecondServlet.java

Example33
JCode Cell
1 
2 {
3 PrintWriter out = resp.getWriter();
4 out.println("<h1>Hi ...This is Second Servlet</h1>");
5 }
6 }
7
Output

    <h1>Hi ...This is Second Servlet</h1>
          

ThirdServlet.java

eption, IOException

Example34
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 public class ThirdServlet extends HttpServlet
6 {
7 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletExc
8

ThirdServlet.java

Example35
JCode Cell
1 
2 {
3 PrintWriter out = resp.getWriter();
4 out.println("<h1>Hi ...This is Third Servlet</h1>");
5 }
6 }
7
Output

    <h1>Hi ...This is Third Servlet</h1>
          

DefaultServlet.java

eption,IOException

Example36
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 public class DefaultServlet extends HttpServlet
6 {
7 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletExc
8

DefaultServlet.java

web.xml:

Example37
JCode Cell
1 
2 {
3 PrintWriter out = resp.getWriter();
4 out.println("<h1>Hi ...This is Default Servlet</h1>");
5 }
6 }
7
Output

    <h1>Hi ...This is Default Servlet</h1>
          

DefaultServlet.java

advapps2E

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-SecondServlet.class

|-ThirdServlet.class

|-DefaultServlet.class

FS==>/test

SS==>/test/test/*

TS==>*.do

DS===>/

http://localhost:7777/advapps2E/test ==>FS

http://localhost:7777/advapps2E/test/test/durga ==>SS

http://localhost:7777/advapps2E/test/test/durga.do ==>SS

http://localhost:7777/advapps2E/test/durga.do ==>TS

http://localhost:7777/advapps2E/test/anushka ==>DS

Q. How to configure Default Servlet in web.xml and when it will get chance?

We can configure Default Servlet with url-pattern "/".

If no other servlet matched then only default servlet will get chance.

Example38
JCode Cell
1 
2 <web-app>
3 <servlet>
4 <servlet-name>FirstServlet</servlet-name>
5 <servlet-class>FirstServlet</servlet-class>
6 </servlet>
7 <servlet>
8 <servlet-name>SecondServlet</servlet-name>
9 <servlet-class>SecondServlet</servlet-class>
10 </servlet>
11 <servlet>
12 <servlet-name>ThirdServlet</servlet-name>
13 <servlet-class>ThirdServlet</servlet-class>
14 </servlet>
15 <servlet>
16 <servlet-name>DefaultServlet</servlet-name>
17 <servlet-class>DefaultServlet</servlet-class>
18 </servlet>
19 <servlet-mapping>
20 <servlet-name>FirstServlet</servlet-name>
21 <url-pattern>/test</url-pattern>
22 </servlet-mapping>
23 <servlet-mapping>
24 <servlet-name>SecondServlet</servlet-name>
25 <url-pattern>/test/test/*</url-pattern>
26 </servlet-mapping>
27 <servlet-mapping>
28 <servlet-name>ThirdServlet</servlet-name>
29 <url-pattern>*.do</url-pattern>
30 </servlet-mapping>
31 <servlet-mapping>
32 <servlet-name>DefaultServlet</servlet-name>
33 <url-pattern>/</url-pattern>
34 </servlet-mapping>
35 </web-app>
36

Getting Extra Information from the url

Example39
JCode Cell
1 
2 getRequestURI()
3 getContextPath()
4 getServletPath()
5 getPathInfo()
6 getQueryString()
7

FirstServlet.java

eption,IOException

Example40
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 public class FirstServlet extends HttpServlet
6 {
7 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletExc
8

FirstServlet.java

web.xml

Example41
JCode Cell
1 
2 {
3 PrintWriter out = resp.getWriter();
4 out.println("<h1>Request URI:" +req.getRequestURI()+"</h1>");
5 out.println("<h1>Context Path:" +req.getContextPath()+"</h1>");
6 out.println("<h1>Servlet Path:" +req.getServletPath()+"</h1>");
7 out.println("<h1>Path Info:" +req.getPathInfo()+"</h1>");
8 out.println("<h1>Query String:" +req.getQueryString()+"</h1>");
9 }
10 }
11

FirstServlet.java

advapps2F

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

FS==>/test/test/*

Eg1:

http://localhost:7777/advapps2F/test/test/durga/software?user=durga&pwd=anushka

Request URI:/advapps2F/test/test/durga/software

Context Path:/advapps2F

Servlet Path:/test/test

Path Info:/durga/software

Query String:user=durga&pwd=anushka

http://localhost:7777/advapps2F/test/test/durga/software

Request URI:/advapps2F/test/test/durga/software

Context Path:/advapps2F

Servlet Path:/test/test

Path Info:/durga/software

Query String:null

http://localhost:7777/advapps2F/test/test

Request URI:/advapps2F/test/test/durga/software

Context Path:/advapps2F

Servlet Path:/test/test

Path Info: null

Query String:null

Configuring welcome files for web application:

It is highly recommended to configure welcome files for our web application. It increases easyness

to use our web application for the end user.

We can configure welcome files in the web.xml as follows...

Example42
JCode Cell
1 
2 <web-app>
3 <servlet>
4 <servlet-name>FirstServlet</servlet-name>
5 <servlet-class>FirstServlet</servlet-class>
6 </servlet>
7 <servlet-mapping>
8 <servlet-name>FirstServlet</servlet-name>
9 <url-pattern>/test/test/*</url-pattern>
10 </servlet-mapping>
11 </web-app>
12

FirstServlet.java

<welcome-file-list> is the direct child tag of <web-app> and hence we can take anywhere.

We can configure any number of welcome files but the order is important. Web container always

consider from top to bottom.

In any web application index.html acts as default welcome file.If index.html is not available then

index.jsp acts as default welcome file.

If we configured welcome files explicitly then default welcome files concept is not applicable.

welcome files concept is applicable for sub folders also.

Example43
JCode Cell
1 
2 <web-app>
3 <welcome-file-list>
4 <welcome-file>home.jsp</welcome-file>
5 <welcome-file>login.jsp</welcome-file>
6 <welcome-file>index.jsp</welcome-file>
7 </welcome-file-list>
8 </web-app>
9

Demo Program to demonistrate default welcome files

Example44
JCode Cell
1 
2 <h1>Welcome to Durgajobs information<br/><hr/>
3 <a href="/advapps2GW/test1">Hyderabad Jobs Info</a><br/>
4 <a href="/advapps2GW/test2">Bangalore Jobs Info</a><br/>
5 <a href="/advapps2GW/test3">Pune Jobs Info</a></h1>
6

HydJobsServlet.java

eption,IOException

Example45
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 public class HydJobsServlet extends HttpServlet
6 {
7 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletExc
8

HydJobsServlet.java

Example46
JCode Cell
1 
2 {
3 PrintWriter out = resp.getWriter();
4 out.println("<h1>Hyderabad Jobs Info</h1>");
5 }
6 }
7
Output

    <h1>Hyderabad Jobs Info</h1>
          

BangaloreJobsServlet.java

eption,IOException

Example47
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 public class BangaloreJobsServlet extends HttpServlet
6 {
7 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletExc
8

BangaloreJobsServlet.java

Example48
JCode Cell
1 
2 {
3 PrintWriter out = resp.getWriter();
4 out.println("<h1>Bangalore Jobs Info</h1>");
5 }
6 }
7
Output

    <h1>Bangalore Jobs Info</h1>
          

PuneJobsServlet.java

eption,IOException

Example49
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 public class PuneJobsServlet extends HttpServlet
6 {
7 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletExc
8

PuneJobsServlet.java

web.xml:

Example50
JCode Cell
1 
2 {
3 PrintWriter out = resp.getWriter();
4 out.println("<h1>Pune Jobs Info</h1>");
5 }
6 }
7
Output

    <h1>Pune Jobs Info</h1>
          

PuneJobsServlet.java

advapps2GW

|-WEB-INF

|-web.xml

|-classes

|-HydJobsServlet.class

|-BangaloreJobsServlet.class

|-PuneJobsServlet.class

http://localhost:7777/advapps2GW

Example51
JCode Cell
1 
2 <web-app>
3 <servlet>
4 <servlet-name>FirstServlet</servlet-name>
5 <servlet-class>HydJobsServlet</servlet-class>
6 </servlet>
7 <servlet>
8 <servlet-name>SecondServlet</servlet-name>
9 <servlet-class>BangaloreJobsServlet</servlet-class>
10 </servlet>
11 <servlet>
12 <servlet-name>ThirdServlet</servlet-name>
13 <servlet-class>PuneJobsServlet</servlet-class>
14 </servlet>
15 <servlet-mapping>
16 <servlet-name>FirstServlet</servlet-name>
17 <url-pattern>/test1</url-pattern>
18 </servlet-mapping>
19 <servlet-mapping>
20 <servlet-name>SecondServlet</servlet-name>
21 <url-pattern>/test2</url-pattern>
22 </servlet-mapping>
23 <servlet-mapping>
24 <servlet-name>ThirdServlet</servlet-name>
25 <url-pattern>/test3</url-pattern>
26 </servlet-mapping>
27 </web-app>
28

Demo Program to demonistrate customized welcome files

http://localhost:7777/advapps2G ==>home.jsp

http://localhost:7777/advapps2G/durga==>login.jsp

http://localhost:7777/advapps2G/durga/durga1==>home.jsp

http://localhost:7777/advapps2G/durga2==>index.jsp

http://localhost:7777/advapps2G/durga3==>404 Status code

Note:

According to Servlet Specification the value of <welcome-file> tag should be name of the jsp but

not location. Hence it should not starts with "/"

Eg:

<welcome-file>home.jsp</welcome-file>==>valid

<welcome-file>/home.jsp</welcome-file>===>invalid

Example52
JCode Cell
1 
2 <web-app>
3 <welcome-file-list>
4 <welcome-file>home.jsp</welcome-file>
5 <welcome-file>login.jsp</welcome-file>
6 <welcome-file>index.jsp</welcome-file>
7 </welcome-file-list>
8 </web-app>
9

Configuring Error Pages in web.xml

Configuring error page based on error code:

Example53
JCode Cell
1 
2 <web-app>
3 <error-page>
4 <exception-type>java.lang.ArithmeticException</exception-type>
5 <location>/error.jsp</location>
6 </error-page>
7 </web-app>
8

Configuring Error Pages in web.xml

Note:

Example54
JCode Cell
1 
2 <web-app>
3 <error-page>
4 <error-code>404</error-code>
5 <location>/test1</location>
6 </error-page>
7 </web-app>
8

Configuring Error Pages in web.xml

<web-app>.

  • error page can be either servlet or jsp.
Example55
JCode Cell
1 
2 <error-page> is the direct child tag of <web-app> and hence we can take anywhere within
3

FirstServlet.java

error.jsp:

<h1>Hello your provided input is invalid...plz provide valid input</h1>

error404.jsp:

<h1>Hello Stupid..Plz cross check your url and send valid url</h1>

web.xml:

Example56
JCode Cell
1 
2 public class FirstSevlet extends HttpServlet
3 {
4 public void doGet(..)...
5 {
6 PrintWriter out = resp.getWriter();
7 out.println(10/0);
8 }
9 }
10

FirstServlet.java

|-error.jsp

|-error404.jsp

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

If we are sending the request to the FirstServlet then instead of getting ArithmeticException,we

will get error.jsp page response.

If we are sending the request with invalid url-pattern then instead of 404 status code,we will get

error404.jsp page response.

Example57
JCode Cell
1 
2 <web-app>
3
4 <servlet>
5 <servlet-name>FirstSevlet</servlet-name>
6 <servlet-class>FirstSevlet</servlet-class>
7 </servlet>
8
9 <servlet-mapping>
10 <servlet-name>FirstSevlet</servlet-name>
11 <url-pattern>/test</url-pattern>
12 </servlet-mapping>
13
14 <error-page>
15 <exception-type>java.lang.ArithmeticException</exception-type>
16 <location>/error.jsp</location>
17 </error-page>
18
19 <error-page>
20 <error-code>404</error-code>
21 <location>/error404.jsp</location>
22 </error-page>
23 </web-app>advapps2H
24

Demo Program 2 for demonistrating error pages

Example58
JCode Cell
1 
2 <h1>
3 <form action ="/advapps2I/test" >
4 Enter Name: <input type="text" name="uname"><br>
5 <input type="submit" value="Login"/>
6 </form></h1>
7

FirstServlet.java

eption,IOException

Example59
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import java.util.*;
6 public class FirstServlet extends HttpServlet
7 {
8 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletExc
9

FirstServlet.java

error401.jsp:

Example60
JCode Cell
1 
2 {
3 PrintWriter out = resp.getWriter();
4 String name= req.getParameter("uname");
5 if(name.equals("durga"))
6 {
7 out.println("<h1>your authentication is correct...you can avail the facilities</h1>");
8 }
9 else
10 {
11 resp.sendError(401);
12 }
13 }
14 }
15

FirstServlet.java

web.xml:

Example61
JCode Cell
1 
2 <h1>Your authentication is failed....plz provide valid credentials...<br/>
3 <a href="/advapps2I/login.html">Click here to login once again</a></h1><br>
4

FirstServlet.java

Example62
JCode Cell
1 
2 <web-app>
3

FirstServlet.java

Example63
JCode Cell
1 
2 <error-page>
3 <error-code>401</error-code>
4 <location>/error401.jsp</location>
5 </error-page>
6

FirstServlet.java

Example64
JCode Cell
1 
2 <servlet>
3 <servlet-name>FirstServlet</servlet-name>
4 <servlet-class>FirstServlet</servlet-class>
5 </servlet>
6

FirstServlet.java

Example65
JCode Cell
1 
2 <servlet-mapping>
3 <servlet-name>FirstServlet</servlet-name>
4 <url-pattern>/test</url-pattern>
5 </servlet-mapping>
6

FirstServlet.java

advapps2I

|-login.html

|-error401.jsp

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

Case-1:

We can configure <error-page> either based on exception type or based on error code but not

both simultaneously in the same <error-page> tag.

Eg:

Example66
JCode Cell
1 
2 </web-app>
3

FirstServlet.java

It is invalid

Case-2:

The <exception-type> tag value should be fully qualified name of exception.

Example67
JCode Cell
1 
2 <error-page>
3 <exception-type>java.lang.AE</exception-type>
4 <error-code>404</error-code>
5 <location>/error.jsp</location>
6 </error-page>
7

FirstServlet.java

It is invalid

Case-3:

The <location> value must be compulsary starts with "/",otherwise application won't be deployed.

Example68
JCode Cell
1 
2 <error-page>
3 <exception-type>IOException</exception-type>
4 <location>/error.jsp</location>
5 </error-page>
6

FirstServlet.java

It is invalid

<mime-mapping>:

We can use <mime-mapping> to map file extension with the corresponding <mime-type>.

Example69
JCode Cell
1 
2 <error-page>
3 <error-code>404</error-code>
4 <location>error.jsp</location>
5 </error-page>
6

FirstServlet.java

<mime-mapping> is the direct child tag of <web-app> and hence we can take anywhere.

war File

Objective:

  • Explain the purpose of war file?
  • Describe the contents of war file?
  • Explain the process of creation?

war (Web Archieve) provides a convenient way to store resources of web appication in a single

component.

It is a compressed file(zip file) represents total web application which may contains Servlets, JSPs,

XML Files, HTML Pages, JavaScript Files, CSS Files etc..

The main advantage of maintaining web application in the form of war file is Project delivery,

Project transportation and deployment will become easy.

Servlet specification defined a standard structure for the war file and every web server can

provide support for that war file.

Example70
JCode Cell
1 
2 <mime-mapping>
3 <extension>durga</extension>
4 <mime-type>application/pdf</mime-type>
5 </mime-mapping>
6

Various Commands

jar -cvf mywebapp.war *

Example71
JCode Cell
1 
2 Creation of war File (zip file):
3

Various Commands

jar -xvf mywebapp.war

  • Display Table of contents of war File

jar -tvf mywebapp.war

http://localhost:7777/wardemo/login.html

Structure of war File:

advapps2A

Name of Application*.htmlStatic

OR *.jpg Context

*.css

Context Root

:::

:::

*.jsp

META-INF

MANIFEST.MF

WEB-INF

web.xml

classes

*.class

lib

*.jar

tags

*.tld

*.tag

Every war file should compulsary contains META-INF folder, which should contain MANIFEST.MF.

i.e META-INF folder and MANIFEST.MF are mandatory for every war file.

META-INF folder contains security related resources like signature files,digital certificates, license

agreements etc which are mandatory for maintaining the web application.

Example72
JCode Cell
1 
2 Extraction of war File (unzip operation)
3

MANIFEST.MF

It represents one web application that contains servlets,jsps,html files...

Example73
JCode Cell
1 
2 war(web archieve)
3

MANIFEST.MF

It represents an enterprise application which contains servlets,jsps,ejbs,jms components etc..

Example74
JCode Cell
1 
2 ear(enterprise archieve):
3
📝 Key Takeaways
  • Every example is complete and compiles as-is
  • Examples are grouped by topic
  • Typing programs is the fastest way to learn servlets