• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Servlet » Servlet Introduction

Creating and Executing Servlets

By Dinesh Thakur

Servlets are platform independent and can work with almost all the web servers. They can be executed on any web server that supports the servlet API. Some of the web servers having built-in support for Java servlets are Tomcat server (Apache), Java web server (Sun Microsystems), Enterprise server (Netscape), Zeus web server (Zeus Technology), Tengah application server (Weblogic) and Sun web server (Sun Microsystems).

In this unit, we will be using the Tomcat server to explain the steps required to execute the servlet in Windows environment. Assume that the default location of Tomcat 6.0 is as follows.

C:\Program Files\Apache Software Foundation\Tomcat 6.0\

Following are the steps to create and execute the servlet.

1. Create a . java source file containing the code for creating servlet and save it with the name, say Sample. java.

2. Compile this source file, as a result Sample . class file will be created.

3. Copy the Sample. class file in the directory under the webapps directory of Tomcat. The

path for the directory is as follows.

C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\MyApp\WEB-INF\classes

Add the name and mapping of this servlet in the web . xml file. The path of this file is as follows.

C:\Program Files\Apache Software Foundation\Tomcat6.0\webapps\MyApp\WEB-INF

4. Add the following statements in the section which defines the servlets.

<servlet>

     <servlet-name>Sample</servlet-name>

    <servlet-class>Sample</servlet-class>

</servlet>

Also, add the following statements in the section which defines the servlets mappings.

<servlet-mapping>

     <servlet-name>Sample</servlet-name>

     <url-pattem>/servlet/Sample</url-pattem>

</servlet-mapping>

5. Start the Tomcat. To start the Tomcat, click the Start menu, point to All Programs, point to Apache Tomcat 6.0 and then click Configure Tomcat. This displays the Apache Tomcat Properties. Click the Start button.

6. Start a web browser and request for the servlet. Note that the HTML code can be included in the servlet code or a separate HTML file can be used. If the HTML code is included in the servlet code, enter the following URL in the address bar.

https://ecomputernotes.com:8080/MyApp/servlet/Sample

or

http:/1127.0.0.1:8080/MyApp/servlet/Sample

If separate HTML file is used for the HTML code, enter the following URL in the address bar.

https://ecomputernotes.com:8080/MyApp/Sample.html

or

http:/1127.0.0.1:8080/MyApp/Sample.html

Here, 127 . 0 . 0 . 1 : 8O80 is an IP address of the local system. Note that the . html file must be saved in the MyAppdirectory.

The output of the servlet will be displayed in the display area of browser.

Advantages of Servlets

By Dinesh Thakur

Internet and WWW are often used interchangeably but both are different. Internet is the global network of computer networks whereas Web is one of the services provided over Internet. That is, Web is an application running over Internet. While creating web applications, the main goal is to perform most of the processing on the browser side, there by, reducing processing load on the server side.

 

However, sometimes it is not possible to eliminate all processing at the server side. For example, in situations like online registration, retrieving data from underlying data, etc., some processing might be required at the server side. One of the server side technologies, servlets is used to handle server side processing. Servlets are small programs written in Java, which are loaded and executed by web server as applets are loaded and executed by web browser. Since, servlets are written in Java, they are platform independent and also posses all other advantages of Java.

Advantages of servlets

A servlet can be imagined to be as an applet running on the server side. Some of the other server side technologies available are Common Gateway Interface (CGI), server side JavaScript and Active Server Pages (ASP). Advantages of servlets over these server side technologies are as follows:

• Persistent: Servlets remain in memory until explicitly destroyed. This helps in serving several incoming requests. Servlets establishes connection only once with the database and can handle several requests on the same database. This reduces the time and resources required to establish connection again and again with the same database. Whereas, CGI programs are removed from the memory once the request is processed and each time a new process is initiated whenever new request arrives.

• Portable: Since servlets are written in Java, they are portable. That is, servlets are compatible with almost all operating systems. The programs written on one operating system can be executed on other operating system.

• Server-independent: Servlets are compatible with any web server available today. Most of the software vendors today support servlets within their web server products. On the other hand, some of the server side technologies like server side JavaSricpt and ASP can run on only selected web servers. The CGI is compatible with the web server that has features to supports it.

• Protocol-independent: Servlets can be created to support any of the protocols like FTP commands, Telnet sessions, NNTP newsgroups, etc. It also provides extended support for the functionality of HTTP protocol.

• Extensible: Servlets being written in Java, can be extended and polymorphed into the objects that suits the user requirement.

• Secure: Since servlets are server side programs and can be invoked by web server only, they inherit all the security measures taken by the web server. They are also safe from the problems related to memory management as Java does not support the concept of pointers and perform garbage collection automatically.

• Fast: Since servlets are compiled into bytecodes, they can execute more quickly as compared to other scripting languages. The bytecode compilation feature helps servlets to give much better performance. In addition, it also provides advantage of strong error and type checking.

Jsp To Servlet Communication

By Dinesh Thakur

JSP is a tag-based language, i.e., code is written within specified tags. It is developed by Sun Microsystems. Unlike servlet program, we can write HTML tags within the JSP program, making it easier to build.

When a servlet JSP communication is taking place, it is not just about forwarding the request to a JSP from a servlet. There might be a need to transfer a string value or an object itself.

In the JSP program we use simple HTML tags to take input from the client but we will save the file as a .jsp extension and then we will retrieve the data in the servlet program.

                 

Login.html

<center>

<form action=”login” method=”get” >

USERNAME <input type=’text’ name=’t1′><br>

PASSWORD <input type=’text’ name=’t2′><br>

<input type=”submit” value=”login” >

<input type=”reset” value=”reset” >

</form>

</center>

Login·java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class Login extends HttpServlet

{

           public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException

       {

               res.setContentType(“text/html”);          

               String usname=req.getParameter(“t1”);

               String pass=req.getParameter(“t2”);

               PrintWriter pw=res.getWriter();

               pw.println(“USERNAME IS : “+usname);

               pw. println (” PASSWORD IS : “+pass) ;

               pw.close();

        }

}

To test the application

https://ecomputernotes.com:portno/login.jsp

Servlet to Database Communication

By Dinesh Thakur

Accessing data in a database or in any other data sources is a significant operation in web programming. Data access from JSPs and servlets is done through Java Database Connectivity (JDBC). [Read more…] about Servlet to Database Communication

Applet to Servlet Communication

By Dinesh Thakur

HTML exhibits high performance by taking less time to load in the browser. However, when we use HTML page for important user details, by default, all the parameters that are passed appended in the URL. This compromises with the security. On the other hand, applet takes more time to load but there is no problem with Java security. This is an advantage of this technique. [Read more…] about Applet to Servlet Communication

What is the difference between doGet and doPost?

By Dinesh Thakur

In doGet Method the parameters are appended to the URL and sent along with the information. Maximum size of data that can be sent using do Get it 240 bytes. Parameters are not encrypted. doGet method generally is used to query or to get some informationfromthe server.

doGet is faster if we set the response content length since the same connection is used. Thus increasing the performance. doGet should be important. doGet should be able to be repeated safely many times. doGet should be safe without any side effects for which user is held responsible.

doPost

In doPost, parameters are sent in separate line in the body. There is no maximum size for data. Parameters are encrypted. doPost is generally used to update or posts some information to the server. do Post is slower compared to doGet since do Post does not write the content length.

This method does not need to be important Operations requested through POST can have side effects for which the user can be held accountable, for example, updating stored data  or buying items online.

What is HttpServlet and it’s Methods?

By Dinesh Thakur

HttpServlet is an abstract class given under the servlet-api present. It is present in javax.servlet.http package and has no abstract methods. It extends GenericServlet class.

When the servlet container uses HTTP protocol to send request, then it creates HttpServletRequest and HttpServletResponse objects. HttpServletRequest binds the request information like header and request methods and HttpServletResponse binds all information of HTTP protocol.

HttpServlet does not override in it or destroy method. However, it uses service (-,-) method. ServletRequest and ServletResponse references are cast into HttpServletRequest and HttpServletResponse, respectively.

Methods in HttpServlet

The methods in httpservlet are given as follows:

i. protected void doDelete (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a DELETE request. The DELETE operation allows a client to remove a document or web page from the server.

ii. protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method)”to allow a servlet to handle a GET request. Overriding this method to support a GETrequest also automatically supports an HTTP HEAD request.

iii. protected void doHead(HttpServletRequest req,HttpServletResponse resp)

throws ServletException, IOException

Receives an HTTP HEAD request from the protected service method and handles the request.

iv. protected void doOptions(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle OPTIONS request. The OPTIONS request determines which HTTP methods the server supports and returns an appropriate header.

v. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a POST request. The HTTP POST method allows the client to send data of unlimited length to the Web server a single time and is useful when posting information such as credit card numbers.

vi. protected void doPut(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a PUT request. The PUT operation allows a client to place a file on the server and is similar to sending a file by FTP.

vii.· protected void doTrace(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException

Called by the server (via the service method) to allow a servlet to handle a TRACE request. ATRACE returns the headers sent with the TRACE request to the client, so that they can be used in debugging. There’s no need to override this method.

viii. protected long getLastModified(HttpServletRequest req)

Returns the time the HttpServletRequest object was last modified, in milliseconds since midnight 1January 1970GMT.If the time is unknown, this method returns a negative number (the default).

ix. protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class. This method is an HTTP· specific version of the service method. There’s no need to override this method.

x. public void service (ServletRequest req/ ServletRespon,se res) throws ServletException, IOException

Dispatches client request to the protected service method. There’s no need to override this method.

What is Http Header?

By Dinesh Thakur

HTTP headers are the request to a server for information and the resulting response. When you input an address into your browser, it sends a request to the server hosting the domain and the server responds. You can see the request and response using the basic HTTP Header Viewer. The HTTP Header Viewer can be used to view the Headers or Headers and Content of any valid http:/ / url. When the HEAD is selected, the request is for the server to only send header information. A GET selection requests both headers and file content just like a browser request. Information in response headers may include: [Read more…] about What is Http Header?

Describing ServletRequest and ServletResponse.

By Dinesh Thakur

The ServletRequest is a predefined interface present in javax.serviet package. The object of ServletRequest interface deals with the client request and fetches it to the servlet program. This object is created by the servlet container and is used as the argument of service method (life cycle method).

This interface is also used by javax.http package.

Methods in ServlelRequest

(i) public Object getAttribute(String name)

Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.

 

(ii) public Enumeration getAttributeNames()

Returns an Enumeration containing the names of the attributes available to this request.

 

(iii) public String getCharacterEncoding()

Returns the name of the character encoding used in the body of this request.

 

(iv) public intgetContentLength()

Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known. For HTTP Servlets, same as the value of the CGI variable CONTENT_LENGTH.

 

(v) public String getContentType()

Returns the MIME type of the body of the request, or null if the type is not known.

 

(vi) public ServletInputStreamgetInputStream() throws IOException

Retrieves the body of the request as binary data using a ServletInputStream.

 

(vii) public Locale getLocal()

Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.

(viii) public Enumeration getLocales()

 

Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the client based on the Accept-Language header.

(ix) public String getParameter(String name)

Returns the value of a request parameter as a String, or null if the parameter does not exist.

(x) public Map getParameterMap()

Returns a java.uti1.Map of the parameters of this request

 

(xi) public Enumeration getParameterNames()

Returns an Enumeration of String objects containing the names of the parameters contained in this request.

(xii) public String[] getParameterValues(String name)

Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.

(xiii) public String getProtocol()

Returns the name and version of the protocol the request uses in the form protocol/majorVersion.minorVersion, for example, HTTP/1.1 For HTTP servlets, the value returned is the same as the value of the CGI variable SERVER_PROTOCOL.

(xiv) public BufferedReadergetReader() throws IOException

 

Retrieves the body of the request as character data using a BufferedReader.

 

(xv) public String getRemoteAddr()

Returns the Internet Protocol (IP) address of the client that sent the request.

 

(xvi) public String getRemoteHost()

Returns the fully qualified name of the client that sent the request.

 

(xvii) public RequestDispatchergetRequestDispatcher(String path)

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.

 

(xviii) public String getScheme()

Returns the name of the scheme used to make this request, for example, http, https, or ftp.

 

(xix) public String getServerName.()

Returns the host name of the server that received the request.

 

(xx) public intgetServerPort()

Returns the port number on which this request was received.

 

(xxi) public booleanisSecure()

Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.

(xxii) public void removeAttribute(String name)

Removes an attribute from this request. This method is not generally needed as attributes only persist as long as the request is being handled.

 

(xxiii) public void setAttribute(String name,Object 0)

Stores an attribute in this request. Attributes are reset between requests.

 

(xxiv) public void setCharacterEncoding(String env) throws Unsupported EncodingException

Overrides the name of the character encoding used in the body of this request.

ServletResponse

The ServletResponse is a predefined interface present in javax.servlet package. The object of this interface sends response to the client. Its object is created by the servlet container. To send binary data in MIME body response, we have to use ServletOutputStream returned by getOutputStream. To send text data we will use PrintWriter returned by getWriter.

 

Melhods in ServlelResponse

 

(i) public void flushBuffer() throws IOException

 

Forces any content in the buffer to be written to the client.

 

(ii) public intgetBufferSize()

 

Returns the actual buffer size used for the response. lf no buffering is used, this method returns().

 

(iii) public String getCharacterEncoding()

 

Returns the name of the charset used for the MIME body sent in this response. lf no charset has been assigned, it is implicitly set to 150-8859-1 (Latin-1).

 

(iv) public Locale getLocal()

 

Returns the locale assigned to the response.

 

(v) public ServletOutputStreamgetOutputStream() throws IOException

 

Returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data.

 

(vi) public PrintWritergetWriter() throws IOException

 

Returns a PrintWriter object that can send character text to the client.

 

(vii) public booleanisCommitted()

 

Returns a boolean indicating if the response has been committed. A commited response has already had its status code and headers written.

 

(viii) public void reset()

 

Clears any data that exists in the buffer as well as the status code and headers.

(xi) public void resetBuffer()

Clears the content of the underlying buffer in the response without clearing headers or status code.

 

(x) public void setBufferSize(int size)

 

Sets the preferred buffer size for the body of the response.

 

(xi) public void setContentLength(intlen)

 

Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.

 

(xii) public void setContentType(String type)

 

Sets the content type of the response being sent to the client.

 

(xiii) public void setLocaIe(Locale loc)

 

Sets the locale of the response, setting the headers (including the Content-Type’s charset) as appropriate.

Implementing Servlet Object

By Dinesh Thakur

The Servlet object is a Java object that is initiated and managed by the Servlet container. However, the Java object needs to be implemented descriptive to the Servlet container. The following rules are specified by the Java Servlet specification for implementing the Servlet object:

• Should be a public non-abstract class.

• Should be a subtype of the javax.servlet.Servlet interface, as the Servlet container understands the Servlet object by using this interface.

• Should support a no-argument constructor.

• Recommended not to declare the methods of the javax.servlet.Servlet interface implemented by the Servlet object as final.

As we understood the rules for implementing servlet object, let us learn about the  javax.servlet.Servlet andjavax.servlet.ServletConfig interfaces,which arethe basic and important elements of Java Servlet API to understand the Servlet life cycle.

 

ServletConfig OBJECT

 

• It is one per Servlet Class Object so it is called right hand object of the servlet class object.

 

• ServletContainer creates this object along with our servlet class object and also destroys this object along with our Servlet class object.

 

• This is the object of underlying Servlet Container Supplied java class that implements javax.servlet.ServletConf ig interface.

 

• This object is useful to gather details about Servlet program and to pass information to servlet program.

 

• This object is useful to gather unit parameter values from web.xml file.

 

• This object is required to get access to ServletContext object.

 

ServletContext Object

 

• It is one per web application and visible to all web resource programs of the web application, it is called global memory of the web application.

 

• Servlet Container creates this object either during server startup (cold deployment) or during deployment of the web application (hot deployment) using this object.

 

(a) We can get underlying server info.

 

(b) We can get details of the web resource program of the web.

 

(c) We can get servlet API version that server uses.

 

(d) We can get streams pointing to the resource program of the web application.

 

(e) We can write message to long files.

 

•Different ways of access to ServletConfig obj.in our Servlet program.

Explain Server Side Programming

By Dinesh Thakur

All of us would have started programming in java with the famous “hello world” program. If you can recollect, we saved the file with a ‘.java’ extension and later compiled the program using ‘javac’ and then executed the program using ‘java’. Apart from introducing you to the language basics, the important point is that it is a client-side program. That means you write, compile and execute the program in the client machine (i.e., your PC). No doubt, it is the easiest and fastest way to write, compile and execute the program. However, it has little practical significance when it comes to real-world programming.

Why Server Side Programming

Though it is technically feasible to implement almost any business logic using client-side programs, logically or functionally it server no purpose when it comes to enterprises application (e.g., banking, air ticketing, e-shopping, etc). To further explain, going by the client-side programming logic; a bank having 10,000customers would mean that each customer would have a copy of the program(s) in his or her PC (and now even mobiles) which translates to 10,000 programs! In addition, there are issues like security, resource pooling, concurrent access and manipulations to the database which simply cannot be handled by client-side programs. The answer to most of the issues cited above is-“Server Side Programming”. Figure illustrates the Server Side Architecture in the simplest way.

                     Server Side Programming Architecture

Advantages of Server Side Programs

Some of the advantages of Server Side programs are as follows:

1. All programs reside in one machine called server. Any number of remote machines (called clients) can access the server programs.

ii. New functionalities to existing programs can be added at the server side which the clients can take advantage of without having to change anything.

iii. Migrating to newer versions, architectures, design patterns, adding patches, switching to new databases can be done at the server side without having to bother about client’s hardware or software capabilities.

iv. Issues relating to enterprise applications like resource management, concurrency, session management, security and performance are managed by the server side applications.

v. They are portable and possess the capability to generate dynamic and user-based content (e.g., displaying transaction information of credit card or debit card depending on user’s choice).

Types of Server Side Programs

The following are the different types of server side programs:

(a) Active Server Pages (ASP)

(b) Java Servlets

(c) Java Server Pages (JSP)

(d) Enterprise JavaBeans (EJB)

(e)PHP

To summarize, the objectives of server side programs are to centrally manage all programs relating to a particular application (e.g., banking, insurance, e-shopping, etc). Clients with bare minimum requirements (e.g., Pentium II, Windows XP professional, MS Internet Explorer and an internet connection) can experience the power and performance of a server (e.g., IBM Mainframe, Unix Server, etc.) from a remote location without having to compromise on security or speed. More importantly server programs are not only portable but also possess the capability to generate dynamic responses based on user’s request.

Terminology in Web Application

By Dinesh Thakur

Important terms used in web application are discussed here.

Common Gateway Interface (CGI)

The Common Gateway Interface (CGI) is one of the practical techniques developed for creating dynamic content. By using the CGI, web server passes request to an external program and after executing the program the content is sent to the client as an output. In CGI, when the server receives a request, it creates a new process to run the CGI program; so creating a process for each request requires significant server resources and time, which limits the number the of requests that can be processed concurrently. CGI applications are platform dependent. There is no doubt that CGI has played a major role in explosion of internet and its performance and scalability issues make it optimal solution.

Java Servlets

Java Servlet is a generic server extension that means a Java class can be loaded dynamically to expand the functionality of the server. Servlets are used with web servers and run inside the Java Virtual Machine (JVM) on the server so it is safe and portable. Unlike applets they do not need support from Java in the browsers. In contrast to CGI, servlets do not use multiple processes to handle separate requests. Servlets can be handled by separate threads in the same process. Servlets are portable and platform independent.

Web Server

A web server extension is the combination of computer and the program installed on it. The web server interacts with the client through a web browser. It delivers the web pages to the client and to an application by using web browser and the Hypertext Transfer Protocol (HTTP) protocols respectively. We can also define the web browser as the package of large number of programs installed on the computer connected to internet or intranet for downloading the requested files using File Transfer Protocol (FTP), serving email and building and publishing web pages. A computer connected to internet or intranet must have a server program. In Java language, a web server is a server that is used to support the web component like servlet and Java server page (JSP).

A computer connected to the internet for providing services to a small company or a departmental store may contain the HTTP server (to access and store the web pages and file), Simple Mail Transfer Protocol (SMTP) server (to support mail services), FTP server (for file downloading) and Network News Transfer Protocol (NNTP) server (for newsgroup). The computer containing all of these servers is called web server. Internet service providers and large companies may have all these servers and many more on separate machines. In case of Java, a web server can be defined as a server that only supports the web components like servlet and JSP. It does not support the business component like EJB.

Application Server

An application server is a software framework dedicated to the efficient execution of procedures (programs, routines, scripts, etc.) for supporting the construction of applications. Normally, the term refers to Java application servers. When this is the case, the application server behaves like an extended virtual machine for the running applications, handling transparently connections to the database at one side, and connecting to the web client at the other end.

An application server is typically used for complex transaction-based applications. To support high-end needs, an application server has to have built-in redundancy, monitor for high-availability, high-performance distributed application services and support for complex database access.

Servlet Container

A servlet container is nothing but a compiled, executable program. The main function

of the container is to load, initialize and execute servlets. The servlet container is the official Reference Implementation for the Java Servlet and Java server pages technologies. The Java servlets and Java server pages specifications are developed by Sun Microsystems under the Java Community Process (JCP).

A container handles large number of requests as it can hold many active servlets, listeners, etc. It is interesting to note that the container and objects in a container are multithreaded. So each object must be thread safe in a container as the multiple requests are handled by the container due to entrance of more than one thread at a time.

We can categorize the servlet container as:

(a)A simple servlet container is not fully functional; therefore, it can run very simple servlets and do the following:

• Wait for HTTP request.

• Construct ServletRequest object and ServletResponse object.

• If the request is for static method, invoke the process method of StaticResourceProccesor instance, passing ServletRequest object and ServletResponse object.

• If the request is for servlet, load the servlet class and invoke the service method passing ServletRequest object and ServletResponse object. Note that in this servlet container, the servlet class is loaded every time the servlet is requested.

(b)A fully functional servlet container additionally does the following for each HTTP request:

• When the servlet is called for the first time, load the servlet class and its init method (once only).

• For each request, construct an instance of javax. servlet. ServletRequest and an instance of javax. servlet. ServletResponse objects.

• Invoke servlet’s service method, passing ServletRequest object and ServletResponse object.

• When the servlet class is shut down, call the servlet’s destroy method and unload the servlet class.

Additional Capabilities of HTTP Servlets

By Dinesh Thakur

Of these, HTTP servlets have some additional objects that provide session-tracking capabilities, the servlet writer can use the HttpSession interface to maintain the state of a client between client requests upto some time period. The capability of maintaining cookies is also provided by the HTTP servlets, The servlet writer uses the Cookie class to save small bits of information within the client machine, which can be retrieved at request processing time, Program illustrates the use of the HttpServlets.

public class Servlet_A extends HttpServlet

{

                  public void doGet (HttpServletRequest request, HttpServletResponse response)

                  throws ServletException, IOException

               {

                          PrintWriter pout;

                        String title = “Http Servlet Example”;

                     // set content type and other response header fields first

                        response,setContent Type(“text/html”);

                       // then write the data of the response

                       pout = response,getWriter();

                       pout,println (“<html ><head><title> “);

                       pout,println(title);

                       pout,printl n(“</title></head><body>”);

                       pout,println(“<h1 >” + title + “</h1 >”);

                       pout,println(“<P>This is output from Servlet_A”);

                       for(int i=0;i<=5;1++)

                              pout,print(i+” “);

                              pout.println (“</body></html>”);

                              pout.c1ose();

                }

}

Servlet_A extends the HttpServlet class which, in turn, implements the Servlet interface. Here the title of the tag is displayed as the name of the browser window. Servlet_A overrides the doGet method in the HttpServlet class. The doGet method is called when a client makes a GET request (which is the default HTTP request method), and this results in the simple HTML page being returned to the client.

If a request is made to HttpServlet then the container delegates the request to the public service method within the servlet. This method will cast the ServletRequest, ServletResponse object to their corresponding HttpServletRequest and HttpServletResponse. Then this method will delegate the call to the protected service method. In the protected service method we call the method getMethod() on the request object, which will return the string specifying the type request. If the request is get then the doGet() method is called. In case the request is post then the doPost() method is called.

Objects of the HttpServletRequest class

Within the doGet method, the user’s request is represented by an HttpServletRequest object. An HttpServletResponse object represents the response to the user. Because text data is returned to the client, the reply is sent using the Writer object obtained from the HttpServletResponse object.

Objects of the HttpServlet Response class

An object of the class HttpServletResponse provides two ways of returning data to the user:

• The getWriter() method which returns a PrintWriter object.

• The getOutputStream() method which returns a ServletOutputStream object.

One way of handling this is to use the getWriter method to return text data to the user and the getOutputStream method for binary data. Closing the Writer or ServletOutputStream after the response is sent allows the server to know when the response is complete. The HTTP header data must be setbeforeaccessing the Writer or OutputStream. The HttpServletResponse class provides methods to set the header data. For example, the setContent Type() method is used to set the content type (This is the header used most by the developer). So, in general, it is preferable to set the content type before accessing the Writer object.

Examples of GET and POST Requests

To handle HTTP requests in a servlet, extend the Http5ervlet class and override the servlet methods that handle the HTTP requests made by the clients. Programs illustrate how to handle GET and POST requests. The methods that handle these requests are doGet and do Post.

HandlingGETrequestsHandling GET requests involves overriding the doGet method. Program illustrates the use of the GET request. The Get method, in general, sends requests to the servlet without passing any parameters. It is also possible to pass the parameter to the get method.

Program Using theGETrequest. 
import javax.servlet.*;
import javax.servlet.http*;
import java.util.*;
import java.io.*;
public class ServlecGet extends HttpServlet
{
             public void init(ServletConfig config) throws ServletException
            {
                    super.init(config);
             }
             public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException
            {
                    response.setContent Type("text/html");
                    PrintWriter pout = response.getWriter();
                    pout.println("<html><head><title> Receipt </title>" );
                    String date = new Date().toString();
                    pout.println("<h3> To day's date is:"+date);
                    pout.println ("</h3></head></html>");
                    pout.close();
            }
            public void destroy( )
           {
                    // destroyall resource if any connected to the servlet
           }
}

The Servlet_Get class extends the HttpServlet class and overrides the doGet method. To respond to the client, the doGet method in Programuses a Writer from the HttpServletResponse object to return text data to the client. Before accessing the writer, the content-type header is set in this program. At the end of the doGet method, after the response has been sent, the Writer is closed.

Handling POSTrequestsHandling POST requests involves overriding the doPost method. Programillustrates the means of overriding the doPost method. The Post method is used when information is passed to the servlet. If the doPost() method is overridden then the information has to be passed to the servlet.

Program UsingPOSTrequests

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class Servlet_Post extends HttpServlet
{
            public void init(ServletConfig config) throws ServletException
           {
                    super.init( config);
            }
            public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException. IOException
           {
                           response.setContent Type("text/html");
                           PrintWriter pout = response.getWriter();
                           pout.println("<html><head><title> Receipt </title>" );
                           String date = new Date().toString();
                           pout.println("<h3>" +date);
                           pout.println ("</h3></head></html>");
                           pout.c1ose();
            }
                      public void destroy( )
                 {
                                 // destroy allresource if any connected to the servlet
                  }
  }

Html to Servlet Communication

By Dinesh Thakur

A web resource application is a combination of static as well as dynamic web resource programs, images, etc. A static web resource resides in server and is executed in client side web browser, e.g., HTML. A dynamic web resource program resides in server, is executed in context of server and gives response back to the client, e.g., servlet, JSP. In web application, static web resource takes data from client side and takes it to the dynamic web resource as per request. The dynamic web resource processes the data and sends the response back to client in the form of response. [Read more…] about Html to Servlet Communication

What happens when our servlet program gets first or Other than First Request from browser window?

By Dinesh Thakur

1. Servlet container loads our servlet class from WEB-INF\classes folder of deployed web application.

2. Servlet container instantiates (object creation) our servlet class object as Class.forName (“FolderName”).newInstance (); 

             Class.forName (“FolderName”)      // loads our servlet class   

             newInstance ()       // creates object for the loaded class DateSrv    

3. During instantiation process the 0-param constructor of our servlet class executes.

4. Servlet container creates one servlet config object for our servlet class object.

5. Servlet container calls init (-) life cycle method having servlet config object as argument value on our servlet class object.               

Note: 1 to 5 steps completes instantiation and initialization on our servlet class object.

6. Servlet container calls next life cycle method service (-,-) on our servlet class object. This will process the request and generated response goes to browser window as web page through web server.

Other than First Request

 Servlet container checks the availability of our servlet class object.

1. If available, servlet container calls service (-,-) (public) on existing object of our servlet class to process the request and this response goes to browser window.

2. If not available, servlet container performs all operations of first request.

What is the Servlet container raises the life cycle events in servlet program?

By Dinesh Thakur

* Every software and non-software objects life cycle (considering all the operations that are taken place from object birth to object death)

* Our servlet class object life cycle will be managed by servlet container

* Event is an action performed/raised on the object  

                                                                                                                                     

  • Servlet container raises the following life cycle events in the life cycle of our servlet program. They are:
  1. Instantiation Event (raises when servlet container creates our servlet class object)
  2. RequestArrival Event (raises when servlet container takes the browser window generated request)
  3. Destruction Event (raises when servlet container is about to destroy our servlet class object)

When container raises these events on our servlet class object it looks to call certain methods automatically so these methods are called as life cycle methods or container callback methods. They are:

init (ServletConfig cg)

Service (ServletRequest req, ServletResponse res)

Destroy ()

Prototype of servlet life cycle methods

Public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException

Public void init (ServletConfig cg) throws ServletException

Public void destroy ()

* For one life cycle event only one life cycle method will be called by servlet container so init (), service (HttpServletRequest, HttpServletResponse), doXxx () methods are not life cycle methods.

* Servlet container calls init (-) life cycle method for instantiation event.                               

* Servlet container calls service (-,-) life cycle method for RequestArrival event.

* Servlet container calls destroy () life cycle method for destruction event

* The method that is called by underlying container automatically based on the event that is raised on the object is called container callback methods.

* Programmer never calls life cycle methods manually; they will be called by underlying container automatically.

* Servlet API as supplied life cycle methods:

  1. To allow programmer to place his choice logics in the execution of servlet programs.
  2. To supply servlet container created objects to servlet program (also for programmers as parameters of life cycle methods) (like request object, response object, ServletConfig object and etc)

* While overriding super class method in subclass, the method can have same modifier or access modifier

* While overriding protected service () method of predefined HttpServlet class in its subclass we can take either protected or public modifiers for that method.

Public class TestSrc extends HttpServlet

{

      Public void service (here protected method is overridden) (HttpServletRequest,   HttpServletResponse) throws ServletException, IOException

    {

        _______

        _______

        ­­­­_______

    }

}

Service () method-1

Public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException

Service () method-2

Protected void service (HttpServletRequest,   HttpServletResponse) throws ServletException, IOException

* Servlet container is responsible to raise various life cycle events on our servlet class objects so logics placed in life cycle methods are not responsible to raise these events but they are responsible to process these events by executing programmers supplied logic.

Example:- Code which is written in init () life cycle method never creates our servlet class object but programmer places this code as instantiation logic to execute for instantiation event raised by servlet container by creating our servlet class object.

* Life cycle method and its logic are not capable of raising life cycle events on the object but when underlying container raises life cycle events on the objects it automatically calls a relevant life cycle methods.

Response Status Code in Servlet.

By Dinesh Thakur

* Response status code indicates the status of generated response to display on the browser window.

* Every generated http response contains one http status code, default status code is 200.

* If web resource program generates warnings based web page then the status code is 100-199.   

* If web resource program generates successful web page then the status code is 200-299.

* If request given to one web site is forwarded to another web site then the status code will be 300-399.

* If our web resource program is incomplete or invalid to process the request then the status code will be 400-499.

* If server fails to execute our web application the status code will be 500-599.     

* 400-599 are error status codes, Using them the programmer can debug the problems related       to web application execution and server.

* 100-399 indicates success response status codes that means they display web pages on browser window having output content. So these status codes will not appear on the web pages.

* For related information on http response status codes refer page no 49 and 50.      

* Response headers provide instructions to browser window through web server towards displaying web pages on the browser window.

* The content type we have placed in PW.println statements becomes response body http response.

How many ways we can develop a servlet?

By Dinesh Thakur

The three important resources of servlet API.

1. javax.servlet.Servlet

2. javax.servlet.GenericServlet      (Abstract class)

3. javax.servlet.http.httpServlet    (Abstract class)

• In Java an abstract class can contain only abstract methods or only concrete methods or mix of both.

• The above give predefined HttpServlet class is an abstract class containing no abstract methods.

• If you want to make methods / logics of one java class accessible only through subclass the make that class as abstract class even though that class contains only concrete methods.

              servlet method inheritance

• Every servlet program is a java class that is developed based on servlet api. There are three ways to develop servlet program.

1. Take a java class implementing javax.servlet.Servlet interface and provide implementation for all the five methods of that interface.

2. Take java class extending from javax.servlet.GenericServlet class and provide implementation for service() method.

3. Take java class extending from javax.servlet.http.httpServlet class and override one of the seven doxxx() methods or one of the two service(- -) methods.

• In the above said three approaches the overridden / implemented service (-,-) / doxxx(-) programmer places request processing logic that generates web pages by processing the request. But programmer never calls these methods manually but servlet container calls these methods automatically for every request given by client to servlet program.

• Programmer just supplies his servlet program related java class to servlet container then onwards servlet container is responsible to manage the whole life cycle of servlet program. (From object birth to death every operation will be take care by container).

• For all the request given to servlet program the servlet container creates one object but for every request given to servlet program, the servlet container create one separate request, response objects and calls service(-,-) method by keeping these requests, response objects as argument values.

                Servlet Object

• Servlet program uses request object to read details from the request.

• Servlet program uses response object to send response content to browser window through web server.

• When 10 requests are given to a servlet program from single or different browser windows (clients)

• Servlet container creates 10 threads on servlet program objects representing 10 requests.

• Servlet container creates 10 sets of request, response objects and calls service (-,-) or methods for 10 times having request, response objects as arguments values.

• To make our servlet program java class visible to servlet container the java class must be taken as public class.

 

The javax.servlet.Servlet Interface

 

The javax.servlet.Servlet interface is the basic interface of the Java Servlet API. This provides a standard abstraction for the servlet container to understand the Servlet object created by the user. That means the interface is designed to describe the user-defined Java object to the Servlet container, which encapsulates the application logic to plug into the servlet container for processing the client request. The servlet object must be a subtype of the interface to be managed by the servlet container. The following are the five methods declared in this interface:

 

1. public abstract void init(ServletConfig)

 

2. public abstract void service (Service Request, Service Response) throws servlet Exception, IO Exception

 

3. public abstract void destroy()

 

4. public abstract void ServletConfiggetServletConfig()

 

5. public abstract String getServletlnfo()

 

The javax.servlet.GenericServlet Class

 

The GenericServlet class implements the servlet interface and, for convenience, the ServletConfig interface. Servlet develops typically subclass GenericServlet, or its descendent HttpServlet, unless the servlet needs another class as a parent. (If a servlet does need to subclass another class, the servlet must implement the Servlet interface directly. This would be necessary when, for example, RMI or CORBA objects act as servlets.)

 

The GenericServlet class was created to make writing servlets easier. It provides simple versions of the life-cycle and ini t destroy methods, and of the methods in the ServletConfig interface. It also provides a log method, from the ServletContext interface. The servlet writer must override only the service method, which is abstract. Though not required, the servlet implementer should also override the getServletInfo method, and will want to specialize the ini t and destroy methods if expensive servlet-wide resources are to be managed. The following are the methods residing in GenericServlet class.

 

• public void destroy()

 

• public String getlnitParameter(String name)

 

• public Enumeration getlnitParameterNames()

 

• public ServletConfiggetServletConfig()

 

• public ServletContextgetServletContext()

 

• public String getServletlnfo()

 

• public void init(ServletConfigconfig) throws ServletException

 

• public void init() throws ServletException

 

• public void log (Exception e,Stringmsg)

 

• public void log (String message,Throwable t)

 

• public abstract· void service (ServletRequest req, ServletResponse res)

 

throw Servlet Exception, IOException

 

The javax.servlet.http.HttpServlet Class

 

It is an abstract class that simplifies writing HTTP servlets. It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. Because it is an abstract class, servlet writers must subclass it and override at least one method. The methods normally overridden are;

 

• doGet, if HTTP GET requests are supported. Overriding the doGet method automatically also provides support for the HEAD and conditional GET operations. Where practical, the getLastModified method should also be overridden, to facilitate caching the HTTP response data. This improves performance by enabling smarter conditional GET support.

 

• doPost, if HTTP POST requests are supported.

 

• doPut, if HTTP PUT requests are supported.

 

• doDelete, if HTTP DELETE requests are supported.

 

• life cycle methods-in it and destroy, if the servlet writer needs to manage resources that are held for the lifetime of the servlet. Servlets that do not manage resources do not need to specialize these methods.

 

• getServletInfo, To provide descriptive information through a service’s administrative interfaces.

 

Notice that the service method is not typically overridden. The service method, as provided, supports standard HTTP requests by dispatching them to appropriate methods, such as the methods listed above that have the prefix “do”, In addition, the service method also supports the HTTP1.l protocol’s TRACE and OPTIONS methods by dispatching to the doTrace and doOptions methods. The doTrace and doOptions methods are not typically overridden.

 

Servlets typically run inside multi-threaded servers; servlets must be written to handle multiple service requests simultaneously. It is the servlet writer’s responsibility to synchronize access to any shared resources. Such resources include in-memory data such as instance or class variables of the servlet, as well as external components such as files, database and network connections.

Difference between Process and Thread Based Server Side Technology

By Dinesh Thakur

Process based Server Side Technology

• The procedure of transferring control from one process to another process or from one thread to another thread is called as the scheduling based control jumping or context switching.

• Since operating system process are heavy weight process so they take lot of time for control jumping or context switching.

• Due to this when more requests are given CGI based web application more operating system processes will be created on one per request basis and performance of website will be degraded (That means web application becomes non scalable web application).

• If application is giving same performance irrespective of increase or decrease in number of clients / no. of requests is called as scalable application.

           Process based Server Side Technology

Thread based Server Side Technology

Operating System managed process P1 representing the web server startup t1,t2,t3,t4 core threads started on servlet program related object representing request given by clients.

           Thread based Server Side Technology

• The control jumping between threads of a process takes very much less time when compare to control jumping between to separate processes, so we can say thread based server side technology gives better performance when compare to process based server side technologies.

• The web application that is developed based on thread based server side technologies is scalable application.

• servlet program is a single instance multiple threads based java component of java web application as shown above, that means if 100 request are give to single servlet program then the servlet container create only one object for that servlet program class but starts 100 threads on that object representing 100 request as shown above.

Configuration of Tomcat

By Dinesh Thakur

Apache Tomcat is a Open source java based web server software. At present tomcat 7.0 is compatible with jdk1.6/1.7. Tomcat default port no is 8080(changeable).To download tomcat we use www.apache.org.

To install tomcat 6.0 software use apache/ tomat6.0.26 setup file and use can change the default port no, default username and password details during installation. If not changed default port no is “8080”, default username is “admin” default password is “admin”.

Every software installed in a computer will reside in a logical position called software port and every software port will be identified with its port no(communication end point).

After installing tomcat you will get the following folders and files in the installing folder.

                      tomcat directory structure

• To installation folder of tomcat is called as <tomcat_home>

• To start tomcat server use<tomcat_home>/bin/tomcat6.exe file

• To launch home page of tomcat the procedure is

• Open browser windows the type https://ecomputernotes.com:8080 in address bar.

Procedure to change port no. of tomcat server after installation:

• Goto <tomcat_home>/conf/server.xml file modify port attribute value of first <connector> tag then restart the server.

• The browser window keeps every web page in the buffer before display it for end user.

• A buffer is a temporary memory which can hold the data for temporary period.

• While giving new port no to any software service use 1025 to 65535 range numbers because 1 to 1024 range numbers are busy for with OS services.

• Programmer can supply java web application to tomcat server either in the form of directory or war file.

• Programmer uses <tomcat_home>/webApps folder to display web applications.

Architecture of Java Based web Server

By Dinesh Thakur

• Once web server is started one daemon process will be started to listen to clients continuously and to trap and take the client generated Http request.

• The process that runs continuously is called as daemon process.

• Every java application contains two default threads.

   1. Main threads

   2. Garbage collector threads (daemon thread).

• JSP container is the enhancement of servlet container and both containers use JRE/JVM supplied by web server.

• Middle ware services are configurable additional services on the application to make applications executing perfectly in all the situations.

• Security middle ware service protects the application from unauthorized and unauthenticated users.

            Architecture of Java Based web Server

• Transaction Management service executes the logics by applying do everything or nothing principle.

• JDBC connection pool supplies set of ready available JDBC Connection objects.

• Logging service keeps track of the application execution process through conformation statements / messages / log messages.

• Middle ware services are not minimum logics of application development. they are additional or optional services to apply on applications.

• A web application can be there with or without middle ware services.

• Web server automatically activates servlet container and JSP container to execute servlet, JSP programs when they are requested by clients.

• The client side web resource programs of web application goes to browser window for execution whereas the server side programs will be executed by using the containers of web server.

• In web application executing environment browser software is called as client software and web server software is called as server software.

Responsibilities of Web Server

By Dinesh Thakur

• Listens to client request continuously (HTTP Request).

• Traps and takes client generated HTTP Request.

• Passes the HTTP request to an appropriate web resource program of web application (deployed web application).

• provides container software to execute server side programs (web resource programs)

• Gathers output generated by web resource programs.

• Passes output of web resource programs to browser window as http response in the form of web page.

• Provide environment to deploy manage and to undeploy the web application.

• Gives middle ware services and etc.

• A container is a software or software application that can manage the whole life cycle (Object birth to death) of given resource.(like java classes).

• A file or program is called as resource of the application.

• Servlet container takes care of servlet program life cycle.

• JSP container takes care of JSP program lifecycle.

• Applet container (applet viewer) takes care of applet program lifecycle.

• Servlet container, JSP containers are part of web server (java based).

• Container is like a aquarium who can take care of the whole life cycle of given resources called fishes.

• Programmer is not responsible to develop containers and web servers but he is responsible to use them to execute web application.

What is the difference between HttpRequestHeaders and Request Parameters?

By Dinesh Thakur

Both are send input values to target web resource program like servlet program along with the request. The difference are

Http Request Headers

Request Parameters

Holds the browser supplied input values.

Holds the visitor (end user) supplied input values. (from data)

Headers names are fixed but the values are browser specified.

Parameters names and values are user-defined.

Mandatory in every request.

Optional.

Headers names are unique.

Duplicate names are allowed.

Example:- User-agent:

                  Accept:

                  and etc.

Example:- sno=101 & sname=thakur

List of http request headers:

Http Header

Header Values

Accept-Encoding

gzip,deflate

Cookie

ISESSIONID=f73d57hfdn98789654ff8

Connection

keep-alive

Host

Localhost:8080

Referrer

http:// Localhost:8080/project/test

User-agent                   

Mozilla/5.0 (Windows NT 6.1; rv:29.0) Gecko/20100101 Firefox/29.0

If-Modified-since        

Date: Fri, 05 Feb 2014 16:11:54 GMT

Authorization

Authorization: Basic PWxhsdGRpnnjpncGVuIHNlc2FtZQ==

Accept-charset and etc…….

Accept-Charset: utf-8

To gather various details from client generate request being from Servlet program we need to use either ServletRequest object (or) httpServletRequest object. Using httpServletRequest object we can gather all the details from request. Using ServletRequest object we can gather only few details that mean we can’t gather details like header values & some miscellaneous info.  

 1. Different approaches of gathering request parameter values being servlet programs:

Use either ServletRequest object/HttpServletRequest object.

Example request url:

 

https://ecomputernotes.com:8080/project/test1?sno=101 & fname=dinesh & lname=thakur

Approach 1:

String s1=req.getParameter(“sno”); //gives 101

String s2=req.getParameter(“fname”); //gives dinesh

String s3=req.getParameter(“lname”); //gives thakur

Note: 1. we must know parameter name in order to get its value.

          2. If parameter contains multiple values then it gives only one value. (1st value)

Approach 2:              

Enumeration e = request.getParameterNames();

while (e.hasMoreElements()

{

String Pname=(String) e.nextElement();

String Pval=req.getParameter (Pname);

PW.println (Pname +”            ” +Pval);             

}

Approach 3:

String S[]= req.getParameterValues (“sname”);     // (holds dinesh, sandeep as element values)                                       

String S1 = req.getParameterValues (“sname”) [0]; //gives dinesh                                          

String S2 = req.getParameterValues (“sname”) [1]; //gives sandeep

Note:-  This is useful for gather the multiple values of each request parameter.


 If you give any request code then you must write in service (-,-)                                           


2. Different approaches of reading request headers values being from Servlet program:

We must use HttpServletRequest object for this

Approach 1:

String S1=req.getHeader (“user-agent”); //gives browser software name    

String S1=req.getHeader (“accept-language”); //gives en-us

Note: Here we must know header name to get its value. 

 

Approach 2:    

    

Enumeration e=req.getHeaderNames();  

while (e.hasMoreElements())                    

{

  String hname= (String) e.nextElement(); //gives each header name

  String hval=req.getHeader(hname); //gives each header value

  PW.println(hname+”               “ +hval);

}

                                               

Gives all the request heard names and values.

Using browser settings we can change certain header values.

Header values will change based on the browser software we use.

*** We can change accept-language value through browser setting.

Servlets Client HTTP Request

By Dinesh Thakur

• The text that allows non-sequential access through hyper link is called as “hyper text”.

• Protocol http defines set of rules that are required to pass hyper text between browser to server and server to browser.

• Http is application level protocol that runs over network level protocol TCP/IP.

• HTTP is a application level protocol that runs over network level protocol called TCP/IP having set of rules to get communication between browser window and web server.
• Application level protocols defines set of rules that are required to get communication between two softwares or software applications.
Ex. HTTP, JDBC:ODBC, JDBC:Oracle, SMTP and etc…
• Network level protocol defines set of rules to get communication between two physical computers of network.
Ex. TCP/IP

• When browser window generates request to web application the request contains multiple details given by browser window. We can remember this details h2p2 details.

Request URL:

https://ecomputernotes.com:2020/project/test1?sno=101 & sname=thakur (query string)

h2p2 details:

 

H

http request method (GET/POST/…..)

H

http request headers (user-agent, accept language,  …..)

P

path of the requested web resource program (project/test1)

P

request parameters (query string) (s no=101 & s name=thakur)

Generating http request with above set details is the responsibility of browser window.

Block diagram of http request:

                 http request

An example of http request:

                 HTTP basic

How Servlet handling multiple post Requests

By Dinesh Thakur

When four requests are given to a Servlet program.

a) The Servlet container creates one object of that Servlet class.

b) Servlet container starts 4 threads on that object representing 4 requests on per request basis.

c) Servlet container creates 4 sets of request, response objects on one set per each request. (if any change is occur recompile, reload.)

                     Multiple Request

Every thread can be identified through its “thread name”. Every object can be identified with its unique number called “Hashcode”. To get the Hashcode of any object call Hashcode() of an that object.

What is Servlet Container?

By Dinesh Thakur

In Java, Servlet container (also known as aWeb container) generates dynamic web pages. So servlet container is the essential part of the web server that interacts with the java servlets. Servlet Container communicates between client Browsers and the servlets.

Servlet Container managing the life cycle of servlet. Servlet container loading the servlets into memory, initializing and invoking servlet methods and to destroy them. There are a lot of Servlet Containers like Jboss, Apache Tomcat, WebLogic etc.

How does this Servlet Container work?

Servlet Container

• A client browser accesses a Web server or HTTP server for a page.

• The Web server redirects the request to the servlet container (Servlets are HTTP listeners that run inside the servlet container).

• The servlet container redirects the request to the appropriate servlet.

• The servlet is dynamically retrieved and loaded into the address space of the container, if it is not in the container.

• The servlet container invokes servlet init () method once when the servlet is loaded first time for initialization.

• The servlet container invokes the service () methods of the servlet to process the HTTP request, i.e., read data in the request and formulate a response. The servlet remains in the container’s address space and can process other HTTP requests.

• Web servlet generates data (HTML page, picture …) return the dynamically generated results to the correct location.

Java Servlet Life Cycle

By Dinesh Thakur

Java Servlet life cycle consists of a series of events that begins when the Servlet container loads Servlet, and ends when the container is closed down Servlet. A servlet container is the part of a web server or an application server that controls a Servlet by managing its life cycle. Basically there are three phases of the life cycle.

First, the Servlet container loading Servlet in the memory, creating a servlet object and initializes it. Second, Servlet object services requests mapped it by the Servlet container. Thirdly Servlet container shuts down Servlet and Java Virtual Machine (JVM), which is the environment that runs Java applications, freeing the computer resources that the Servlet.

Three of the five methods defined by the Servlet interface — init (), service () and destroy () —‘s life cycle methods.

The init() method:

The Servlet container running a Servlet’s init () method, which initializes Servlet, once in the Servlet life cycle, after loading the Servlet and create a Servlet object. The init method definition looks like this:

public void init(ServletConfig config) throws ServletException {
  // Initialization code...
}

 

 

 

 

 

 

When instantiating the servlet container passes an argument to the init() method a ServletConfig object for loading specific configuration settings to the servlet.

If an error occurs upon calling the init () method, it throws an exception of type and ServletException servlet is not initialized.

The service () method

The container runs the Servlet service () method for each request from a client, a web browser. The service method definition looks like this:

public void service(ServletRequest request, 
                    ServletResponse response)
      throws ServletException, IOException{
}

 

 

 

 

 

 

 

 

The ServletRequest and ServletResponse objects are automatically passed as a parameter to the service () method by the container.

The destroy () method

The Servlet container running a servlet’s destroy () method once in a lifetime to close the Servlet. The destroy method definition looks like this:

public void destroy() { 
    // Finalization code...
  }

 

 

 

 

 

 

 

The destroy ( ) method waits until all threads started by the service () method before terminating the execution of the servlet.

Note– The init() and destroy() method only once called during its servlet life cycle.

Architecture Diagram of Servlet Life Cycle:

                     Architecture Diagram of Servlet Life Cycle

 

The servlet is loaded at server startup or when the first request. The servlet is instantiated by the server. The init ( ) method is invoked by the container. In the first application, the container creates specific Request and Response objects to the query.

The service () method is called for each request in a new thread. The Request and Response objects are passed as parameters. Through the Request object, the service () method will be able to analyze information from the client With the Response object, the service () method will provide a response to the client.

This method can be executed by multiple threads; there should be exclusion for the use of certain resources processes.

The destroy () method is called when unloading the servlet, that is to say when it is no longer required by the server. The servlet is then reported to the garbage collector.

Types of Servlets

By Dinesh Thakur

There is a possibility of developing ‘n’ types of servlets, like httpservlet, ftpservlet, smtpservlet etc. for all these protocol specific servlet classes GenericServlet is the common super class containing common properties and logics. So, GenericServlet is not a separate type of servlet.

As of now Servlet API is giving only one subclass to GenericServlet i.e HttpServlet class because all web servers are designed based on the protocol http.

                               Type of Servlet
Generic servlets extend javax.servlet.GenericServlet – It is protocol independent servlet. Generic Servlet is a base class servlet from which all other Servlets are derived. Generic Servlet supports for HTTP, FTP and SMTP protocols. It implements the Servlet and ServletConfig interface. It has only init() and destroy() method of ServletConfig interface in its life cycle. It also implements the log method of ServletContext interface.

HTTP servlets extend javax.servlet.HttpServlet – HTTPServlet is HTTP dependent servlet. The HTTP protocol is a set of rules that allows Web browsers and servers to communicate.  When Web browsers and servers support the HTTP protocol, Java-based web applications are dependent on HTTP Servlets.HttpServlet is Extended by Generic Servlet. It provides an abstract class for the developers for extend to create there own HTTP specific servlets.

Server side Web Technology

By Dinesh Thakur

Server side web technology is used to develop dynamic web resource programs that having the capability to generate dynamic web pages. Server side web technologies are two types.

1. Process based                

2. Thread based   

Process based Technologies are CGI and thread based technologies are Servlet, JSP, ASP.net.

A light weight sub process is called Thread. Operating system controls processes but threads can be controlled through java programming using JRE support.

Transferring control between two processes (or) between two threads is called as “Context switch” (or) “Control jumping” (or) “scheduling”. The scheduling on processes takes more time compare to the scheduling on threads.

Understanding CGI Environment:

Understanding CGI Environment

Since processes based scheduling takes more time, the CGI web applications performance will be degraded when multiple requests are given simultaneously. This makes the CGI web applications as non-scaleable web applications (If application gives good performance respective of increase (or) decrease in request count then that application is called as “Scaleable applications”).

Understanding Servlet/JSP Environment:

Understanding Servlet/JSP Environment

Since, scheduling on threads takes less time the above diagram based web application gives good performance in all situations. This makes web applications as “scaleable applications.” It is recommended to use thread based server side technologies in web application development for better performance.

Every servlet program is a “Single instance multiple threads component” that means when multiple requests are given to servlet program. The servlet container creates only one object for that servlet program class but multiple threads will be started on that object representing multiple request. As shown above diagram.

Servlet vs. other Technologies

By Dinesh Thakur

Client side programs can be written using different client side technologies. These are given to develop client side web resources such as html (Web), JavaScript (Netscape), VBScript (Microsoft), AJAX (asynchronous JavaScript and xml) programming languages.

Server side web resource programs can be written using different server-side web resource technologies, such as.

Technologies

Software license

Based

Servlets

Sun Microsystems (Oracle corp.)

Java

JSP

Sun Microsystems (Oracle corp.)

Java

PHP

Apache Foundation

Non-Java

Cold Fusion

Open Community

Java

ASP (Active Server Page)

Microsoft

Non-Java

ASP.Net             

Microsoft

Non-Java

SSJS (Server Side JavaScript)             

Netscape

Non-Java

The Web /Http server software that helps to deliver web content that can be accessed through the Internet. There are many Web/Http server software’s to serve different forms of data.

Software

Software license

Based

Tomcat

Apache

Java

Resin

Caucho Technology

Java

Jetty

Apache

Java

PWS (Personal web server)

Microsoft

Non-Java

Apache HTTP Server

Apache

Non-Java

IIS (Internet Information server)         

Microsoft

Non-Java

Oracle HTTP Server

Oracle

Non-free proprietary

Application Server that handles all app operations between users. With application Server, you can easily share business logic or database. There are many Application Server software’s to share business logic data. Application Server s/w is enhancement of web server s/w.

Software

Software license

WebLogic

Oracle

WebSphere

IBM

JBoss

Red Hat

GlassFish

Sun Microsystems

JRun

Macromedia

Oracle Application Server 10g

Oracle

Note:  All application server software’s are Java based server software’s.

Database application software used for storing, organizing and managing information, that application software interact with the user, applications, and the database itself to capture and analyze data. The Database software designed to allow the definition, creation, querying, update, and administration of databases. There is much database software such as.

Database

Software license

Oracle

Oracle

MS-Access           

Microsoft

Sybase

Open Community

DB2            

IBM

MySql

Sun Microsystems

SQL Server           

Microsoft

To develop& execute java based web application:

1. Choose any browser Software.

2. Choose one (or) more client side technologies to develop client-side web resource program.

3. Choose any database Software.

4. Choose java based web server/Application server.

5. Choose java based server side technologies. To develop server side web resource programs. (Servlet, JSP programs) 

 Procedure to develop and execute PHP based web application:

1. Choose any browser Software.

2. Choose one (or) more client side technologies to develop client-side web resource program.

3. Choose any database Software.

4. Use Apache web server.

5. Use PHP to develop server-side web resource programs.

Next Page »

Primary Sidebar

Servlet Tutorials

Servlet Tutorials

  • Servlet - Home
  • Servlet - Types
  • Servlet - Advantages
  • Servlet - Container
  • Servlet - API
  • Servlet - Chaining
  • Servlet - Life Cycle
  • Servlet - Developement Way
  • Servlet - Servlet Vs CGI
  • Servlet - Server Side
  • Servlet - HttpServletRequest
  • Servlet - Cookies Advantages
  • Servlet - JDBC Architecture
  • Servlet - HttpServlet
  • Servlet - HttpServletResponse
  • Servlet - Web Technology
  • Servlet - Applet Communication
  • Servlet - Html Communication
  • Servlet - HTTP POST Request
  • Servlet - HTTP GET Request

Other Links

  • Servlet - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2023. All Rights Reserved.