Introduction

In this tutorial we will create web application for Spring, JSP and Servlet integration example. In this spring, jsp and servlet integration example we will use spring version 3, jsp version 2 and servlet version 3.

Though there are several MVC frameworks like JSF, Struts, Spring MVC etc. but still if you need to use Servlet without any MVC framework, here it is. Most of us know how to work with Servlet and JSP. So if you have any knowledge of Spring then it will be easier for you to pick up.

I have used here Servlet 3.x so that I can use annotation based URL mapping without configuring in the web.xml file.

Spring also uses annotation based configuration and for that I have already configured in applicationContext.xml file.

This is a basic example and youcan customize according to your needs.

I have not used any database here for query instead I have used enum as a datasource. If you want you can use database and there are number of tutorials on Spring JDBC or Spring Hibernate.

Prerequisites

Eclipse JEE Developer IDE
Tomcat 8.5
JDK 1.8

Project Structure

We create maven based web project in Eclipse with the below details:

Group Id: com.roytuts
Artifact Id: spring-jsp-servlet

Maven Dependencies

Here is the pom.xml file that contains the required dependencies for our project:

<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.roytuts</groupId>
	<artifactId>spring-jsp-servlet</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.2.8.RELEASE</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>spring-jsp-servlet</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

In the above pom file we just defined three dependencies and other transitive dependencies for Spring are downloaded automatically from spring web dependency.

Deployment Descriptor

We will first look into our deployment descriptor file – web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	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>Spring 3, JSP, Servlet</display-name>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

In the above web.xml file we have let web application know where to look for the Spring XML configuration file.

Model Class

Now we will create a simple POJO class to represent as a model class which has simply getters and setters for the attributes.

package com.roytuts.springjspservlet.model;
public class Todo {
	private String id;
	private String desc;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getDesc() {
		return desc;
	}
	public void setDesc(String desc) {
		this.desc = desc;
	}
}

DAO Class

We are not going to fetch data from database, instead we will create an Enum to represent as a repository to hold some data. We can add or remove also as per our needed, though there is no functionality to add or remove from the repository.

package com.roytuts.springjspservlet.dao;
import java.util.HashMap;
import java.util.Map;
import com.roytuts.springjspservlet.model.Todo;
public enum TodoDao {
	instance;
	private Map<String, Todo> contentProvider = new HashMap<String, Todo>();
	private TodoDao() {
		Todo todo1 = new Todo();
		Todo todo2 = new Todo();
		todo1.setId("0001");
		todo1.setDesc("Todo One");
		todo2.setId("0002");
		todo2.setDesc("Todo Two");
		contentProvider.put(todo1.getId(), todo1);
		contentProvider.put(todo2.getId(), todo2);
	}
	public Map<String, Todo> getModel() {
		return contentProvider;
	}
}

Service Class

Next Step is to create Spring Service class, where we may perform some business for the application.

package com.roytuts.springjspservlet.service;
import java.util.List;
import com.roytuts.springjspservlet.model.Todo;
public interface ToDoService {
	List<Todo> getToDos();
	Todo getToDo(String id);
}

The corresponding service implementation can be written as for the above service interface:

package com.roytuts.springjspservlet.service.impl;
import java.util.ArrayList;
import java.util.List;
import com.roytuts.springjspservlet.dao.TodoDao;
import com.roytuts.springjspservlet.model.Todo;
import com.roytuts.springjspservlet.service.ToDoService;
public class ToDoServiceImpl implements ToDoService {
	@Override
	public List<Todo> getToDos() {
		List<Todo> todos = new ArrayList<>();
		todos.addAll(TodoDao.instance.getModel().values());
		return todos;
	}
	@Override
	public Todo getToDo(String id) {
		Todo todo = TodoDao.instance.getModel().get(id);
		return (todo != null ? todo : null);
	}
}

Spring Configuration File

Now we will create applicationContext.xml file and put it under classpathsrc/main/resources directory.

Now we will create servlet to see how Spring and Servlet get integrated. This servlet shows all the ToDo list in the jsp page.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
	<context:annotation-config />
	<bean id="todoService"
		class="com.roytuts.springjspservlet.service.impl.ToDoServiceImpl" />
</beans>

Java Servlets

Create below servlet to fetch all todos from the repository:

package com.roytuts.springjspservlet.servlets;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.roytuts.springjspservlet.model.Todo;
import com.roytuts.springjspservlet.service.ToDoService;
@WebServlet("/todos")
public class ToDoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	//We have already configured in applicationContext.xml for annotation
	@Autowired
	private ToDoService toDoService;
	//Spring ApplicationContext to get the beans
	private WebApplicationContext webApplicationContext;
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ToDoServlet() {
		super();
	}
	/**
	 * @see Servlet#init(ServletConfig)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		// get Spring ApplicationContext
		webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
		// get the bean from ApplicationContext
		toDoService = (ToDoService) webApplicationContext.getBean("todoService");
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// get the data from source using Spring Service
		List<Todo> todos = toDoService.getToDos();
		// set the returned data to the variable for later use
		request.setAttribute("todos", todos);
		// forward the response to the jsp page
		RequestDispatcher requestDispatcher = request.getRequestDispatcher("/index.jsp");
		requestDispatcher.forward(request, response);
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}
}

Below servlet is used to get a ToDo for a given id, i.e., it will fetch single todo:

package com.roytuts.springjspservlet.servlets;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.roytuts.springjspservlet.model.Todo;
import com.roytuts.springjspservlet.service.ToDoService;
import com.roytuts.springjspservlet.utils.Utils;
@WebServlet("/todo")
public class GetToDoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@Autowired
	private ToDoService toDoService;
	private WebApplicationContext webApplicationContext;
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetToDoServlet() {
		super();
	}
	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
		toDoService = (ToDoService) webApplicationContext.getBean("todoService");
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id");
		boolean isInt = Utils.isInteger(id);
		if (isInt) {
			Todo todo = toDoService.getToDo(id);
			if (todo == null) {
				request.setAttribute("error", "No ToDo found for this id: " + id);
			} else {
				request.setAttribute("todo", todo);
			}
		} else {
			request.setAttribute("error", "id must be an integer value.");
		}
		RequestDispatcher requestDispatcher = request.getRequestDispatcher("/index.jsp");
		requestDispatcher.forward(request, response);
	}
}

Related posts:

View Page

View page – index.jsp – where a ToDo for a given id and all the ToDo list will be shown:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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=ISO-8859-1">
<title>Spring 3 JSP Servlet</title>
</head>
<body>
	<c:if test="${todos.size() > 0}">
		<c:out value="Total ToDo Count: ${todos.size()}" />
	</c:if>
	<p> </p>
	<c:choose>
		<c:when test="${todos.size() > 0}">
			<table border="1">
				<tr>
					<th>ToDo ID</th>
					<th>ToDo Description</th>
				</tr>
				<c:forEach items="${todos}" var="todo">
					<tr>
						<td>${todo.id}</td>
						<td>${todo.desc}</td>
					</tr>
				</c:forEach>
			</table>
		</c:when>
		<c:otherwise>
			No ToDo found!
		</c:otherwise>
	</c:choose>
	<p> </p>
	<div>
		<p>
			<c:if test="${!empty error}">
				<c:out value="${error}" />
			</c:if>
		</p>
		<form method="post" action="todo">
			<label>Input ToDo id:</label> <input type="text" name="id" id="id" />
			<input type="submit" name="ToDoSubmit" value="Get ToDo" />
		</form>
		<p>
			<c:if test="${!empty todo}">
				<c:out value="ToDo id: ${todo.id}" />
				<br />
				<c:out value="ToDo desc: ${todo.desc}" />
			</c:if>
		</p>
	</div>
</body>
</html>

Utils Class

The following utils class is required to check whether an input id is integer or not:

package com.roytuts.springjspservlet.utils;
public class Utils {
	private Utils() {
	}
	public static boolean isInteger(String s) {
		try {
			Integer.parseInt(s);
		} catch (NumberFormatException e) {
			return false;
		} catch (NullPointerException e) {
			return false;
		}
		return true;
	}
}

Download Source Code

Thanks for reading.

Tags:

2 thoughts on “Spring, JSP and Servlet integration example

Leave a Reply

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