This is the beginning of a new series of learning to build a non trivial application hard way, We will be creating a very simple skeletal application using primitive technology and progressively work our way towards more modern and advanced tech stack. The veteran developers who were around while the technology progression was happening would have already learnt it the hard way as part of their career, but any one who was not a part of that evolution missed out on the need for these frameworks and technologies. Most of the websites or blogs would tell you how to use a particular framework but rarely some one talks about the need for lets say Spring or Hibernate, this series intends to address these points and take the reader on the expedited evolution of technology. So feel free to ride along.

We will start by creating a very simple shopping cart application selling wines using pure JSP and Servlet. Now before you cringe and say I don’t use servlet, hear me out. Servlet still forms the foundation of every java based web application, and it’s important to understand how servlets works before we get into magical frameworks where one annotation magically builds every thing without writing a single line of code. This would help you understand why the magic works and what to do when the magical things do not behave the way they should.

We will be using maven to build the application, lets start with creating a basic application from archetype or you can checkout the project from GitHub and copy the initial folder as a starting.

mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-webapp -DarchetypeVersion=1.4 -DgroupId=com.learnithardway -DartifactId=shoppingcart -DinteractiveMode=false

This would create a skeleton shell application in a folder called shoppingcart, we need to import this folder into a java editor to start coding, you can use either Eclipse or Idea. For this example I am using Eclipse, if you are more familiar with Idea, feel free to use it. Before importing it to editor we need to run maven command to generate appropriate project files, so we would run following command.

mkdir src/main/java
mvn eclipse:eclipse 

Lets try and run this application and see what did the archetype built for us. A java webapp needs to be packaged as war (Web Archieve) file and deployed to a web server like Apache Tomcat, Jetty or a Application server like JBoss. For this exercise to keep things simple, we would use maven jetty plugin which would include an embedded jetty and help us run the application without installing any more softwares. So lets add following code in build section of pom.xml

<plugin>
          <groupId>org.eclipse.jetty</groupId>
          <artifactId>jetty-maven-plugin</artifactId>
          <version>9.4.12.RC2</version>
          <configuration>
            <httpConnector>
              <port>9999</port>
            </httpConnector>
          </configuration>
        </plugin>

This would run a jetty server at port 9999, if you want to change the server port you can change it in pom.xml. Lets run following command to make sure that we have every thing ready before we start modifying the code.

mvn jetty:run

We should be able to see hello world on url http://localhost:9999

If you got things working this far, we have the proper setup to start coding.

For our shopping cart app, we would be doing the index page which would list the items based on our fixed dataset, for this example we would not be using any databaset. Lets add a servlet to list the items. We would need to add servlet dependency to the pom by adding following section in pom.xml

<dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

Eclipse would have added some default config to our web.xml, lets clean that and add our own mapping as following, make sure that <web-app> uses 2.5 version. Copy the following web xml and replace the one generated.

<?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" 
  xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  version="2.5">
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
      <servlet-name>IndexServlet</servlet-name>
      <servlet-class>com.learnithardway.web.IndexServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>IndexServlet</servlet-name>
      <url-pattern>/wines</url-pattern>
  </servlet-mapping>
</web-app>

Now lets create our servlet to display the wines.

package com.learnithardway.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

/**
 * Servlet implementation class IndexServlet
 */
public class IndexServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private static List wines = new ArrayList<>();

    /**
     * Default constructor. 
     */
    public IndexServlet() {
        wines.add("Chardonnay White");
        wines.add("Sauvignon Blanc");
        wines.add("Chennin Blanc");
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("wines", wines);
        request.getRequestDispatcher("wines.jsp").forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

Notice that we are using a request dispatcher to forward the request to wines.jsp, so we are not mixing presentation and logic. We are adding wine list in request and send it to wines.jsp to render. Lets see how are wines.jsp looks like.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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=UTF-8">
<title>Wines</title>
</head>
<body>
    <c:forEach items="${wines}" var="wine">
        Item Name: ${wine}<br/>
      </c:forEach>
</body>
</html>

This should display the list of wines like following image

Though this serves our purpose for the exercise, the ui does not look great and if we have to build on this, we would need a better UI. Fortunately we can use free html templates available on web instead of building our own. We would be using one such free template from colorlib which you can get from https://colorlib.com/wp/template/wines/. Our final look should look like following

The full source is available on github at https://github.com/nitizkumar/shopping-cart-jsp-servlet, feel free to download and play around with the code. In the next post we will add database to this project, please do check that out.


Author

Nitiz

There are currently no comments.

Bitnami