Scaffold your ideas into application
Get your free alpha access now.
Only 445 left, Hurry!
06 Aug 2016

j2ee tutorial for beginners (Servlets)

This is the second part of the j2ee-tutorial-beginners series. Please take some time to read the earlier parts of the series at What is a Server?.

In this part we would explore Servlets. Though very few of us would really ever write a servlet for real world purpose, servlet still provide the underlying implementation of almost all of the framework, and precisely for this reason we would continue with Servlet 2 implementation and not Servlet 3 which has quite different syntax.

Servlets are essentially the workhorse of J2EE web application. The purpose of a servlet is to respond to the client request, similar to the code we wrote in first part. This response could be HTTP or any other protocol, though for most of this series we would focus only on HTTP Servlets.

HTTPServlets are java code which produce HTML document or HTML fragments. It supports all the HTTP methods like GET,POST,PUT,DELETE,HEAD,OPTIONS e.t.c. Once we have the code to produce a html document, we need to map it to a URL which is relative to the context path. For the uninitated, context path is mostly the name of the war file which would be deployed in the web server, though it can be changed. This allows us to have multiple application hosted on same server URL.

So lets go ahead and build our servlet. For this we would need to create a j2ee project. Normally we could quickly do this by using Maven which is an excellent build or we could simply download the prebuilt skeleton application or clone it from github.

If you are using maven archetype, install maven and then run command

mvn archetype:generate -DgroupId=com.scaffoldthis -DartifactId=myApp -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

Maven archetype does not create all the directories which is why you would need to run following additional commands.

cd myApp;  
mkdir -p src/main/java;

Rest of the post assumes that you have the github clone, which is highly recommended.

Lets create a class called DemoServlet

img_create

Copy the following code in demoServlet

    package com.scaffoldthis;

    import java.io.IOException;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class DemoServlet extends HttpServlet {

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.getWriter().println("Hello World");
        }
    }

We still need to map it a URL so lets open our web.xml and add following

    <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>com.scaffoldthis.DemoServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

We are essentially asking server to intercept any request to url /hello and assign it to a servlet with name demo which would resolve to a class com.scaffoldthis.DemoServlet.

Now you can run jetty server using maven jetty plugin or package the app as war and deploy it to apache tomcat. I prefer running local jetty which is why you would find jetty preconfigured in github project. so you can simply run

mvn jetty:run

now go to url http://localhost:8080/hello and it should say Hello World. We just finished writing our first servlet. However it does not look much so lets change the code to print some styled HTML to make sure we have our stuff at right place.

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String html = "<html>\n" + 
                "   <head>\n" + 
                "       \n" + 
                "   </head>\n" + 
                "   <body>\n" + 
                "       <form action=\"/hello\" method=\"post\">\n" + 
                "           <input type=\"text\" placeholder=\"Username\" name=\"username\"><br/>\n" + 
                "           <input type=\"password\" placeholder=\"Password\" name=\"password\"><br/>\n" + 
                "           <input type=\"submit\" value=\"login\">\n" + 
                "       </form>\n" + 
                "   </body>\n" + 
                "</html>";
        resp.getWriter().println(html);
    }

Now when you go to http://localhost:8080/hello it should look like this

img

We still need to handle the form submit so lets add following code to our servlet.

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username.equals("admin") && password.equals("admin")){
            resp.getWriter().println("Welcome Admin");
        }
        else
        {
            resp.getWriter().println("Invalid login");
        }
    }

Now we have a working login application. If we look at the way html is mixed up with java code, it should be clear that it would be very difficult to develop the app. The next big leap in J2EE was JSP which allowed user to have cleaner markup for html while keeping logic seperate, which we would analyze in the next part.


Stats:
174 views
Scaffold your ideas into application
Get your free alpha access now.
Only 445 left, Hurry!

j2ee tutorial for beginners ( What is a server?)

Getting started with J2EE: What is a Server?

Part 3: j2ee tutorial for beginners (JSP)

In this part we explore basics of View technology of J2EE

Part 4: j2ee tutorial for beginners (JDBC)

JDBC is the foundation of persistence in Java. This tutorial explore

Comments:

Leave your comments