How To Create a Web Application Using Simple Servlets and JSP with the help of Maven for dependency Management

In this series of creating web appliction in java in the previous post we create we application using Spring. In this tutorial we will walk through the basic of Java we appliction which are servlets and JSP. This is the basic concept which all other high level frameworks use internally.

Generating Web Project From Maven Template:

 pwd /home/tuturself/Maven_Simple_Servlet_Web_Project
 
 
 tuturself Maven_Simple_Servlet_Web_Project # mvn archetype:generate -DgroupId=com.tuturself.app -DartifactId=SampleWebAppServlet -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
 [INFO] Scanning for projects...
 [INFO] Searching repository for plugin with prefix: 'archetype'.
 [INFO] ------------------------------------------------------------------------
 [INFO] Building Maven Default Project
 [INFO]    task-segment: [archetype:generate] (aggregator-style)
 [INFO] ------------------------------------------------------------------------
 [INFO] Preparing archetype:generate
 [INFO] No goals needed for project - skipping
 [INFO] [archetype:generate {execution: default-cli}]
 [INFO] Generating project in Batch mode
 [INFO] ----------------------------------------------------------------------------
 [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:1.0
 [INFO] ----------------------------------------------------------------------------
 [INFO] Parameter: basedir, Value: /home/admin/Maven_Simple_Servlet_Web_Project
 [INFO] Parameter: package, Value: com.tuturself.app
 [INFO] Parameter: groupId, Value: com.tuturself.app
 [INFO] Parameter: artifactId, Value: SampleWebAppServlet
 [INFO] Parameter: packageName, Value: com.tuturself.app
 [INFO] Parameter: version, Value: 1.0-SNAPSHOT
 [INFO] project created from Old (1.x) Archetype in dir: /home/admin/Maven_Simple_Servlet_Web_Project/SampleWebAppServlet
 [INFO] ------------------------------------------------------------------------
 [INFO] BUILD SUCCESSFUL
 [INFO] ------------------------------------------------------------------------
 [INFO] Total time: 22 seconds
 [INFO] Finished at: Mon Sep 12 13:10:07 IST 2016
 [INFO] Final Memory: 26M/178M
 [INFO] ------------------------------------------------------------------------
 

Structure of the Project :

 devilsden SampleWebAppServlet # tree 
 .
 |-- pom.xml
 |-- src
 |   `-- main
 |       |-- resources
 |       `-- webapp
 |           |-- index.jsp
 |           `-- WEB-INF
 |               `-- web.xml
 `-- target
     `-- classes
 
 7 directories, 3 files

Importing Project into Eclipse :

To import the current project to eclispse we need to add eclipse nature to the project using the below command

mvn eclipse:eclipse -Dwtpversion=2.0

 tuturself SampleWebAppServlet # mvn eclipse:eclipse -Dwtpversion=2.0
 [INFO] Scanning for projects...
 [INFO] Searching repository for plugin with prefix: 'eclipse'.
 [INFO] ------------------------------------------------------------------------
 [INFO] Building SampleWebAppServlet Maven Webapp
 [INFO]    task-segment: [eclipse:eclipse]
 [INFO] ------------------------------------------------------------------------
 [INFO] Preparing eclipse:eclipse
 [INFO] No goals needed for project - skipping
 [INFO] [eclipse:eclipse {execution: default-cli}]
 [INFO] Adding support for WTP version 2.0.
 [INFO] Using Eclipse Workspace: null
 [INFO] Adding default classpath container: org.eclipse.jdt.launching.JRE_CONTAINER
 [INFO] Not writing settings - defaults suffice
 [INFO] Wrote Eclipse project for "SampleWebAppServlet" to /home/admin/Maven_Simple_Servlet_Web_Project/SampleWebAppServlet.
 [INFO] 
 [INFO] ------------------------------------------------------------------------
 [INFO] BUILD SUCCESSFUL
 [INFO] ------------------------------------------------------------------------
 [INFO] Total time: 1 second
 [INFO] Finished at: Mon Sep 12 13:11:44 IST 2016
 [INFO] Final Memory: 14M/179M
 [INFO] ------------------------------------------------------------------------
 

 

After the Build is Successful on command we need to import project in eclipse.

 File -> Import… -> General -> Existing Projects into workspace.

 

 

Structure will look like :

 

NOTE: Most of the case you will see only src/main/resources we need to add a source folder manually 

Right Click on Project → New → Source Folder (A popup will arise there you need to put the path below is the image )

 

 

After the project is imported you will have to change few files web.xml. Since Current web.xml contains web-app verion 2.3 update to 2.5 or 3.0

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:web="http://java.sun.com/xml/ns/javaee"
	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"
	version="3.0">

	<display-name>Sample Web Application Using Servlet</display-name>

	<!-- Setting Servlet Name and Class to let the Cotainer know -->
	<servlet>
		<servlet-name>baseservlet</servlet-name>
		<servlet-class>com.tuturself.servletwebapp.BaseServlet</servlet-class>
		 <load-on-startup>0</load-on-startup>
	</servlet>

	<!-- URL Mapping for the servlet -->
	<servlet-mapping>
		<servlet-name>baseservlet</servlet-name>
		<url-pattern>/getServerTime</url-pattern>
	</servlet-mapping>

</web-app>

Adding Dependencies (Dependent java libraries) :

Dependency management is taken care by maven just need to add dependency by searching on maven central repository https://mvnrepository.com/

    Add project dependencies – httpServlet
    Add plugins to configure project

Below pom.xml →

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.tuturself.app</groupId>
	<artifactId>SampleWebApp</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>SampleWebApp Maven Webapp</name>
	<properties>
		<jdk.version>1.7</jdk.version>
		<junit.version>4.11</junit.version>
		<log4j-api.version>2.6.2</log4j-api.version>
		<log4j-core.version>2.6.2</log4j-core.version>
		<disruptor.version>3.2.0</disruptor.version>
		<jstl.version>1.2</jstl.version>
		<jsp.version>2.1</jsp.version>
		<servlet-version>3.1.0</servlet-version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlet-version}</version>
		</dependency>

		<!-- Jstl Lib -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl.version}</version>
		</dependency>

		<!-- Jsp Api -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>${jsp.version}</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>${log4j-api.version}</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>${log4j-core.version}</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/com.lmax/disruptor -->
		<dependency>
			<groupId>com.lmax</groupId>
			<artifactId>disruptor</artifactId>
			<version>${disruptor.version}</version>
		</dependency>

	</dependencies>

	<build>
	   <finalName>SampleWebApp</finalName>

	   <plugins>
        	<!-- JDK Compiler Level -->
		<plugin>
		  <groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>2.3.2</version>
			<configuration>
				<source>${jdk.version}</source>
				<target>${jdk.version}</target>
			</configuration>
		</plugin>
	  <plugins>

       </build>
</project>

Creating Base Servlet to Handle Request :

 

Right Click → New → Servlet

 

 

 package com.tuturself.servletwebapp;
 
 import java.io.IOException;
 
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 /**
  * Servlet implementation class BaseServlet
  */
 
 public class BaseServlet extends HttpServlet {
 	private static final long serialVersionUID = 1L;
        
     /**
      * @see HttpServlet#HttpServlet()
      */
     public BaseServlet() {
         super();
         // TODO Auto-generated constructor stub
     }
 
 	/**
 	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 	 */
 	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 		response.getWriter().append("Served at: ").append(request.getContextPath());
 	}
 
 	/**
 	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 	 */
 	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 		doGet(request, response);
 	}
 
 }
 

 

Configuring log4j2.xml for logging :

 
<?xml version="1.0" encoding="UTF-8"?>
 <Configuration status="WARN">
 <Appenders>
   <RollingFile name="DebugRollingFile" fileName="${sys:catalina.home}/logs/debuglogs/baas.log"
     filePattern="${sys:catalina.home}/logs/debuglogs/baas.log.%d{yyyy-MM-dd-HH}.gz">
 	<PatternLayout>
 	   <Pattern>%d{ISO8601} %-5p [%c:%F:%L] - [%t] - %m%n</Pattern>
 	</PatternLayout>
 	<Policies>
 	  <TimeBasedTriggeringPolicy />
 	</Policies>
 	<Filters>
 	  <ThresholdFilter levelMin="TRACE" levelMax="FATAL" onMatch="ACCEPT" onMismatch="NEUTRAL" />
 	</Filters>
   </RollingFile>
 </Appenders>
 
 <Loggers>
 
  <AsyncLogger name="com.tuturself.controller" level="${sys:baas-loglevel}" includeLocation="true" additivity="false">
    <AppenderRef ref="DebugRollingFile" />
  </AsyncLogger>
 
  <AsyncLogger name="org.springframework" level="error" includeLocation="true" additivity="false">
    <AppenderRef ref="DebugRollingFile" />
  </AsyncLogger>
 
  <AsyncRoot level="WARN" includeLocation="true" additivity="false">
    <AppenderRef ref="DebugRollingFile" />
  </AsyncRoot>
 </Loggers>
</Configuration>

 

Current Folder Structure :

 tuturself SampleWebAppServlet # tree
 .
 |-- pom.xml
 `-- src
     `-- main
         |-- java
         |   `-- com
         |       `-- tuturself
         |           `-- servletwebapp
         |               `-- BaseServlet.java
         |-- resources
         `-- webapp
             |-- index.jsp
             |-- serverTime.jsp
             `-- WEB-INF
                 `-- web.xml
 
 9 directories, 5 files

 

Deploying Generated war in target folder to tomcat web app folder :

 tuturself target # pwd
/home/tuturself/Maven_Simple_Servlet_Web_Project/SampleWebAppServlet/target
 
 tuturself target # ls -ltrh
 total 1.8M
 drwxr-xr-x 3 root root 4.0K Sep 12 15:36 generated-sources
 drwxr-xr-x 4 root root 4.0K Sep 12 15:36 SampleWebApp
 drwxr-xr-x 3 root root 4.0K Sep 12 15:36 classes
 drwxr-xr-x 2 root root 4.0K Sep 12 15:36 maven-archiver
 -rw-r--r-- 1 root root 1.8M Sep 12 15:36 SampleWebApp.war
 drwxr-xr-x 2 root root 4.0K Sep 12 15:36 surefire
 
 tuturself target # cp SampleWebApp.war /home/admin/Software/tomcat/webapps/
  
 tuturself bin # cd /home/admin/Software/tomcat/bin
 
 tuturself bin # pwd
 /home/admin/Software/tomcat/bin
  
  tuturself bin # ./startup.sh 
  Using CATALINA_BASE:   /home/admin/Software/tomcat
  Using CATALINA_HOME:   /home/admin/Software/tomcat
  Using CATALINA_TMPDIR: /home/admin/Software/tomcat/temp
  Using JRE_HOME:        /media/Data/jdk1.8.0_92/
  Using CLASSPATH:       /home/admin/Software/tomcat/bin/bootstrap.jar:/home/admin/Software/tomcat/bin/tomcat-juli.jar
  Tomcat started.

 

Testing using Browser :  http://localhost:8080/SampleWebApp/

Home Page

 

 

doGet Method of the servlet called it lods the JSP and Renders.

 

 

 

Git hub Link : https://github.com/mastershifu007/Maven_Simple_Servlet_Web_Project

 

 

JSP-SERVLET SERVLET