Java Servlets Tutorial: A Concise Tutorial Just An Hour | ACTE
Java Servlets Tutorial

Java Servlets Tutorial: A Concise Tutorial Just An Hour – FREE

Last updated on 10th Jul 2020, Blog, Tutorials

About author

Vidhyawati (Sr Java Developer )

Vidhyawati is a Java developer with 8+ years of experience in a flexible business process management suite that is written in Java. She has skills in JavaScript, HTML, CSS, SQL, Python, BPMN, Red Hat Process, Drools software, Jira, and Appian.

(5.0) | 19623 Ratings 853

Today we all are aware of the need of creating dynamic web pages i.e the ones which have the capability to change the site contents according to the time or are able to generate the contents according to the request received by the client. If you like coding in Java, then you will be happy to know that using Java there also exists a way to generate dynamic web pages and that way is Java Servlet. But before we move forward with our topic let’s first understand the need for server-side extensions.

Servlets are the Java programs that runs on the Java-enabled web server or application server. They are used to handle the request obtained from the web server, process the request, produce the response, then send response back to the web server.

servlets.

    Subscribe For Free Demo

    [custom_views_post_title]

    Servlet Lifecycle

    The following figure illustrates the lifecycle of a servlet. Since it was created, processed requests from the users, until it was destroyed.

    servlets life cycle

    There are 5 step:

    •   Load Servlet Class.
    • Create Instance of Servlet.
    • Call the servlets init() method.
    • Call the servlets service() method.
    • Call the servlets destroy() method.
    servlet container

    Step 1, 2 and 3 are executed only once, when the servlet is initially loaded. By default the servlet is not loaded until the first request is received for it. You can force the container to load the servlet when the container starts up though.

    Step 4 is executed multiple times – once for every HTTP request to the servlet.

    Step 5 is executed when the servlet container unloads the servlet.

    You can see the following illustration to better understand the lifecycle of the Servlet.

    When the request of users to Servlet, the servlet will call the method of  service() to serve the requirements of users, the  service() will call either  doGet() or  doPost().

    Thus, when users request a Servlet, the servlet will be created at the time of the first request, and  will simultaneously call the  init() method of servlet to initialize it,  init() method is called only one time. Method of  destroy() is used to destroy the servlet, it will be called only once when removing deployment (undeloy) of web application or stop the web server.

    Properties of Servlets :

    • Servlets work on the server-side.
    • Servlets are capable of handling complex requests obtained from web server.

    Execution of Servlets :

    Execution of Servlets involves six basic steps:

    • The clients send the request to the web server.
    • The web server receives the request.
    • The web server passes the request to the corresponding servlet.
    • The servlet processes the request and generates the response in the form of output.
    • The servlet sends the response back to the web server.
    • The web server sends the response back to the client and the client browser displays it on the screen.

    Servlet Architecture

    The following diagram shows the servlet architecture:

    system architecture.

    Need For Server-Side Extensions:

    These APIs allow us to build programs that can run with a Web server. In this case , Java Servlet is also one of the component APIs of Java Platform Enterprise Edition which sets standards for creating dynamic Web applications in Java.

    Before learning about something, it’s important to know the need for that something, it’s not like that this is the only technology available for creating dynamic Web pages. The Servlet technology is similar to other Web server extensions such as Common Gateway Interface(CGI) scripts and Hypertext Preprocessor (PHP). However, Java Servlets are more acceptable since they solve the limitations of CGI such as low performance and low degree scalability.

    Attributes in Servlets 

    An attribute in servlet is an object that can be set, get or removed by the following aspects

    • Request Scope
    • Application Scope
    • Session Scope

    To pass the value from servlet to html/jsp files, setAttribute() method is called by the request object. setAttribute() method takes an input as an object which sends the data from servlet to the requesting website.

    Java Servlets | Need of Filters

    The need for implementing filters can be understood with the help of few examples Let’s take example of a Web application that formats the data to be presented to clients in a specific format say Excel However, at a later point of time, the clients may require data in some other format, such as Hypertext Markup Language (HTML) Portable Document Format (PDF), or Word. In sch a situation instead of modifying the code every time to change the format of data, a filter can be created to transform data dynamically in the required formats.

    Let’s consider another example where a developer creates a Web application in which a servlet handles user logins. This implies that when a user submits his credentials, the servlet verifies the credentials against the user information. The serviet also creates a session for the user, so the other components in the application can also use the session details of the user. At a later point of time, the developer might require maintaining a login entry for each user login attempt in the application server’s log system. In order to implement this, the developer would need to change the existing code or add additional code to the servlet and redeploy the Web application.

    In such a situation, a servlet, besides fulfilling its primary objective that is to accept request and send responses to clients has to implement additional functionalities. This additional lo servlet reduces the efficiency of the application. To overcome this problem filters were introduced that can implement these additional functionalities, such as verifying login credentials maintaining the server log in a database. One of the most striking features of the filters is that the can be reused in other Web applications as well.

    Some situations and tasks where filters can be used are as follows:

    • Security verification
    • Session validation
    • Logging operations
    • Internationalization
    • Triggering resource access events
    • Image conversion
    • Scaling maps
    • Data compression
    • Encryption
    • Tokenization
    • Mime type changing
    • Caching and XSL transformations of XML responses
    • Debugging
    Course Curriculum

    Learn Hands-On Practical Java Servlets Certification Course By MNC Trainers

    Weekday / Weekend BatchesSee Batch Details

    Elaboration of some situation where filters are needed:

    Modifying the Request Character cryptography : Currently, several browsers don’t send character cryptography data within the Content-Type header of a protocol request. If an cryptography has not been such by the shopper request, the instrumentation uses a default cryptography to analyse request parameters. If the shopper hasn’t set character cryptography and also the request parameters area unit encoded with a special cryptography than the default, the parameters are parsed incorrectly. you’ll be able to use the strategy setCharacterEncoding within the ServletRequest interface to line the cryptography. Since this technique should be known as before parsing any post knowledge or reading any input from the request, this perform may be a prime application for filters.

    Reduce size of the Response : Another example of a filter that modifies the response is that the compression filter contained within the examples distributed with the Tomcat servlet engine. though high-speed net connections are getting a lot of commonplace, there’s still a requirement to use information measure effectively. A compression filter is handy as a result of you’ll be able to attach it to any servlet to cut back the scale of a response.

    Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

    Advantages of a Java Servlet

    • Servlet is faster than CGI as it doesn’t involve the creation of a new process for every new request received.
    • Servlets as written in Java are platform independent.
    • Removes the overhead of creating a new process for each request as Servlet doesn’t run in a separate process. There is only a single instance which handles all requests concurrently. This also saves the memory and allows a Servlet to easily manage client state.
    • It is a server-side component, so Servlet inherits the security provided by the Web server.
    • The API designed for Java Servlet automatically acquires the advantages of Java platform such as platform independent and portability. In addition, it obviously can use the wide range of APIs created on Java platform such as JDBC to access the database.

    The Servlet Container

    Servlet container, also known as Servlet engine is an integrated set of objects that provide run time environment for Java Servlet components.

    In simple words, it is a system that manages Java Servlet components on top of the Web server to handle the Web client requests.

    Services provided by the Servlet container :

    Network Services : 

    Loads a Servlet class. The loading may be from a local file system, a remote file system or other network services. The Servlet container provides the network services over which the request and response are sent.

    Decode and Encode MIME based messages : 

    Provides the service of decoding and encoding MIME-based messages.

    Manage Servlet container : 

    Manages the lifecycle of a Servlet.

    Resource management : 

    Manages the static and dynamic resources, such as HTML files, Servlets and JSP pages.

    Security Service : 

    Handles authorization and authentication of resource access.

    Session Management : 

    Maintains a session by appending a session ID to the URL path.

    common gateway interface

    So, in CGI server has to create and destroy the process for every request. It’s easy to understand that this approach is applicable for handling few clients but as the number of clients increases, the workload on the server increases and so the time taken to process requests increases.

    • Get the basic information of the Servlet
    • You can retrieve the information relating to the time served by Servlet instance:
    • Information requests from the client.
    • Server Information 
    • Client Information
    • Header information sent on request

    Redirect:

     When a request from the user to a Servlet (page A), this servlet can redirect requests to another page (page B), and the end of its mission.  The page is redirected to  may be the page in your application, or may be any page.

    Unlike Forward:

    With Redirect you cannot use request.setAttribute(..) to transfer data from page A to page B.

    unlike forward

    Servlet database:

    This tutorial assumes you have understanding on how JDBC application works. Before starting with database access through a servlet, make sure you have proper JDBC environment setup along with a database.

    For more detail on how to access database using JDBC and its environment setup you can go through our JDBC Tutorial.

    To start with basic concept, let us create a simple table and create few records in that table as follows −

    HTTP is a “stateless” protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.

    Still there are following three ways to maintain session between web client and web server.

    Cookies:

    A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the recieved cookie.

    This may not be an effective way because many time browser does not support a cookie, so I would not recommend to use this procedure to maintain the sessions.

    Hidden Form Fields:

    A web server can send a hidden HTML form field along with a unique session ID as follows.
    This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of different web browsers.

    This could be an effective way of keeping track of the session but clicking on a regular (<A HREF…>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking.

    URL Rewriting:

    You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session.

    For example, with http://tutorialspoint.com/file.htm;sessionid = 12345, the session identifier is attached as sessionid = 12345 which can be accessed at the web server to identify the client.

    URL rewriting is a better way to maintain sessions and it works even when browsers don’t support cookies. The drawback of URL re-writing is that you would have to generate every URL dynamically to assign a session ID, even in case of a simple static HTML page.

    The HttpSession Object:

    Apart from the above mentioned three ways, servlet provides HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.

    The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user.

    Java Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    You would get HttpSession object by calling the public method getSession() of HttpServletRequest.
    You need to call request.getSession() before you send any document content to the client. Here is a summary of the important methods available through HttpSession object.

    Conclusion

    This module explained what servlets are and placed them in context. You know how the Web browser and Web server work together to get information to the user.

    The browser sends a GET request and some request headers.

    The server sends some response headers and then a stream of HTML.

    Many times the HTML is from a file, however, it can also be one of the following:

    • the output of a CGI program that ran on the Web server
    • it could be a file, with some other information included by the server, using server side includes or ASP.
    • it could be the output of a servlet.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free