Head First Servlets and JSP

Bryan Basham, Kathy Sierra, Bert Bates

Mentioned 19

This book gets readers up to speed on the technology necessary to write servlets and JSPs, what makes the Container tick, how to use the new JSP Expression Language (EL), how to write deployment descriptors, and even how to use some server-side design patterns.

More on Amazon.com

Mentioned in questions and answers.

It seems that there are two methods for templating with JSP. Including files with one of these statements

<%@ include file="foo.html" %>
<jsp:include page="foo.html" />

or using JSP tag files

// Save this as mytag.tag
<%@ tag description="Description" pageEncoding="UTF-8"%>

And in another JSP page call it with

<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>

    <h1>Hello World</h1>

So which method should I use? Is one now considered deprecated or are they both valid and cover different use cases?


Isn't using this tag file the same as using an include?

// Save this as product.tag
<%@ tag description="Product templage" pageEncoding="UTF-8"%>
<%@ tag import="com.myapp.Product" %>
<%@ attribute name="product" required="true" type="com.myapp.Product"%>

Product name: ${product.name} <br/>
Quantity: ${product.quantity} <br/>

And call it on another JSP with

<%@ taglib prefix="t" tagdir="/WEB-INF/tags" %>

    <c:forEach items="${cart.products}" var="product">
        <t:product product="${product}"/>

That seems to me to be the very same as using an include and passing parameters to it. So are Tag Files the same as includes?

There are several mechanisms for reusing content in a JSP page.

The following 4 mechanisms to include content in JSP can be categorized as direct reuse:
(for the first 3 mechanisms quoting from "Head First Servlets and JSP")

1) The include directive:

<%@ include file="header.html" %>

Static: adds the content from the value of the file attribute to the current page at translation time. The directive was originally intended for static layout templates, like HTML headers.

2) The <jsp:include> standard action:

<jsp:include page="header.jsp" />

Dynamic: adds the content from the value of the page attribute to the current page at request time. Was intended more for dynamic content coming from JSPs.

3) The <c:import> JSTL tag:

<c:import url=”http://www.example.com/foo/bar.html” />

Dynamic: adds the content from the value of the URL attribute to the current page, at request time. It works a lot like <jsp:include>, but it’s more powerful and flexible: unlike the other two includes, the <c:import> url can be from outside the web Container!

4) Preludes and codas:

Static: preludes and codas can be applied only to the beginnings and ends of pages.
You can implicitly include preludes (also called headers) and codas (also called footers) for a group of JSP pages by adding <include-prelude> and <include-coda> elements respectively within a <jsp-property-group> element in the Web application web.xml deployment descriptor. Read more here:
Configuring Implicit Includes at the Beginning and End of JSPs
Defining implicit includes

Tag File is an indirect method of content reuse, the way of encapsulating reusable content. A Tag File is a source file that contains a fragment of JSP code that is reusable as a custom tag.

The PURPOSE of includes and Tag Files is different.

Tag file (a concept introduced with JSP 2.0) is one of the options for creating custom tags. It's a faster and easier way to build custom tags. Custom tags, also known as tag extensions, are JSP elements that allow custom logic and output provided by other Java components to be inserted into JSP pages. The logic provided through a custom tag is implemented by a Java object known as a tag handler.

Some examples of tasks that can be performed by custom tags include operating on implicit objects, processing forms, accessing databases and other enterprise services such as email and directories, and implementing flow control.

Regarding your Edit

Maybe in your example (in your Edit), there is no difference between using direct include and a Tag File. But custom tags have a rich set of features. They can

  • Be customized by means of attributes passed from the calling page.

  • Pass variables back to the calling page.

  • Access all the objects available to JSP pages.

  • Communicate with each other. You can create and initialize a JavaBeans component, create a public EL variable that refers to that bean in one tag, and then use the bean in another tag.

  • Be nested within one another and communicate by means of private variables.

Also read this from "Pro JSP 2": Understanding JSP Custom Tags.

Useful reading.


Use the right instruments for the concrete task.

Use Tag Files as a quick and easy way of creating custom tags.

As for the including content in JSP (quote from here):

  • Use the include directive if the file changes rarely. It’s the fastest mechanism. If your container doesn’t automatically detect changes, you can force the changes to take effect by deleting the main page class file.

  • Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested.

I am new to servlets. I got the init parameters in DD within the init() method using getInitParameter("name"). I tried a lot from within doGet() method to access the init parameters, but it always returns null.

I tried with


and with


but they all return null. Can I get the init parameters in the doGet()?

The answer is - Yes, you can.

OK, besides the JB Nizet's comment here are a few suggestions.

1) Have you added your init parameters while the Web Container / Application Server was running?

Quote from "Head First Servlets & JSP: Passing the Sun Certified Web Component Developer Exam":

The servlet init parameters are read only ONCE - when the Container initializes the servlet. ...
When the Container makes a servlet, it reads the DD and creates the name/value pairs for the ServletConfig. The Container never reads the init parameters again! Once the parameters are in the ServletConfig, they won’t be read again until/unless you redeploy the servlet.

2) There are two types of init parameters available. Another quote from "Head First Servlets and JSP" (emphasis mine):

There are context init parameters (defined in <context-param> element) and servlet init parameters (defined in <init-param> element). They are both referred to as init parameters, although defined in defferent elements.

  • Context init parameters are available to any servlet or JSP that are part of the current web app.

  • Servlet init parameters are available to only the servlet for which the <init-param> was confgured.

  • Context init parameters are defined within the <web-app> element.

  • Servlet init parameters are defined within the <servlet> element for each specific servlet.


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"

    <display-name>Servlet testing app</display-name>

    <!-- This is a context init parameter -->

        <servlet-name>Info Servlet</servlet-name>
        <!-- This is a servlet init parameter -->
            <param-value>John Doe</param-value>
        <servlet-name>Info Servlet</servlet-name>


Accessing context init parameter in a servlet:

Accessing servlet init parameter in a servlet for which it was defined in the deployment descriptor:

An alternative way of getting servlet init parameter is using a method defined in the abstract class GenericServlet:
public String getInitParameter(String name);
This method is supplied for convenience. It gets the value of the named parameter from the servlet's ServletConfig object.

And there is also Enumeration<String> getInitParameterNames() method for both ServletContext and ServletConfig to get all init parameters.

Hope this will help you.

I'm looking to start developing for the web using Java - I have some basic Java knowledge, so that's not a problem, but I'm at a loss when it comes to deciphering the various technologies for use in web applications.

What options are available to me? How do they work? Are there any frameworks similar to Django/Ruby on Rails which I could use to simplify things?

Any links which could help with understanding what's available would be much appreciated.

I learned Java in college back when it was in version 1.1.5. I recently started trying to program for the web, but it didn't make sense until I read Head First Servlets and JSP. There are way more things involved in web development with Java than I ever realized, and without this book, I would have quit and just used PHP.

I am trying to implement a servlet that gets raw requests, and decide either to process them, or forward them to another backend server. It is similar to a load-balancer, where a received request is forwarded to one of the (in my case 2) destinations. One of the destination is remote (on another host). Furthermore, the requests could come to the root (http://mycompany.com/).

Since I want to get raw requests, I implemented my own servlet (subclassing HttpServlet), and that works great. My servlet looks like:

public class MyProxyServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        processOrForward(req, resp);
    // also doGet(), doHead(), ...

Since the service I want to process may send requests to the root, I would like to map my servlet to be the default servlet, thereby receiving any request that does not have an explicit servlet mapping. Assume my servlet's name is "myservlet", and is running along side of another servlet "foo", I expect all requests in the form of http://mycompany.com/foo/... to be delivered to foo, and everything else (e.g., /, /bar/..., /myservlet/...) to "myservlet". Looking at earlier posts (eg., root mapping here and here, or url rewriting here), I thought I figured it out, but it does not work.

Here is my web.xml:



In the above web.xml, for url-pattern I tried

"/" and "/*" and empty (i.e., <url-pattern></url-pattern>), all behave the same -->
    Requests to root (/)goes to tomcat's default servlet
    Requests to /myservlet/... are handled by "myservlet"
    Requests to /fubar/... are always 404

Is there a way of turning my servlet to be the default. I.e., any request that does not map specifically to a servlet comes to mine (it is even acceptable to receive all requests, since I can deploy this servlet in its own container). In case it matters, I am using Tomcat 7.0.30 on Ubuntu 12.10.

This should be useful to you.

From the Java™ Servlet Specification Version 3.1 (JSR 340)

Chapter 12. Mapping Requests to Servlets

12.2 Specification of Mappings

In the Web application deployment descriptor, the following syntax is used to define mappings:

  • A string beginning with a / character and ending with a /* suffix is used for path mapping.

  • A string beginning with a *. prefix is used as an extension mapping.

  • The empty string ("") is a special URL pattern that exactly maps to the application's context root, i.e., requests of the form http://host:port/<contextroot>/. In this case the path info is / and the servlet path and context path is empty string ("").

  • A string containing only the / character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.

  • All other strings are used for exact matches only.

As an addition, read this nice explanation with short examples from the book Head First Servlets & JSP: Passing the Sun Certified Web Component Developer Exam (2nd edition) (quote):

The THREE types of <url-pattern> elements

1) EXACT match


  • MUST begin with a slash (/).
  • Can have an extension (like .do), but it’s not required.

2) DIRECTORY match


  • MUST begin with a slash (/).
  • Always ends with a slash/asterisk (/*).

3) EXTENSION match


  • MUST begin with an asterisk (*) (NEVER with a slash).
  • After the asterisk, it MUST have a dot extension (.do, .jsp, etc.).

The URL patterns represent logical / virtual structure, i.e. the patterns (paths) specified does not need to exist physically.


If you want, as you say in your comment,

I want host:port to hit my servlet, not the default tomcat servlet

then see the solution here:
How do I make my web application be the Tomcat default application

In other words, what you want is a path without application context, which implies the application context of the Tomcat default application.

Quote from the above link:

In a standard Tomcat installation, you will notice that under the same directory (CATALINA_BASE)/webapps/, there is a directory called ROOT (the capitals are important, even under Windows). That is the residence of the current Tomcat default application, the one that is called right now when a user calls up http://myhost.company.com[:port]. The trick is to put your application in its place.

I need to start developing using this technology servlets/jsp with tomcat. I need to get up to speed fairly quick. What would you recommend to get up there fairly quick? No 900+ pages manuals. A good tutorial (even a video lectures) with lots of examples would be perfect.


so now i think i have learned all basics and terminology for java. but what i don´t know is how to code and display a web page with Netbeans in Java.

the most tutorials contains lots of talks about different technologies "Java uses Java Beans, JSP and servlets" and so on. Where can i find short practical tutorials that actually teach me where to code what and then compile and where to put all the files (war, jar, ear..) in Glassfish to be able to see the output from a Web browser. Simples things that makes one understand all these different "layers" which are just classes using classes. Feels like i never get to know how i can put up a web server with Java cause I can´t find this kind of tutorials.

Would be great if someone could send some links to such practical stuff.


I would start by taking a look at servlets and JSP. I found this book helpful when I read it: Head First Servlets and JSP

I have some experience writing web applications in Java for class projects. My first project used Servlets and my second, the Stripes framework.

However, I feel that I am missing the greater picture of Java web development. I don't really understand the web.xml and context.xml files. I'm not sure what constitutes a Java EE application as opposed to a generic Java web application. I can't figure out how a bean is different from an ordinary Java class (POJO?) and how that differs from an Enterprise Java Bean (EJB). These are just the first few questions I could think of, but there are many more.

What is a good way to learn how Java web applications function from the top down rather than simply how to develop an application with a specific framework? (Is there a book for this sort of thing?) Ultimately, I would like to understand Java web applications well enough to write my own framework.

Update: To be clear, I am not interested in learning how to use specific frameworks (for instance, Spring or Java EE). I am looking for an explanation of the internals of a generic Java web application.

I don't really understand the web.xml and context.xml files.

The web.xml file is just a configuration file which instructs the application server under each which filters/servlets to load and instantiate and on which url-patterns those should be invoked.

The context.xml is just another configuration file which instructs the application under each where the webapp is located at the local storage system and on which domain/URL context it should listen.

The appserver parses both files on startup and takes actions accordingly.

I'm not sure what constitutes a Java EE application as opposed to a generic Java web application.

It's unclear what your own definitions of "Java EE application" and "Generic Java Web application" are. To answer such a question (even though yourself), you'll need to lookup and/or redefine the definitions. But in general, there are two kinds of Java EE applications: web applications (usually to be deployed in flavor of WAR's) and enterprise applications (usually to be deployed in flavor of EAR's). The major difference is that the second involves EJB's and thus require to be run on an application which supports EJB's (e.g. Tomcat doesn't).

I can't figure out how a bean is different from an ordinary Java class (POJO?) and how that differs from an Enterprise Java Bean (EJB). These are just the first few questions I could think of, but there are many more.

Those are just terms which are been applied dependent on the purpose (and history) of the class in question. The term "POJO" is a (generally negative) term representing a Javabean which is just a value object (totally no business logic, pure bean with only getter/setter methods) and is generally a model object which is part of a "legacy" program which uses EJB/Hibernate. Some call it VO (Value Object), others call it DTO (Data Transfer Object), again others just stick to "javabeans".

What is a good way to learn how Java web applications function from the top down rather than simply how to develop an application with a specific framework? (Is there a book for this sort of thing?) Ultimately, I would like to understand Java web applications well enough to write my own framework.

Start with Head First Servlets & JSP. Read the Servlet API and try to implement one yourself. Knowledge of HTTP is however mandatory as well. Read/debug/play/hack the source of existing open source Servlet API implementations (e.g. Tomcat). Read/debug/play/hack the source of existing open source (MVC) frameworks (e.g. JSF). Try to understand how they works and then try to do it better. For the learning path ("What skills do I need?") I've posted a similar answer before here.

The best way to explore the Java world and to connect all the dot’s is to just use one of the frameworks, as all use web.xml, context.xml and Java EE components (all can persist the Pojo entity beans). As you already know the Stripes framework, I can recommend this book (it’s short an handles all the aspects you named):

Stripes: ...and Java Web Development Is Fun Again, by Frederic Daoud, Pragmatic Programmers, ISBN: 1934356212

A more thoroughly approach for a deeper understanding of these Java EE technologies would be to gain all the knowledge necessary for passing these two Java Certification exams:

Sun Certified Web Component Developer (SCWCD)

Sun Certified Business Component Developer (SCBCD)

Where do I have to put my *.class file in Tomcat Directory?

In my Java-Complete Reference book, they told to put it in C:\Program Files\Apache Tomcat 4.0\webapps\examples\WEB-INF\classes. But now i'm using Tomcat 7.0. There is no folder exists with the name "examples" in webapps.

How can I fix this? Can you tell me links that will illustrate Servlets from beginning?

Just create one yourself. Any folder which you create in Tomcat/webapps will become a standalone webapplication. You don't even need to name it explicitly /examples. You can even name it /beer. You then just have to change the URL from http://localhost:8080/examples to http://localhost:8080/beer.

That said, I think it's better to look for a more recent book than the one mentioning Tomcat 4.0 which is already over a decade old. There might be more old fashioned advices/practices in the book which really can't be done anymore nowadays (for example, cough, scriptlets). Those books are more recent (in order from newest to older):

To learn JSP/Servlets online, I can recommend the tutorials and ebook at coreservlets.com:

See also:

Where can I get knowledge about servlets?

Background [from Jacob]:

Servlets are server side java programs. For example when you submit a order to buy some stuff a servlet could process your order and send you an email confirmation.

Servlets handle requests better than say CGI and most other technologies.

Servlets need a web container or a J2EE container to be able to deploy, your normal http server will not be sufficient.

Servlets are backed by the java programming language and as such programming languages theoretically have no limitations on delivering functionality, this is not true of some other languages

General Information

Sun's Tutorials


After reading the official tutorial. Think of getting a copy of Head First Servlet and JSP. Servlet and related techs would become handy after reading this.

I usually write my web services using PHP + Mysql, in a simplified way: reading the POST/GET params, connecting to the MySQL database and finally printing a JSON.

I'd like to check how to do this with a Java server, I've never programmed Java web servers and I'd like to know what should I study to learn to do it


I'm supposing here that you have a good understand of java programming.

Fisrtly, I think you should understand java for web. I recommend this book:

Head First Servlets and JSP http://www.amazon.com/Head-First-Servlets-JSP-Certified/dp/0596516681/

Then you can learn web services with java:

Java Web Services: Up and Running http://www.amazon.com/Java-Web-Services-Up-Running/dp/1449365116

Of course, there are many tutorials over the internet as well, but books give you a lot of background information.

Please bear with me here, I'm a student and new to Java Server Pages. If I'm being a complete idiot, can someone give me a good link to a tutorial on JSP, since I've been unable to find info on this anywhere.

Okay, here goes...

I'm using Netbeans and trying to pass an object that connects to a database between the pages, otherwise I'd have to reconnect to the database every time a new page is displayed.

Using Netbeans, you can view each page as "jsp", in "design" view, or view the Java code. In the Java code is the class that extends an AbstractPageBean. The problem is that I'd like to pass parameters, but there is no object representing the class and so I can't just access the instance variables.

Can anyone tell me how to do this?

I second the suggestion for the Head First book on JSP and Servlets. Don't be put off by the cutesy presentation, it's very thorough and the manner in which the information is presented is very effective both in terms of making it easy to learn, and helping it to 'stick'.

You could consider taking the Sun Java Web Component Developer certification exam, it's a good way to force yourself to learn the material thoroughly. Unfortunately, you'll need to take the Sun Java Programmer certification first.

class father {
    static int s = 0;

father f1 = new father();
father f2 = new father();
out.println(f2.s); // It must print "1"

When I run the file, I got this error. Can anybody explain?

The field s cannot be declared static; static fields can only be declared in static or top level types.

Don't do this in a JSP. Create a real Java class, if need be in flavor of a Javabean.

public class Father {
    private static int count = 0;
    public void incrementCount() {
    public int getCount() {
        return count;

and use a Servlet class to do the business task:

public class FatherServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Father father1 = new Father();
        Father father2 = new Father();
        request.setAttribute("father2", father2); // Will be available in JSP as ${father2}
        request.getRequestDispatcher("/WEB-INF/father.jsp").forward(request, response);

which you map in web.xml as follows:


and create /WEB-INF/father.jsp as follows:

<!doctype html>
<html lang="en">
        <title>SO question 2595687</title>

and invoke the FatherServlet by http://localhost:8080/contextname/father. The ${father2.count} will display the return value of father2.getCount().

To learn more about programming JSP/Servlets the right way, I recommend you to get yourself through those tutorials or this book. Good luck.

There seems to be a dearth of fresh JSP reference books to purchase. Most are from between 1999 and 2003, with almost nothing after that. There are still lots of Java books, and while most of the syntax is easily swapped, I'd rather have a reference book specifically for the dynamic browser aspect.

Does anyone have recommendations?

Head First Servlets and JSP covers the topic very comprehensively and gently. The 2nd edition was published in 2008 and AFAIK there have been little or no changes to the JSP spec since then.

Although this book covers both Servlets and JSPs, in most environments where JSPs are being used, Servlets (or something similar like Struts actions) are also used. Because JSPs are Servlets at runtime, it could be argued that understanding Servlets is a pre-requisite for understanding JSPs.

What I want to realize is the following: In a JSP x I have a 3 dropdownlists and a button called edit when user click this button a table dynamically should be displayed. Now this table is modified correponding the values in those 3 dropdownlists. So it can be 3 cols or 4 cols or even 6 cols, it depends on the selected values. So what I tried is to use the servlet to getParameter doing the if clause construct the html and then forward the response. Have you any the suggestion of the structure that I can use in JSP? Thank you.

You shouldn't construct HTML in the servlet. Do it in the JSP. You can use JSTL to control the page flow in JSP page. Just drop jstl-1.2.jar in /WEB-INF/lib and declare the taglibs as per the aforelinked TLD documentation.

You can use the <c:if> or <c:choose> tag to introduce a condition in the page flow. You can use the <c:forEach> tag to iterate over an array or a collection in JSP. Your functional requirement is pretty vague, but here's a kickoff example:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!doctype html>
<html lang="en">
        <title>SO question 2690671</title>
            <select name="cols">
            <select name="rows">
            <input type="submit">
        <c:if test="${param.cols > 0 && param.rows > 0}">
            <p>Here is a table with ${param.cols} cols and ${param.rows} rows.
                <c:forEach begin="1" end="${param.rows}">
                        <c:forEach begin="1" end="${param.cols}">

Pretty straightforward, isn't it? You actually don't need a servlet here, unless you want to preprocess the rows/cols and implement some validation/business logic. Just change the form action to the servlet URL and let the servlet forward the request to the JSP using requestdispatcher which was already explained to you in several answers before. Don't process the HTML in Servlet. There's no need to do that.

After all, you really need get yourself through some basic JSP/Servlet tutorials/books first instead of stabbing around in the dark. You can find excellent online JSP/Servlet tutorials here and you can find good books here and here. Leave your project aside and concentrate you on actually learning the stuff.

Basically I am trying to map a servlet to my web.xml but it's not working.

Here is how i am doing it:

Project directory: C:\Program Files (x86)\Apache Software Foundation\Tomcat 9.0\webapps\ROOT

FYI: I have removed all apache default webapp files and have putted my own project, so it could be accessed with just localhost which works fine.

My servlet location in my drive: C:\Program Files (x86)\Apache Software Foundation\Tomcat 9.0\webapps\ROOT\src\duck\reg\pack\userlogin.java

My package in eclipse IDE: package in eclipse IDE Image

and my web.xml file:

 <?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">


My HTML Form:

<form method="POST" action="/ROOT/WebContent/src" autocomplete="off">
    .../ code

I don't know why but this doesn't works, and I am not running apache through Ecplise

Thanks for all replies:)

Change your web.xml as below


and In your HTML form

<form method="POST" action="userlogin.do" autocomplete="off">
    .../ code

For complete explanation refer the page taken from the book Head First Servlets & JSP.

enter image description here

I already know the syntax of Java, my next educational goal is to learn a framework (or library), some friends advice me to go for Spring some other advice me to go for Java EE 6.

I wonder which is better to start learning and practicing with. Would you please help me to choose a book or manual to enter the practical world of Java?

I think it's better to start learning basic Java EE concepts (as you said you are php developer and you just started to learn java syntax). Because to understand Java EE frameworks you need to know what is Servlet and JSP and other basic concepts like filters or servlet container (like tomcat). After you developed some simple Java EE application with Servlet and JSP you would be ready to learn more advanced concepts and frameworks (like Spring). My advice is start to read Head First Servlet & JSP or any online resources that learns you these concepts.

Good luck.

I am a fairly experienced Java programmer that is interested in learning Java EE. Could someone point me to (or describe) how I can get a test environment set up locally so that I can start developing an application (i.e. what webserver I should use, framework if any - Spring? etc.). I am working on a linux machine. I think I will learn much faster this way instead of reading a book or a tutorial. Thanks in advance.

Update: Thanks for the answers so far. Should I start with Spring/Hibernate or should I familiarize myself with the basics of EE first?

  1. Get and install Java SE JDK.
  2. Get and install "Eclipse IDE for Java EE developers"
  3. Get and install Apache Tomcat 6.0 core binary distribution
  4. Start Eclipse and go to Workbench. Open the Servers view in the right bottom box. Rightclick > New > Server, select Apache Tomcat 6.0 from list, locate the Tomcat installation directory (its root folder) and Finish.
  5. Go to the left column (project explorer). Rightclick > New > Dynamic Web Project, give it a name, ensure that Tomcat is selected as target runtime. On Next you can specify the context name which would then appear as contextname in http://example.com/contextname.

Now you can create classes in project's src folder and create web files in WebContent folder. You can follow any decent JSP/Servlet tutorial for this. For example the Sun Java EE tutorial part II or the Coreservlets tutorials. If you prefer books, I can recommend the Head First Servlets & JSP.

To run a web project, rightclick the Tomcat instance in Servers view, add the newly created web project, start Tomcat server and visit http://localhost:8080/contextname/whateverpage.jsp in your favourite webbrowser.

I am learning servlets and I know that servlet lifecycle will be call at the time of loading of servlet or whenever request sent to servlet. But how the web container knows at the time of loading of servlet I need to call Servlet init method or at the time of request came I need to call Service() method? I want know how exacty web container internally invoking init(), Service() Method at the time of loading of servlet and request sent by client at code level?

I took the below code from Tomcat 8 Source code which is loading the servlet and calling init() of the servlet.

Full source code available here.

    public synchronized Servlet loadServlet() throws ServletException {
        if (singleThreadModel) {
            Servlet instance;
            try {
                instance = existing.getClass().newInstance();
            } catch (InstantiationException e) {
                throw new ServletException(e);
            } catch (IllegalAccessException e) {
                throw new ServletException(e);
            return instance;
        } else {
            if (!instanceInitialized) {
                instanceInitialized = true;
            return existing;

This page from Head first servlets & JSP book explains the lifecycle clearly,

enter image description here

For more details, I recommend to read Head First Servlets & JSP