Skip to content

Servlet in Java

Servlet in java

The Java Servlet technology provides a simple, vendor-independent mechanism to extend the functionality of a Web server. This technology provides high level, component-based, platform-independent, server-independent standards to develop Web applications in Java. The Java Servlet technology is similar to other scripting languages, such as Common Gateway Interface (CGI) scripts, JavaScript (on the client-side), and Hypertext Preprocessor (PHP). However, servlets are more acceptable as they overcome the limitation of CGI, such as low performance and scalability.

What is a servlet?

servlet is a simple Java class working on the request-response model. Various interfaces and classes to handle common HTTP-specific services are defined in the Java Servlet API. Each servlet implements the Servlet interface by providing the implementation of the servlet life cycle methods, init(), service(), and destroy().

A servlet is a simple Java class, which is dynamically loaded on a Web server and thereby enhances the functionality of the Web server. Servlets are secure and portable as they run on Java Virtual Machine (JVM) embedded with the Web server and cannot operate outside the domain of the Web server. In other words, servlets are objects that generate dynamic content after processing requests that originate from a browser. They are Java components that are used to create dynamic Web applications. Servlets can run any Java-enabled platform and are usually designed to process Hypertext Transfer Protocol (HTTP) requests such as GET and POST.

Java Servlets provides various key features, such as security, performance, as well as the request and response model. In addition, a key feature of a servlet is that you can create multiple instances of a servlet with different data and each servlet can be configured with different names. In addition, scripting languages can be used in servlets to dynamically modify or generate Hypertext Markup Language (HTML) pages.

Security in Servlet

Servlets have access to information about their clients. Peer identities can be determined reliably when servlets are used with secure protocols, such as Secure Sockets Layer (SSL) Servlets that rely on HTTP also have access to HTTP-specific authentication data.
Servlets are similar to Java. For example, as in Java, memory access violations and strong typing violations are also not possible with servlets. Due to these advantages, faulty servlets do not crash servers, which is common in most C language server extension environments.

Java Servlet provides strong security policy support, unlike any other current server extension API. This is because a security manager, provided by all Java environments, can be used to control the permissions for actions such as accessing a network or file. Servlets are not considered trustworthy in general and are not allowed to carry out the actions by default. However, servlets that are either built into the server or digitally signed servlets that are put into Java Archive (JAR) files are considered trustworthy and granted permissions by the security manager. A digital signature on any executable code ensures that the organization that created and signed the code takes the guarantee of its trustworthiness. Such digital signatures cannot support answerability for the code by themselves. However, they do provide assurance about the use of that code. For example, all code that accesses network services within a corporate Intranet of the Management Information System (MIS) organization may require having a particular signature, to access this network services. The signature on the code ensures that the code does not violate any security policy.
Below figure shows the approaches to server extensions depicting the Java server security manager layer used by servlets to verify permissions:

activities of signed and unsigned servlet

Above picture, compares two approaches to server extensions:

  • Activities of servlets in case of signed servlets, which are monitored at fine granularity by Java security manager
  • Activities of native code extensions in case of unsigned servlets, which are never monitored
  • In both cases, the host operating system usually provides very coarse-grained protection
  • In languages, such as C or scripting languages, extension APIS cannot support fine-grained access controls, even if they do allow digital signatures for their code. This explains that Pure Java Extensions are fundamentally more secure than current competitive solutions including, in particular, ActiveX of Microsoft

There are some immediate commercial applications for such improved security technologies. At present, it is not possible for most Internet Service Providers (ISPS) to accept server extensions from their clients. The reason is that the ISPs do not have proper methods to protect themselves or their clients from the attacks building on extensions, which use native C code or CGI facilities. However, it has been observed that extensions built with pure Java Servlet can prevent the modification of data. Along with the use of digitally signed code, ISPs can ensure that they safely extend their Web servers with the servlets provided by their customers.

Performance of Servlet

One of the most prominent performance features and of Java Servlets is that a new process need not be created for every new request received. In most environments, several environments, several servlets run in parallel to the server within the same process. This is a big advantage. When you use servlets in such environments with HTTP, performance is assumed to be much better than what it would be if the CGI or Fast-CGI approach was used.

New Features in Servlet 3.0

Various new features have been introduced in Servlet 3.0, the new version of Java Servlet. However, before discussing these features, let’s briefly review Servlet 2.5, which was the previous version of Java Servlet. The features of Servlet 2.5 have been retained in Servlet 3.0; therefore, let’s first discuss the features of Servlet 2.5.

Servlet 2.5 introduced several new advancements, such as changes in the web.xml file and in filter mapping, and support for annotations. We assume that you are familiar with the classes and methods of the previous versions of Java Servlets. The following features and enhancements have been included in Servlet 2.5:

  • Provides support for the new language features of J2SE 5.0, such as generics, the new enum type, and autoboxing. Note that the minimum platform requirement for the Servlet 2.5 specification is JDK 1.5 (J2SE 5.0). This implies that Servlet 2.5 cannot be used in versions below JDK 1.5
  • Provides support for annotations. An annotation is a special form of syntactic metadata that is added to the Java source code in such a way that processors may alter their behavior based on the metadata information.
  • Introduces changes in the web.xml file that have allowed Java developers to easily configure the resources of an application. In addition, in Servlet 2.5, you can bind all servlets to a filter simultaneously, which was not possible in the earlier versions. Now, it is possible to use an asterisk (*) within the <filter-mapping> element as the value of the <servlet-name> element to represent all servlets. Moreover, you can provide multiple matching criteria in the same entry while writing the <servlet-mapping> or <filter-mapping> elements in Servlet 2.5. Earlier, the <servlet-mapping> element supported a single <url-pattern> element; however, now in Servlet 2.5, the <servlet-mapping> element supports more than one URL pattern.
  • Removes two major restrictions in error-handling and session tracking. Earlier, there was a rule that the resource configured in the <error-page> element could not call the setStatus () method to alter the code provided to display an error message. However, the Servlet 2.5 specification no longer prevents the error-handling page to produce a non-error response. Therefore, the error-handling page can do far more than just show an error. Moreover, in the case of session tracking, Servlet 2.5 does not allow you to set response headers for a servlet called by the RequestDispatcher include () method.
  • Clarifies certain options available in the Servlet 2.4 specification. These clarifications are as follows:
    • According to the Servlets 2.4 specification, before calling the request.getReader() method, you need to call the request.setCharacterEncoding () method. However, the specification does not clarify why this needs to be done. The Servlet 2.5 specification describes this properly and states that if you ignore this specification option, the request.getReader() method is not executed.
    • The Servlets 2.4 specification does not define what happens if the session id is not specified. However, the Servlet 2.5 specification states that the HttpServletRequest interface will return false if the session id is not specified.
    • The Servlet 2.4 specification states that a response should be committed in most situations. The following code snippet shows a situation where the amount of content specified in the setContentLength() method of the response is not greater than zero and has been returned to the response:
      res.setHeader(“Host”, “localhost”);
      res.setHeader(“Pragma”, “no-cache”);
      res.setHeader(“Content-Length”,”0″); res.setHeader(“Location”,”www.erainnovator.com”)

      In the preceding code snippet, a servlet technically ignores the Location header because the response must be committed immediately, as the zero-byte content length is satisfied. However, the Servlet 2.5 specification states that the response should be committed when the amount of content specified in the setContentLength() method of the response is greater than zero and is returned to the response.

    • The Servlet 2.5 specification changes the rules of cross-context session management. This feature is used when Servlets dispatch requests from one context to another. The Servlet 2.5 specification states that resources present in a context can refer to the session of that context, irrespective of the origin of a request.

All the preceding features of Servlet 2.5 are also retained in Servlet 3.0, along with the introduction of some new features. The following new features have been included in Servlet 3.0:

  • Introduction of annotations as an enhanced feature. When you use annotations to create Servlets, using Deployment Descriptor in the form of the web.xml file to map the servlet is optional Developers can directly mark servlets by using annotations. However, if Deployment Descriptor is also used, it overrides the configuration information provided by using annotations. Some of the annotations introduced in Servlet 3.0 are as follows:
    • @WebServlet annotation: Marks the annotated class as a servlet
    • @WebinitParam annotation: Specifies the init parameters to be passed to the servlet.
    • @WebListener annotation: Marks the annotated class as a listener
  • Introduction of Web fragments to implement the concept of modularization of the web.xml file. A Web fragment can be assumed as a segment of the web.xml file. This implies that one or more Web fragments constitute a web.xml file. All configuration information specified in the web.xml file can also be specified in the web-fragment.xml file. When multiple web fragment.xml files exist for a Web application, the order of their execution can be decided by specifying absolute or relative ordering.
  • Introduction of the concept of asynchronous processing, which is implemented by setting the asyncSupported attribute of the @WebServlet or @WebFilter annotation. The asyncSupported attribute takes a Boolean value, which should be set to true to obtain asynchronous processing. In asynchronous processing, a servlet does not have to wait for a response from the request made for a resource, such as a database.

Learn more about the Life Cycle of Servlet

nv-author-image

Era Innovator

Era Innovator is a growing Technical Information Provider and a Web and App development company in India that offers clients ceaseless experience. Here you can find all the latest Tech related content which will help you in your daily needs.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.