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 7.x
JDK 1.6
Jar files

spring, jsp and servlet integration example

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

<?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>Spring 3, JSP, Servlet</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/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>

Now we will create a model class which has simply getters and setters for the attributes.

package com.jeejava.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;
}
}

We have then DAO but as I didn’t use database so I have used enum as a repository

package com.jeejava.springjspservlet.dao;
import com.jeejava.springjspservlet.model.Todo;
import java.util.HashMap;
import java.util.Map;
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;
}
}

Next Step is Spring Service class

package com.jeejava.springjspservlet.service;
import com.jeejava.springjspservlet.model.Todo;
import java.util.List;
public interface ToDoService {
List getToDos();
Todo getToDo(String id);
}
package com.jeejava.springjspservlet.service;
import com.jeejava.springjspservlet.dao.TodoDao;
import com.jeejava.springjspservlet.model.Todo;
import java.util.ArrayList;
import java.util.List;
public class ToDoServiceImpl implements ToDoService {
@Override
public List getToDos() {
List 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);
}
}

Now we will create applicationContext.xml file and put it under WEB-INF directory.

<?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.jeejava.springjspservlet.service.ToDoServiceImpl" />

</beans>

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

package com.jeejava.springjspservlet.servlets;
import com.jeejava.springjspservlet.model.Todo;
import com.jeejava.springjspservlet.service.ToDoService;
import java.io.IOException;
import java.io.PrintWriter;
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;
/**
* Servlet implementation class ToDoServlet
*/
@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 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

package com.jeejava.springjspservlet.servlets;
import com.jeejava.springjspservlet.model.Todo;
import com.jeejava.springjspservlet.service.ToDoService;
import com.jeejava.springjspservlet.utils.Utils;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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;
/**
* Servlet implementation class GetToDoServlet
*/
@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);
}
}

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 JSP Servlet</title>
</head>
<body>
<c:if test="${todos.size() > 0}">
<c:out value="Total ToDo Count: ${todos.size()}" />
</c:if>
<p>&nbsp;</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>&nbsp;</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>

Now run the example and see the output.

Thanks for your reading. Please do not forget to leave a comment.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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