Servlet Tutorial – Java

Filed Under: Java EE

Welcome to Java Servlet Tutorial. In the last article, we learned about Java Web Application and looked into core concepts of Web Applications such as Web Server, Web Client, HTTP and HTML, Web Container and how we can use Servlets and JSPs to create web application. We also created our first Servlet and JSP web application and executed it on tomcat server.

Servlet Tutorial

servlet tutorial, java servlet tutorial, servlets tutorial, java servlet
Servlet tutorial is aimed to provide more details about java servlet, core interfaces in Java Servlet API, Servlet 3.0 annotations, life cycle of Servlet and at the end we will create a simple login servlet example application.

  1. Servlet Tutorial – Overview
  2. Common Gateway Interface (CGI)
  3. CGI vs Servlet
  4. Servlet API Hierarchy
    1. Servlet Interface
    2. ServletConfig Interface
    3. ServletContext interface
    4. ServletRequest interface
    5. ServletResponse interface
    6. RequestDispatcher interface
    7. GenericServlet class
    8. HTTPServlet class
  5. Servlet Attributes
  6. Annotations in Servlet 3
  7. Java Servlet Login Example

  1. Servlet Tutorial – Overview

    Servlet is Java EE server driven technology to create web applications in java. The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our own servlets.

    All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods. When implementing a generic service, we can extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and doPost(), for handling HTTP-specific services.

    Most of the times, web applications are accessed using HTTP protocol and thats why we mostly extend HttpServlet class.

  2. Common Gateway Interface (CGI)

    Before introduction of Java Servlet API, CGI technology was used to create dynamic web applications. CGI technology has many drawbacks such as creating separate process for each request, platform dependent code (C, C++), high memory usage and slow performance.

  3. CGI vs Servlet

    Java Servlet technology was introduced to overcome the shortcomings of CGI technology.

    • Servlets provide better performance that CGI in terms of processing time, memory utilization because servlets uses benefits of multithreading and for each request a new thread is created, that is faster than loading creating new Object for each request with CGI.
    • Servlets and platform and system independent, the web application developed with Servlet can be run on any standard web container such as Tomcat, JBoss, Glassfish servers and on operating systems such as Windows, Linux, Unix, Solaris, Mac etc.
    • Servlets are robust because container takes care of life cycle of servlet and we don’t need to worry about memory leaks, security, garbage collection etc.
    • Servlets are maintainable and learning curve is small because all we need to take care is business logic for our application.
  4. Servlet API Hierarchy

    javax.servlet.Servlet is the base interface of Servlet API. There are some other interfaces and classes that we should be aware of when working with Servlets. Also with Servlet 3.0 specs, servlet API introduced the use of annotations rather than having all the servlet configuration in the deployment descriptor. In this section, we will look into important Servlet API interfaces, classes and annotations that we will use further in developing our application. The below diagram shows servlet API hierarchy.

    Servlet Hierarchy, Servlet Tutorial, Java Servlet Tutorial, Servlet

    1. Servlet Interface

      javax.servlet.Servlet is the base interface of Java Servlet API. Servlet interface declares the life cycle methods of servlet. All the servlet classes are required to implement this interface. The methods declared in this interface are:

      1. public abstract void init(ServletConfig paramServletConfig) throws ServletException – This is the very important method that is invoked by servlet container to initialized the servlet and ServletConfig parameters. The servlet is not ready to process client request until unless init() method is finished executing. This method is called only once in servlet lifecycle and make Servlet class different from normal java objects. We can extend this method in our servlet classes to initialize resources such as DB Connection, Socket connection etc.
      2. public abstract ServletConfig getServletConfig() – This method returns a servlet config object, which contains any initialization parameters and startup configuration for this servlet. We can use this method to get the init parameters of servlet defines in deployment descriptor (web.xml) or through annotation in Servlet 3. We will look into ServletConfig interface later on.
      3. public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException – This method is responsible for processing the client request. Whenever servlet container receives any request, it creates a new thread and execute the service() method by passing request and response as argument. Servlets usually run in multi-threaded environment, so it’s developer responsibility to keep shared resources thread-safe using synchronization.
      4. public abstract String getServletInfo() – This method returns string containing information about the servlet, such as its author, version, and copyright. The string returned should be plain text and can’t have markups.
      5. public abstract void destroy() – This method can be called only once in servlet life cycle and used to close any open resources. This is like finalize method of a java class.
    2. ServletConfig Interface

      javax.servlet.ServletConfig is used to pass configuration information to Servlet. Every servlet has it’s own ServletConfig object and servlet container is responsible for instantiating this object. We can provide servlet init parameters in web.xml file or through use of WebInitParam annotation. We can use getServletConfig() method to get the ServletConfig object of the servlet.

      The important methods of ServletConfig interface are:

      1. public abstract ServletContext getServletContext() – This method returns the ServletContext object for the servlet. We will look into ServletContext interface in next section.
      2. public abstract Enumeration<String> getInitParameterNames() – This method returns the Enumeration<String> of name of init parameters defined for the servlet. If there are no init parameters defined, this method returns empty enumeration.
      3. public abstract String getInitParameter(String paramString) – This method can be used to get the specific init parameter value by name. If parameter is not present with the name, it returns null.
    3. ServletContext interface

      javax.servlet.ServletContext interface provides access to web application variables to the servlet. The ServletContext is unique object and available to all the servlets in the web application. When we want some init parameters to be available to multiple or all of the servlets in the web application, we can use ServletContext object and define parameters in web.xml using <context-param> element. We can get the ServletContext object via the getServletContext() method of ServletConfig. Servlet engines may also provide context objects that are unique to a group of servlets and which is tied to a specific portion of the URL path namespace of the host.

      Some of the important methods of ServletContext are:

      1. public abstract ServletContext getContext(String uripath) – This method returns ServletContext object for a particular uripath or null if not available or not visible to the servlet.
      2. public abstract URL getResource(String path) throws MalformedURLException – This method return URL object allowing access to any content resource requested. We can access items whether they reside on the local file system, a remote file system, a database, or a remote network site without knowing the specific details of how to obtain the resources.
      3. public abstract InputStream getResourceAsStream(String path) – This method returns an input stream to the given resource path or null if not found.
      4. public abstract RequestDispatcher getRequestDispatcher(String urlpath) – This method is mostly used to obtain a reference to another servlet. After obtaining a RequestDispatcher, the servlet programmer forward a request to the target component or include content from it.
      5. public abstract void log(String msg) – This method is used to write given message string to the servlet log file.
      6. public abstract Object getAttribute(String name) – Return the object attribute for the given name. We can get enumeration of all the attributes using public abstract Enumeration<String> getAttributeNames() method.
      7. public abstract void setAttribute(String paramString, Object paramObject) – This method is used to set the attribute with application scope. The attribute will be accessible to all the other servlets having access to this ServletContext. We can remove an attribute using public abstract void removeAttribute(String paramString) method.
      8. String getInitParameter(String name) – This method returns the String value for the init parameter defined with name in web.xml, returns null if parameter name doesn’t exist. We can use Enumeration<String> getInitParameterNames() to get enumeration of all the init parameter names.
      9. boolean setInitParameter(String paramString1, String paramString2) – We can use this method to set init parameters to the application.

      Note: Ideally the name of this interface should be ApplicationContext because it’s for the application and not specific to any servlet. Also don’t get confused it with the servlet context passed in the URL to access the web application.

    4. ServletRequest interface

      ServletRequest interface is used to provide client request information to the servlet. Servlet container creates ServletRequest object from client request and pass it to the servlet service() method for processing.

      Some of the important methods of ServletRequest interface are:

      1. Object getAttribute(String name) – This method returns the value of named attribute as Object and null if it’s not present. We can use getAttributeNames() method to get the enumeration of attribute names for the request. This interface also provide methods for setting and removing attributes.
      2. String getParameter(String name) – This method returns the request parameter as String. We can use getParameterNames() method to get the enumeration of parameter names for the request.
      3. String getServerName() – returns the hostname of the server.
      4. int getServerPort() – returns the port number of the server on which it’s listening.

      The child interface of ServletRequest is HttpServletRequest that contains some other methods for session management, cookies and authorization of request.

    5. ServletResponse interface

      ServletResponse interface is used by servlet in sending response to the client. Servlet container creates the ServletResponse object and pass it to servlet service() method and later use the response object to generate the HTML response for client.

      Some of the important methods in HttpServletResponse are:

      1. void addCookie(Cookie cookie) – Used to add cookie to the response.
      2. void addHeader(String name, String value) – used to add a response header with the given name and value.
      3. String encodeURL(java.lang.String url) – encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.
      4. String getHeader(String name) – return the value for the specified header, or null if this header has not been set.
      5. void sendRedirect(String location) – used to send a temporary redirect response to the client using the specified redirect location URL.
      6. void setStatus(int sc) – used to set the status code for the response.
    6. RequestDispatcher interface

      RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in the same context. We can also use this to include the content of another resource to the response. This interface is used for servlet communication within the same context.

      There are two methods defined in this interface:

      1. void forward(ServletRequest request, ServletResponse response) – forwards the request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
      2. void include(ServletRequest request, ServletResponse response) – includes the content of a resource (servlet, JSP page, HTML file) in the response.

      We can get RequestDispatcher in a servlet using ServletContext getRequestDispatcher(String path) method. The path must begin with a / and is interpreted as relative to the current context root.

    7. GenericServlet class

      GenericServlet is an abstract class that implements Servlet, ServletConfig and Serializable interface. GenericServlet provide default implementation of all the Servlet life cycle methods and ServletConfig methods and makes our life easier when we extend this class, we need to override only the methods we want and rest of them we can work with the default implementation. Most of the methods defined in this class are only for easy access to common methods defined in Servlet and ServletConfig interfaces.

      One of the important method in GenericServlet class is no-argument init() method and we should override this method in our servlet program if we have to initialize some resources before processing any request from servlet.

    8. HTTPServlet class

      HTTPServlet is an abstract class that extends GenericServlet and provides the base for creating HTTP based web applications. There are methods defined to be overridden by subclasses for different HTTP methods.

      1. doGet(), for HTTP GET requests
      2. doPost(), for HTTP POST requests
      3. doPut(), for HTTP PUT requests
      4. doDelete(), for HTTP DELETE requests
  5. Servlet Attributes

    Servlet attributes are used for inter-servlet communication, we can set, get and remove attributes in web application. There are three scopes for servlet attributes – request scope, session scope and application scope.

    ServletRequest, HttpSession and ServletContext interfaces provide methods to get/set/remove attributes from request, session and application scope respectively.

    Servlet attributes are different from init parameters defined in web.xml for ServletConfig or ServletContext.

  6. Annotations in Servlet 3

    Prior to Servlet 3, all the servlet mapping and its init parameters were used to defined in web.xml, this was not convenient and more error-prone when the number of servlets is huge in an application.

    Servlet 3 introduced use of java annotations to define a servlet, filter and listener servlets and init parameters.

    Some of the important Servlet annotations are:

    1. WebServlet – We can use this annotation with Servlet classes to define init parameters, loadOnStartup value, description and url patterns etc. At least one URL pattern MUST be declared in either the value or urlPattern attribute of the annotation, but not both. The class on which this annotation is declared MUST extend HttpServlet.
    2. WebInitParam – This annotation is used to define init parameters for servlet or filter, it contains name, value pair and we can provide description also. This annotation can be used within a WebFilter or WebServlet annotation.
    3. WebFilter – This annotation is used to declare a servlet filter. This annotation is processed by the container during deployment, the Filter class in which it is found will be created as per the configuration and applied to the URL patterns, Servlets and DispatcherTypes. The annotated class MUST implement javax.servlet.Filter interface.
    4. WebListener – The annotation used to declare a listener for various types of event, in a given web application context.

    Note: We will look into Servlet Filters and Listeners in future articles, in this article our focus is to learn about base interfaces and classes of Servlet API.

  7. Java Servlet Login Example

    Now we are ready to create our login servlet example, in this example, I will use simple HTML, JSP, and servlet that will authenticate the user credentials. We will also see the use of ServletContext init parameters, attributes, ServletConfig init parameters and RequestDispatcher include() and response sendRedirect() usage.

    Our Final Dynamic Web Project will look like below image. I am using Eclipse and Tomcat for the application, the process to create dynamic web project is provided in Java Web Applications tutorial.

    Servlet Example, Java Servlet, Servlet Tutorial, Servlet, Servlets

    Here is our login HTML page, we will put it in the welcome files list in the web.xml so that when we launch the application it will open the login page.

    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="US-ASCII">
    <title>Login Page</title>
    </head>
    <body>
    
    <form action="LoginServlet" method="post">
    
    Username: <input type="text" name="user">
    <br>
    Password: <input type="password" name="pwd">
    <br>
    <input type="submit" value="Login">
    </form>
    </body>
    </html>
    

    If the login will be successful, the user will be presented with new JSP page with login successful message. JSP page code is like below.

    
    <%@ page language="java" contentType="text/html; charset=US-ASCII"
        pageEncoding="US-ASCII"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Login Success Page</title>
    </head>
    <body>
    <h3>Hi Pankaj, Login successful.</h3>
    <a href="login.html">Login Page</a>
    </body>
    </html>
    

    Here is the web.xml deployment descriptor file where we have defined servlet context init parameters and welcome page.

    
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
      <display-name>LoginExample</display-name>
      <welcome-file-list>
        <welcome-file>login.html</welcome-file>
      </welcome-file-list>
      
      <context-param>
      <param-name>dbURL</param-name>
      <param-value>jdbc:mysql://localhost/mysql_db</param-value>
      </context-param>
      <context-param>
      <param-name>dbUser</param-name>
      <param-value>mysql_user</param-value>
      </context-param>
      <context-param>
      <param-name>dbUserPwd</param-name>
      <param-value>mysql_pwd</param-value>
      </context-param>
    </web-app>
    

    Here is our final Servlet class for authenticating the user credentials, notice the use of annotations for Servlet configuration and ServletConfig init parameters.

    
    package com.journaldev.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebInitParam;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * Servlet Tutorial - Servlet Example
     */
    @WebServlet(
    		description = "Login Servlet", 
    		urlPatterns = { "/LoginServlet" }, 
    		initParams = { 
    				@WebInitParam(name = "user", value = "Pankaj"), 
    				@WebInitParam(name = "password", value = "journaldev")
    		})
    public class LoginServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        
    	public void init() throws ServletException {
    		//we can create DB connection resource here and set it to Servlet context
    		if(getServletContext().getInitParameter("dbURL").equals("jdbc:mysql://localhost/mysql_db") &&
    				getServletContext().getInitParameter("dbUser").equals("mysql_user") &&
    				getServletContext().getInitParameter("dbUserPwd").equals("mysql_pwd"))
    		getServletContext().setAttribute("DB_Success", "True");
    		else throw new ServletException("DB Connection error");
    	}
    
    	
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    		//get request parameters for userID and password
    		String user = request.getParameter("user");
    		String pwd = request.getParameter("pwd");
    		
    		//get servlet config init params
    		String userID = getServletConfig().getInitParameter("user");
    		String password = getServletConfig().getInitParameter("password");
    		//logging example
    		log("User="+user+"::password="+pwd);
    		
    		if(userID.equals(user) && password.equals(pwd)){
    			response.sendRedirect("LoginSuccess.jsp");
    		}else{
    			RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
    			PrintWriter out= response.getWriter();
    			out.println("<font color=red>Either user name or password is wrong.</font>");
    			rd.include(request, response);
    			
    		}
    		
    	}
    }
    

    Below screenshots shows the different pages of our Servlet Example project, based on the user password combinations for successful login and failed logins.

    Servlet Tutorial, java Servlet tutorial, servlets, servlet

    servlet tutorial, servlets tutorial, java servlet tutorial

    servlet, servlets, servlet tutorial

That’s all for Servlet Tutorial for beginners, in next tutorial we will look into Session Management, Servlet Filters and Listeners.

Update: Check out next article in series, Session Management in Java.

Comments

  1. konstantinos says:

    Always the same error: HTTP Status 405 – Method Not Allowed

    i copied the files but i am getting the error..
    should upload the right files…

  2. A V Kulkarni says:

    Excellent educational application ! Successfully implemented.
    Thanks a lot.

    — A V Kulkarni

  3. Smriti Jha says:

    Hi,
    I am getting an error of

    HTTP Status 405 – Method not allowed
    HTTP method GET is not supported by this URL

    also, my URL is going to http://localhost:8080/LoginServlet/LoginServlet

    I am not getting LoginExample in my URL.

    can anyone please tell me the issue that can be here?

  4. Peter de Boer says:

    Thanks a lot for the tutorial!
    Unfortunately, I get this error when I try to run it:

    HTTP Status 405 – HTTP method GET is not supported by this URL

    Any idea what could be wrong?

    1. Shamique says:

      You must have missed to mention method=”post” in form i.e. by default if you don’t specify method type it takes GET. Since you have not written doGet method in your servlet throwing you an error. You can do 2 things here either specify the method type as “post” or write doGet method.

  5. monika says:

    please tell me how to make login form using mongodb and jsp

  6. Annushree says:

    Hi Pankaj,

    I am using httpServletRequest.getHeader() for my REST API and i get NPE in jboss everytime for httpServletRequest. I have declared it as Context using annotations.

    1. Pankaj says:

      use method getHeaderNames() to get the enumeration of all the header names in the request. then use getHeader(java.lang.String name) to get the particular header value.

      1. Annushree says:

        Hi Pankaj,

        The httpServletRequest object itself is coming as null

  7. manoj says:

    Getting following error

    HTTP Status 500 – DB Connection Error

    type Exception report

    message DB Connection Error

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    javax.servlet.ServletException: DB Connection Error
    com.mann.LoginServlet.init(LoginServlet.java:32)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1527)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1484)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Unknown Source)

    note The full stack trace of the root cause is available in the Apache Tomcat/8.0.24 logs.

    Apache Tomcat/8.0.24

    1. TurboLoong says:

      check out whether the name and value of in web.xml are different from the init parameters of ServletContext in init() method of LoginServlet.java

  8. deepa says:

    thanks pankaj for code

  9. Skini says:

    I am getting following error

    HTTP Status 500 – Servlet.init() for servlet com.journaldev.servlet.LoginServlet threw exception

    1. Nikita says:

      You must use tomcat8 with java8

  10. krishna patel says:

    i want to require a wtad database connectivity program with simple logic

  11. arturo says:

    is there a way to change the WebInitParams values on the fly? something

    @WebInitParam(name = “name1”, value = “noneone”)
    and after logged and retrived some data from DB change that “name1” value so i can see it on the JSP file, like
    getServletConfig().getInitParameter(“name1”) —> Hi “someone”, you’re logged!

    or there’s no way to change it? or im doing it wrong?
    i tried this but no sure if this is right: getServletConfig().getServletContext().setInitParameter(“name1”, “someone”);

    1. Arslan Qadri says:

      You can use “RequestDispatcher” to forward to “LoginSuccess.jsp” instead of redirecting. That way you will have request object with you.

  12. jagadesh says:

    i want to print valid user name in loginsuccess.html page..
    conditions::with out using second servlet.

  13. Shailesh says:

    How to solve this error occured on FireFox browser ?
    I have written java app using servlet “Accept-Encoding:gzip” header.
    plz help me Sir

    Error:Content Encoding Error

    The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression.

  14. chanhdb says:

    thanks Pankaj for helpful post

  15. Umberto says:

    I got an error after login successful:

    “HTTP Status 500 – Unable to compile class for JSP”

  16. zozo says:

    hi
    kindly i want this Example in netBeans

  17. mahesh says:

    Nice Information

  18. JavaNerd says:

    Thanks for article. It’s very detailed and interesting. I keep getting this error (for a couple of hours now…


    HTTP Status 500 - Servlet.init() for servlet com.coredefend.servlet.LoginServlet threw exception

    type Exception report

    message Servlet.init() for servlet com.coredefend.servlet.LoginServlet threw exception

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    javax.servlet.ServletException: Servlet.init() for servlet com.coredefend.servlet.LoginServlet threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:745)

    root cause

    java.lang.NullPointerException
    com.coredefend.servlet.LoginServlet.init(LoginServlet.java:30)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:745)

    note The full stack trace of the root cause is available in the Apache Tomcat/7.0.56 logs.
    Apache Tomcat/7.0.56

    I am using a MacBook with MySQL and Eclipse. I’ve reinstalled MySQL and am successfully able to add a new DB instance via Eclipse in the Database view so I know the pwd/uid are correct.

    Here is my Servlet code:


    package com.example.servlet;

    import java.io.IOException;
    import java.io.PrintWriter;

    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebInitParam;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    /**
    * Servlet implementation class LoginServlet
    */
    @WebServlet(
    description = "Login Servlet",
    urlPatterns = {"/LoginServlet"},
    initParams = {
    @WebInitParam(name = "user", value="me"),
    @WebInitParam(name = "password", value="Password01")
    })

    public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void init() throws ServletException{
    // create DB connection resource here and set it to Servlet context
    if (getServletContext().getInitParameter("dbURL").equals("jdbc:mysql://localhost/test") &&
    getServletContext().getInitParameter("dbUser").equals("root") &&
    getServletContext().getInitParameter("dbUserPwd").equals("Password12345"))
    getServletContext().setAttribute("DB_Success", "True");
    else throw new ServletException("DB Connection Error");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    }
    /**
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // get http request parameters for userID and password
    String user = request.getParameter("user");
    String pwd = request.getParameter("pwd");

    // get servlet config init params
    String userID = getServletConfig().getInitParameter("user");
    String password = getServletConfig().getInitParameter("password");

    // logging example
    log("User="+user+"::password="+pwd);

    if (userID.equals(user) && password.equals(pwd)) {
    response.sendRedirect("LoginSuccess.jsp");
    } else {
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
    PrintWriter out = response.getWriter();
    out.println("Either username or password is incorrect.");
    rd.include(request, response);
    }
    }

    }

    I can’t figure out what I did wrong. Can you help please?

    1. Pankaj says:

      What is the code in line no 30? It’s clearly showing root cause as NullPointerException.

      1. JavaNerd says:

        Thanks for the response. I can bypass this error by commenting out the jdbc connection snippet. Line 30 tries to connect to make the jdbc connection. For some reason it doesn’t connect. Thus when line 43 tries to access the variables user and pwd, it is null and I believe that throws the error. Should this code work *as is* for the database part? Or am I supposed to import libraries or add JARs?

        Also, a separate issue. When I access http://localhost:8080/LoginExample/LoginServlet, the page is blank. However, I can access http://localhost:8080/LoginExample/login.html successfully. This loads the form and if I submit the correct credentials, I am redirected to http://localhost:8080/LoginExample/LoginSuccess.jsp. Any ideas why the /LoginServlet page is blank?

        1. Pankaj says:

          Try to print the stack trace to find out root cause of the issue, I don’t see any JDBC connection code in the above class. Also you need to include the appropriate JDBC driver jar files for getting database connection.

          For URI issue, I think it’s related to the servlet mapping.

  19. Richard Ganni says:

    Thank you for the tutorial, It’s easy to follow. For all the Java beginners (like me :P) I also found this IBM tutorial, it’s ease to follow too and you can see how to communicate your servlet with jsp:
    http://www.ibm.com/developerworks/java/library/j-hangman-app/index.html?ca=drs-

  20. Yuliya says:

    This mistake occurred: HTTP Status 405 – HTTP method GET is not supported by this URL. What should i do to compile without problems?

    1. Yuliya says:

      Done this task. Wasn’t right URL given.

      1. Curtis says:

        The correct URL is: http://localhost:8080/LoginExample/

        Great tutorials!

  21. Indira says:

    Hi Pankaj,

    In the above example you have sent the data in String from servlet to JSP.
    Can we send a JAVA Class object from Servlet to JSP? If so can you guide me regardig the same

    Thank you in advance.

  22. Zafer says:

    Hi Pankaj,First of all,thanks for your tutorials and examples it’s so much informative but I’m getting an error when I write username and password I just see HTTP 404 not found error

    What’s my mistake?

    1. Zafer says:

      I solved my problem thanks anyway 🙂

      1. Pankaj says:

        Wouldn’t it be nice if you explain what was the problem and fix, it might help someone else too.

  23. shivaprasad says:

    Hi Pankaj ,
    i was trying to run the Servlet Login project given above, i received the following error
    INFO: Server startup in 1429 ms
    Check the string getServletContext().getInitParameter(“dbURL”) = jdbc:mysql://localhost/mysql_db/test
    Jun 26, 2014 8:02:49 PM org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Allocate exception for servlet com.journaldev.servlet.LoginServlet
    javax.servlet.ServletException: DB Connection error
    at com.journaldev.servlet.LoginServlet.init(LoginServlet.java:37)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)

    below is the info of my code changes i am using Mysql server where i have created a DB with name as TEST and user name as :root PWD: root123 but i dont knw if there is any mistake in my below code
    why am i receiving the error

    package com.journaldev.servlet;

    import java.io.IOException;
    import java.io.PrintWriter;

    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebInitParam;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    /**
    * Servlet implementation class LoginServlet
    */
    @WebServlet(
    description = “Login Servlet”,
    urlPatterns = { “/LoginServlet” },
    initParams = {
    @WebInitParam(name = “user”, value = “Pankaj”),
    @WebInitParam(name = “password”, value = “journaldev”)
    })
    public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void init() throws ServletException {
    //we can create DB connection resource here and set it to Servlet context

    System.out.println(“Check the string getServletContext().getInitParameter(\”dbURL\”) = ” + getServletContext().getInitParameter(“dbURL”)); // <== NULL pointer exception thrown
    if(getServletContext().getInitParameter("dbURL").equals("jdbc:mysql://localhost/mysql_db") &&
    getServletContext().getInitParameter("dbUser").equals("root") &&
    getServletContext().getInitParameter("dbUserPwd").equals("root123"))
    getServletContext().setAttribute("DB_Success", "True");
    else throw new ServletException("DB Connection error");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    //get request parameters for userID and password
    String user = request.getParameter("user");
    String pwd = request.getParameter("pwd");

    //get servlet config init params
    String userID = getServletConfig().getInitParameter("user");
    String password = getServletConfig().getInitParameter("password");
    //logging example
    log("User="+user+"::password="+pwd);

    if(userID.equals(user) && password.equals(pwd)){
    response.sendRedirect("LoginSuccess.jsp");
    }else{
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
    PrintWriter out= response.getWriter();
    out.println("Either user name or password is wrong.”);
    rd.include(request, response);

    }

    }

    }

    1. Pankaj says:

      You need to change the user and password values accordingly in LoginServlet.

      1. shivaprasad says:

        Pankaj,

        you are saying to change the value of @WebInitParam(name = “user”, value = “Pankaj”),
        @WebInitParam(name = “password”, value = “journaldev”)
        })

        or the dbusre and pwd ?

        i tried changing both but did not work out
        is that due to wrong DB url ?
        i am new to Java please help me

        1. shivaprasad says:

          Thanks Pankaj,
          i got it. just needed to change the para value in xml file also 🙂

          1. xxx@!3343 says:

            I still didn’t get it.

  24. HIMANSU NAYAK says:

    Hi Pankaj,
    One more important API in ServletRequest Interface is setAttribute(). it has both setAttribute() and getAttribute() method.

  25. sana says:

    charset=US-ASCII
    plz tell me this statement.how work this staement and purpose of this statement in program.

  26. Bala says:

    Hello Pankaj,

    Here i have one doubt with struts.. I write html, ActionFormBean , Action Class and one Java Class for Database Connection.. I got HTTP Status 404 exception when i run my application.. Here i have attached sample below.. Could you navigate me..

    JSP Page

    User Name:
    User Id :
    User Address:

    —————————————————
    ACTION BEAN FORM
    —————————————————

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package com.myapp.struts;

    import javax.servlet.http.HttpServletRequest;

    import org.apache.struts.action.ActionErrors;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.action.ActionMessage;

    /**
    *
    * @author Bala
    */
    public class LoginActionForm extends org.apache.struts.action.ActionForm {

    private String user_Name;

    public String getUser_Add() {
    return user_Add;
    }

    public void setUser_Add(String user_Add) {
    this.user_Add = user_Add;
    }

    public String getUser_Id() {
    return user_Id;
    }

    public void setUser_Id(String user_Id) {
    this.user_Id = user_Id;
    }

    public String getUser_Name() {
    return user_Name;
    }

    public void setUser_Name(String user_Name) {
    this.user_Name = user_Name;
    }
    private String user_Id;
    private String user_Add;

    public LoginActionForm() {
    super();
    // TODO Auto-generated constructor stub
    }

    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    ActionErrors errors = new ActionErrors();
    if (getUser_Name() == null || getUser_Name().length() < 1) {
    errors.add("name", new ActionMessage("error.name.required"));
    // TODO: add 'error.name.required' key to your resources
    }
    return errors;
    }
    }

    —————————————-
    ACTION CLASS
    —————————————-

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package com.myapp.struts;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;

    /**
    *
    * @author Bala
    */
    public class LogonAction extends org.apache.struts.action.Action {

    /*
    * forward name="success" path=""
    */
    private static final String SUCCESS = "success";
    private static final String FAILURE = "failure";

    /**
    * This is the action called from the Struts framework.
    *
    * @param mapping The ActionMapping used to select this instance.
    * @param form The optional ActionForm bean for this request.
    * @param request The HTTP Request we are processing.
    * @param response The HTTP Response we are processing.
    * @throws java.lang.Exception
    * @return
    */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws Exception {

    LoginActionForm lf=(LoginActionForm) form;
    DBConnection db=new DBConnection();
    String name=lf.getUser_Name();
    String id=lf.getUser_Id();
    String add=lf.getUser_Add();

    db.establishConnection();
    String str="Insert into strut_table values('"+name+"','"+id+"','"+add+"')";
    if(db.insertData(str)!=0){

    return mapping.findForward(SUCCESS);

    }

    return mapping.findForward(FAILURE);
    }
    }

    ——————————————————————–
    JAVA CLASS FOR DATABASE CONNECTION
    ——————————————————————–
    package com.myapp.struts;

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;

    public class DBConnection {
    Statement stmt=null;
    Connection con=null;
    ResultSet rs;

    public String establishConnection(){
    try{
    Class.forName("com.mysql.jdbc.Driver");
    con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
    stmt=con.createStatement();
    }
    catch(Exception exce){
    exce.printStackTrace();
    return "Data Base does not connected";
    }
    return "Data Base connected Successful";
    }

    public int insertData(String query){
    int val=0;
    System.out.println("Insert Query : "+query);
    try {
    val = stmt.executeUpdate(query);
    } catch (SQLException e) {
    e.printStackTrace();
    }
    return val;
    }

    }

    ———————————–
    WEB.XML
    ———————————–

    action
    org.apache.struts.action.ActionServlet

    config
    /WEB-INF/struts-config.xml

    debug
    2

    detail
    2

    2

    action
    *.do

    30

    Login.jsp

    /WEB-INF/struts-bean.tld
    /WEB-INF/struts-bean.tld

    /WEB-INF/struts-html.tld
    /WEB-INF/struts-html.tld

    /WEB-INF/struts-logic.tld
    /WEB-INF/struts-logic.tld

    /WEB-INF/struts-nested.tld
    /WEB-INF/struts-nested.tld

    /WEB-INF/struts-tiles.tld
    /WEB-INF/struts-tiles.tld

    ———————————————————
    STRUTS-CONFIG
    ———————————————————


    1. Pankaj says:

      You should upgrade to Struts2, 404 error means that the resource is not there, I am sure that you are not connecting to correct URL.

  27. rowandjj says:

    hey,I am a Chinese Student,your posts helps me much!and now i am trying to translating your posts to Chinese!
    I have one question in this article,it’s about getServletInfo methods,you says the string returned should be plain text and can’t have markups.but when i rewrite this method in my servlet and let it return such as “,..;;’@”,it also can work,why??

    my code is here:

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
    {
    System.out.println(“info = “+this.getServletInfo());
    }
    @Override
    public String getServletInfo()
    {
    return “,,”;
    }

    1. Pankaj says:

      Why are you translating my posts to Chinese without my permission. You do know that it’s a copyright infringement.

  28. JavaMuthu says:

    Hi …..

    This is nice tutorial i had got good idea about servlet API.

    Thanks buddy…….

  29. Eranda says:

    Thank you

  30. Arshad says:

    Hi,
    I have developed a website using servlet and jsp. It is working fine at localhost but whenever i deployed it on my website server jsp can’t communicate servlet. What will be the reason please tell me.

  31. CuriousUser says:

    Hey, I am having a little trouble here. The last line, out.println, it is printing the message on top of the tag and as a result, the page is rendering as a text file rather than an html file.

    1. Pankaj says:

      Not sure what is the issue at your end but it seems to be working fine to me.

  32. kk says:

    its very nice

  33. Jack Li says:

    You are amazing, this blog site is awesome. It solved many of my questions about Java. You taught with a very smooth and patient way. Great Teacher !

  34. Aditya C says:

    Thank you very much .
    I have complete first 2 now moving to sessions..

    Thanks you make it easy to understand.

  35. Haidar says:

    Hi, this stuff is incredible, it’s the perfect start for me .
    it is what that i was looking for ,i learn every thing at single place.

    thanx sir

  36. renal diet says:

    Thanks for helpful post. I am pleased sure this post helps me conserve many hours of browsing other related posts in order to find what I was looking for. Merely I want to say: Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages