Logo

Navigation
  • Home
  • Services
    • ERP Solutions
    • Implementation Solutions
    • Support and Maintenance Solutions
    • Custom Solutions
    • Upgrade Solutions
    • Training and Mentoring
    • Web Solutions
    • Production Support
    • Architecture Designing
    • Independent Validation and Testing Services
    • Infrastructure Management
  • Expertise
    • Microsoft Development Expertise
    • Mobile Development
    • SQL Server Database and BI
    • SAP BI, SAP Hana, SAP BO
    • Oracle and BI
    • Oracle RAC
  • Technical Training
    • Learn Data Management
      • Business Intelligence
      • Data Mining
      • Data Modeling
      • Data Warehousing
      • Disaster Recovery
    • Learn Concepts
      • Application Development
      • Client Server
      • Cloud Computing Tutorials
      • Cluster Computing
      • CRM Tutorial
      • EDI Tutorials
      • ERP Tutorials
      • NLP
      • OOPS
      • Concepts
      • SOA Tutorial
      • Supply Chain
      • Technology Trends
      • UML
      • Virtualization
      • Web 2.0
    • Learn Java
      • JavaScript Tutorial
      • JSP Tutorials
      • J2EE
    • Learn Microsoft
      • MSAS
      • ASP.NET
      • ASP.NET 2.0
      • C Sharp
      • MS Project Training
      • Silverlight
      • SQL Server 2005
      • VB.NET 2005
    • Learn Networking
      • Networking
      • Wireless
    • Learn Oracle
      • Oracle 10g
      • PL/SQL
      • Oracle 11g Tutorials
      • Oracle 9i
      • Oracle Apps
    • Learn Programming
      • Ajax Tutorial
      • C Language
      • C++ Tutorials
      • CSS Tutorial
      • CSS3 Tutorial
      • JavaScript Tutorial
      • jQuery Tutorial
      • MainFrame
      • PHP Tutorial
      • VBScript Tutorial
      • XML Tutorial
    • Learn Software Testing
      • Software Testing Types
      • SQA
      • Testing
  • Career Training
    • Career Improvement
      • Career Articles
      • Certification Articles
      • Conflict Management
      • Core Skills
      • Decision Making
      • Entrepreneurship
      • Goal Setting
      • Life Skills
      • Performance Development
      • Personal Excellence
      • Personality Development
      • Problem Solving
      • Relationship Management
      • Self Confidence
      • Self Supervision
      • Social Networking
      • Strategic Planning
      • Time Management
    • Education Help
      • Career Tracks
      • Essay Writing
      • Internship Tips
      • Online Education
      • Scholarships
      • Student Loans
    • Managerial Skills
      • Business Communication
      • Business Networking
      • Facilitator Skills
      • Managing Change
      • Marketing Management
      • Meeting Management
      • Process Management
      • Project Management
      • Project Management Life Cycle
      • Project Management Process
      • Project Risk Management
      • Relationship Management
      • Task Management
      • Team Building
      • Virtual Team Management
    • Essential Life Skills
      • Anger Management
      • Anxiety Management
      • Attitude Development
      • Coaching and Mentoring
      • Emotional Intelligence
      • Stress Management
      • Positive Thinking
    • Communication Skills
      • Conversation Skills
      • Cross Culture Competence
      • English Vocabulary
      • Listening Skills
      • Public Speaking Skills
      • Questioning Skills
    • Soft Skills
      • Assertive Skills
      • Influence Skills
      • Leadership Skills
      • Memory Skills
      • People Skills
      • Presentation Skills
    • Finding a Job
      • Etiquette Tips
      • Group Discussions
      • HR Interviews
      • Interview Notes
      • Job Search Tips
      • Resume Tips
      • Sample Resumes
 

Servlet Basics

By Exforsys | on December 6, 2005 |
J2EE

Servlet Basics

Servlets are Java programs running on a web server that produce results viewed remotely on a web server. Servlets has the same purpose that CGI or PHP had in the past. We shall describe how Servlets works with some examples. You will also learn about Servlet Request and Response Model, Servlet Life Cycle, Servlet Scope Objects and Error Handling.

Servlet Request and Response Model

Note that although there are two types of servlets (GenericServlet and HttpServlet), we will discuss here only HttpServlet since GenericServlet can be used for advanced needs. The important thing here is that you should use GenericServlet if you want your servlet to response in another protocol rather than HTTP.

Figure-1 Request and Response Model of HttpServlets

HttpServlets are servlets that respond to the HTTP protocol requests which is used by web servers to return us the requested web pages. We need to extend javax.servlet.http.HttpServlet class to write a servlet. We should select one of doGet or doPost methods for overriding. This choice depends on what type of http request (GET request or POST request) we are expecting. GET request is generally only used to retrieve data from the web server, however POST request are used for more complex requests like storing data. We will generally override both methods in our tutorials and call a processRequest method to handle both types of request.

Let’s start with our first servlet which is called HelloWorld1 servlet. HelloWorld1 servlet will just print “Hello World1” message.

The source code shown in this section can be found in HelloWorld1 project.

Figure-2 shows overridden doGet and doPost methods in our HelloWorld1 servlet. Both methods call processRequest method to handle the http requests. Figure-3 shows processRequest method.

/** Handles the HTTP < code >GET< /code > method.
* @param request servlet request
* @param response servlet response
*/

protected void doGet(HttpServletRequest request,
ttpServletResponse response)
throws ServletException, IOException {
..........processRequest(request, response);
}

/** Handles the HTTP < code >POST< /code > method.

* @param request servlet request

* @param response servlet response

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
..........processRequest(request, response);
}

Figure-2 Overridden doGet and doPost methods in HelloWorld1 servlet

public class HelloWorld1 extends HttpServlet {
.

/** Processes requests for both HTTP < code >GET< /code > and < code >POST< /code > methods.

* @param request servlet request

* @param request servlet response

*/

.
protected void processRequest
(HttpServletRequest request, HttpServletResponse response)

.....throws ServletException, IOException {

.....response.setContentType(“text/html;charset=UTF-8”);

..........PrintWriter out = response.getWriter();

..........Out.println(“< html >”);

..........Out.println(“< head >”);

..........Out.println(“< title >Servlet HelloWorld1< /title >”);

..........Out.println(“< /head >”);

..........Out.println(“< body >”);

..........Out.println(“< h1 >HelloWorld1< /h1 >”);

..........Out.println(“< /body >”);

..........Out.println(“< /html >”);

..........Out.close();

}

Figure-3 ProcessRequest method used in HelloWorld1 servlet

We get the PrintWriter object from HttpServletResponse object to write the contents of the html page to other side. After writing our content, we close the PrintWriter object. You will get a result similar to shown in Figure-4 after you run the project.

Figure-4 HelloWorld1 servlet running in a browser

Servlet Life Cycle

Servlet container creates only one instance of each servlet but the request of each user is handled with a separate thread. Each thread then calls doGet or doPost methods. This idea is shown in Figure-5.

Figure-5 A way of handling Servlet requests

The init method of the servlet is called when the servlet is first created and each time the server receives a request for a servlet, the server spawns a new thread calls service method.

The service method checks the HTTP request type (GET, SET, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. method as appropriate.

Finally, the server may decide to remove a previous loaded servlets. In this case, the server calls destroy method of the servlet.

Servlet Scope Objects

There are four scope objects in servlets which enables sharing information between web components. The scope objects and their corresponding Java classes are listed below:

• Web Context – javax.servlet.ServletContext
• Session – javax.servlet.http.HttpSession
• Request – javax.servlet.HttpServletRequest
• Page – javax.servlet.jsp.PageContext

You can get attribute values from servlet scope objects using getAttribute method and set new values of attributes using setAttribute method. For example, you can get the client’s IP address by calling getRemoteAddr method of HttpServletRequest class.

Let’s develop an example on how to use servlet scope objects. In this example, we will print the information about the server which hosts our servlet.

The source code shown in this section can be found in ServerInfoServlet project.

In our example, we will use the following methods to get the information about the server which hosts the client:

public String getServerName()
public String getServerPort()
public String getServletContext().getServerInfo()

Figure-6 shows processRequestMethod of ServerInfoServlet servlet and Figure-7 shows the output of the servlet in a browser.

..........

public class ServerInfoServlet extends HttpServlet {

..........
/** Processes requests for both HTTP < code >GET< /code > and < code >POST< /code > methods.

* @param request servlet request

* @param request servlet response

*/

..........

protected void processRequest (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

..........response.setContentType(“text/html;charset=UTF-8”);

..........PrintWriter out = response.getWriter();

..........

..........Out.println(“< html >”);

..........Out.println(“< head >”);

..........Out.println(“< title >Servlet ServerInfoServlet< /title >”);

..........Out.println(“< /head >”);

..........

..........Out.println(“< body >”);

..........Out.println(“< p >Server Name:+request.getServerName()+”< br >”);

..........Out.println(“ Server Port :+request.getServerPort()+”< br >”);

..........Out.println(“Server Path:+request.getServerPath()+”< /p >”);

..........
..........Out.println(“< /body >”);

..........Out.println(“< /html >”);

..........
..........Out.close();

}
..........

Figure-6 ProcessRequest method used in ServerInfoServlet servlet

Figure-7 ServerInfoServlet servlet running in a browser

Error Handling

There are two ways to handle errors in servlets. You can send an error message or throw a ServletException.

For example, if a servlet can not find the requested file, it can display a 404 (“File Not Found”) message to the user by using the following command instead of directly writing the output to the PrintWriter object:

response.sendError(HttpServletResponse.SC_NOT_FOUND)

There are several other HTTP error codes which can be sent to the client. Some of the important ones are listed in Table-1. You can search on the internet about the details of those messages if they are not clear for you.

Mnemonic

Code

Message

SC_OK

200

OK

SC_NO_CONTENT

204

No Content

SC_MOVED_PERMANENTLY

301

Moved Permanently

SC_MOVED_ TEMPORARILY

« « J2EE Overview
SQL Server 2005 – Unattended Installations » »

Author Description

Avatar

Editorial Team at Exforsys is a team of IT Consulting and Training team led by Chandra Vennapoosa.

Free Training

RSSSubscribe 391 Followers
  • Popular
  • Recent
  • J2EE Overview

    December 6, 2005 - 0 Comment
  • A Java TOC2 Class Which Can Contact Aim

    July 12, 2006 - 0 Comment
  • Servlets Advanced

    December 12, 2005 - 0 Comment
  • Quickly Develop Java Programs With Tapestry

    July 12, 2006 - 0 Comment
  • How to Install and Use NetBeans for Java Development

    June 26, 2005 - 0 Comment
  • JSP Basics

    May 7, 2006 - 0 Comment
  • How To Run J2ME Programs on Palm Devices

    July 14, 2006 - 0 Comment
  • .NET and J2EE – A Comparsion Study

    November 26, 2005 - 0 Comment
  • Antipatterns In Java Programs

    July 1, 2006 - 0 Comment
  • How To Use Java DB as Your Client Mobile Database

    July 14, 2006 - 0 Comment
  • Why It is Important To Focus On Java Exceptions For Your Programs

    July 27, 2006 - 0 Comment
  • Important Features of Java – Multithreading, AWT

    July 26, 2006 - 0 Comment
  • What You Should Know About Java XML

    July 25, 2006 - 0 Comment
  • What You Can Do To Deal With Java’s Memory Retention Problems

    July 22, 2006 - 0 Comment
  • Java Overview

    July 17, 2006 - 0 Comment
  • How To Use Java DB as Your Client Mobile Database

    July 14, 2006 - 0 Comment
  • How To Run J2ME Programs on Palm Devices

    July 14, 2006 - 0 Comment
  • Java Virtual Machine

    July 13, 2006 - 0 Comment
  • Quickly Develop Java Programs With Tapestry

    July 12, 2006 - 0 Comment
  • A Java TOC2 Class Which Can Contact Aim

    July 12, 2006 - 0 Comment

Exforsys e-Newsletter

ebook
 

Related Articles

  • Why It is Important To Focus On Java Exceptions For Your Programs
  • Important Features of Java – Multithreading, AWT
  • What You Should Know About Java XML
  • What You Can Do To Deal With Java’s Memory Retention Problems
  • Java Overview

Latest Articles

  • Project Management Techniques
  • Product Development Best Practices
  • Importance of Quality Data Management
  • How to Maximize Quality Assurance
  • Utilizing Effective Quality Assurance Strategies
  • Sitemap
  • Privacy Policy
  • DMCA
  • Trademark Information
  • Contact Us
© 2023. All Rights Reserved.IT Training and Consulting
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.AcceptReject Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT