Srikanth Technologies

Songs Project using Spring MVC, DAO and Spring + JDBC

This is another way of building Songs application. It uses Spring MVC in the presentation tier. Controllers in Spring MVC are used to access DAO, which in turn accesses database using JDBC through Spring Core.

Create Web Application

Use NetBeans (or any other IDE of your choice) to create a new web application. It uses Tomcat. Again you can choose whatever server you like. Also select Spring MVC as the framework to be used for this project.

I am naming the project as SongsSpringMvc as we use Spring MVC in this project.

Add JSTL library,and OJDBC14.jar to libraries node in the project they are required.

In order to use AOP with Spring (we use AOP for transaction management), you need to add the following .jar files:

I have made all these files available as a single download at http://www.megafileupload.com/en/file/311042/springdeplib-rar.html. So download and add these .jar files to your project libraries so that they are placed in the classpath.

Add the following files from previous project, Songs With Spring + Jdbc, as they remain the same for this project also.

WEB-INF/web.xml

We need to modify web.xml in order to load DispatherServlet as the application is deployed. Whenever a request is made with .htm as the suffix, DispatcherServlet is processing the request.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
    <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>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

WEB-INF/dispatcher-servlet.xml

This xml file is used by dispatcher servlet.

<?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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="controller"/>
    
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />
 </beans>
 

controller/SongsController.java

Controller is used to process the request. It accesses the DAO to access database through Spring + JDBC and returns the data to .jsp (view) so that data is displayed. In case of add song, it takes data from data entered into textboxes and sends it to DAO so that data is inserted into database.
package controller;

import entities.Song;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import validators.SongValidator;

@Controller
public class SongsController {

    @RequestMapping("/list")
    protected ModelAndView listSongs(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        ModelAndView mv = new ModelAndView("list", "songs", dao.SongsDAO.getSongs());
        return mv;
    }

    @RequestMapping("/add")
    protected ModelAndView addSong(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        ModelAndView mv = new ModelAndView("add", "command", new Song());
        return mv;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    protected String addSong(@ModelAttribute("command") Song song, BindingResult result, HttpServletRequest req) {
        System.out.println( "Title :" +  result.getFieldValue("title"));
        SongValidator s = new SongValidator();
        s.validate(song, result);
        if (result.hasErrors()) {
            return "add";
        }

        boolean done = dao.SongsDAO.addSong(song.getTitle(), song.getSinger());
        if (done) {
            song.setTitle("");
            song.setSinger("");
            req.setAttribute("msg", "Successfully Added Song!");
            return "add";
        } else {
            req.setAttribute("msg", "Sorry! Could Not Add Song!");
            return "add";
        }
    }
}

validators/SongValidator.java

Validator is used to validate the data entered into textboxes it the form.
package validators;

import entities.Song;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class SongValidator  implements Validator {
    public boolean supports(Class<?> type) {
        return  Song.class.equals(type);
    }
    public void validate(Object obj, Errors errors) {
          System.out.println("Validating...");
    	  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title", "field.required", "Title is required field");
  	  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "singer", "field.required", "Singer is required field");
       }
}

WEB-INF/jsp/add.jsp

This is used to take input from user using Spring MVC forms library.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<html>
    <head>
        <style>
            .error {
                color: red;
            }
        </style>
    </head>
    <body>
        <h1>Add Song</h1>

        <form:form method="post" action="add.htm">
    	    Title :  <form:input path="title"/> <form:errors path="title" cssClass="error"/>
            <br/>
            Singer  : <form:input path="singer" /><form:errors path="singer" cssClass="error"/>
            <p/>
            <input type="submit" value="Add Song">
        </form:form>
            <h3>${msg} </h3>
            <p/>
            <a href="index.jsp">Home Page </a>
    </body>
</html>

WEB-INF/jsp/list.jsp

This is used to display the list of songs. Controller places list of songs in songs attribute, which is placed in Request object.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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>List Of Songs</title>
    </head>
    <body>
        <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

        <h1>List Of Songs</h1>
        <table border="1">
            <tr>
                <th>Song ID </th>
                <th>Title </th>
                <th>Singer</th>
            </tr>
            <c:forEach items="${songs}" var="song">

                <tr>
                    <td>${song.songid} </td>
                    <td> ${song.title} </td>
                    <td> ${song.singer} </td>
                </tr>
            </c:forEach>
        </table>
        <p/>
        <a href="index.jsp">Home Page </a>

    </body>
</html>

index.jsp

This is in the root directory of the web application. It is used to invoke other operations.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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>Songs Database</title>
    </head>
    <body>
        <h1>Songs Database</h1>
        <a href="add.htm">Add New Song</a>
        <p/>
        <a href="list.htm">List Songs</a>
        <p/>
    </body>
</html>

That's All

Well that's all you have to do. Deploy the application and run index.jsp.