Tuesday, July 06, 2010

Simple Spring MVC Program with CRUD Operation on My-SQL.



Simple Spring MVC Example shows CRUD (Create(insert) Read(Select) Update Delete) Operation on MySQL Database:
Step to Create Simple Spring Example

Tool used:

1) STS Spring Source Tool

Steps:

1) Right Click on the Explorer Play ground and create a Web Dynamic Project.
2) Add all necessary jar to lib folder (Coming as Package for Spring Frame Work.)
3) Add a *.jsp in to display the Input/result to the user.
4) Create a XXX-servlet.xml inside SpringWebApp\WebContent\WEB-INF
5) XXX in step 4 depends on the name Developer provide in servlet-name tag of web.xml
5)Create Controller Class that contain business logic in it.

Flow will be like this:

During the deployment of the Spring project, Container will read/refer the deployment descriptor and will create an instance of DispatcherServlet.

When the user hit the URL with *.html content that request is diverted to DispatcherServlet, where requestProcessor delegate the request as per the flow provided in XXX-servlet.xml

In this example we had created enterData-servlet.xml. This example contains beans id with name urlMapping represented by SimpleUrlHandlerMapping class . This class refer to the url entered by the user and delegate that term to perticular controller
i.e. if the user hit http://localhost:8080/EnterData.htm it will call enterDataController tag in
enterData-servlet.xml and this enterDataController tag in enterData-servlet.xml is linked with ShowPage class and finally the code in the ShowPage is executed.

loginFormController is linked with Controller.LoginFormController this bean id represent following tag

1) formView : This represent the name of the jsp file that is displayed to the user.
2) successView : This represent the forward action that has to be done when success is return from the action class.
3) commandName : represent the name that we define in form tag of the jsp: commandName="loginData"
4) commandClass: Represent the name of the class "Controller.LoginFormData" where business logic for the action is written.

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" 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"

id="WebApp_ID" version="2.5">

<servlet>

<servlet-name>enterDataservlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>

<load-on-startup>1load-on-startup>

servlet>

<servlet-mapping>

<servlet-name>enterDataservlet-name>

<url-pattern>*.htmurl-pattern>

servlet-mapping>

<welcome-file-list>

<welcome-file>redirect.jspwelcome-file>

welcome-file-list>

web-app>

enterData-servlet.xml:

xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="viewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix">

<value>/WEB-INF/jsp/value>

property>

<property name="suffix">

<value>.jspvalue>

property>

bean>

<bean id="enterDataController" class="Controller.ShowPage">

bean>

<bean id="loginFormController" class="Controller.LoginFormController">

<property name="formView" value="LogIn" />

<property name="successView" value="ResultPage.htm" />

<property name="commandName" value="loginData" />

<property name="commandClass" value="Controller.LoginFormData" />

bean>

<bean id="resultPageController" class="Controller.ResultPageController">

bean>

<bean id="urlMapping"

class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="urlMap">

<map>

<entry key="EnterData.htm">

<ref bean="enterDataController" />

entry>

<entry key="LogIn.htm">

<ref bean="loginFormController" />

entry>

<entry key="ResultPage.htm">

<ref bean="resultPageController" />

entry>

map>

property>

bean>

beans>

EnterData.jsp:

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Database Modificationtitle>

head>

<body>

No Action has been done on the Database side please check the DB for more confirmation.

body>

html>

LogIn.jsp:

<html>

<body>

<form:form commandName="loginData" method="POST">

ID:<form:input path="id"/><br/>

Name:<form:input path="name"/><br/>

<input type="submit" value="Insert1" name="Insert"/>

<input type="submit" value="Update1" name="Update"/>

<input type="submit" value="Delete1" name="Delete"/>

<input type="submit" value="No_Submit" name="No_Submit"/>

form:form>

body>

html>

ResultPage.jsp

<html>

<body>

<h1>Data Base is updated Successfully!h1>

body>

html>

LoginFormController:

package Controller;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.datasource.DriverManagerDataSource;

import org.springframework.validation.BindException;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.SimpleFormController;

import org.springframework.web.servlet.view.RedirectView;

public class LoginFormController extends SimpleFormController {

@Override

public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {

LoginFormData formData = (LoginFormData)command;

request.getSession().setAttribute("FORM_DATA", formData);

ModelAndView modelAndView = new ModelAndView(new RedirectView(getSuccessView()));

if (request.getParameter("Insert") != null) {

// delete object

return Insert(request, response, command, errors);

} else if (request.getParameter("Update") != null) {

// Update object

return Update(request, response, command, errors);

} else if (request.getParameter("Delete") != null) {

// Delete object

return Delete(request, response, command, errors);

}

else {

// save object

return new ModelAndView("EnterData");

}

}

public ModelAndView Insert(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {

LoginFormData formData = (LoginFormData)command;

request.getSession().setAttribute("FORM_DATA", formData);

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost/siddhutest_db");

dataSource.setUsername("root");

dataSource.setPassword("");

JdbcTemplate template = new JdbcTemplate(dataSource);

template.update("insert into test_table (id, name) values (?, ?)", new Object[] {formData.getId(), formData.getName()});

ModelAndView modelAndView = new ModelAndView(new RedirectView(getSuccessView()));

return modelAndView;

}

public ModelAndView Update(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {

LoginFormData formData = (LoginFormData)command;

request.getSession().setAttribute("FORM_DATA", formData);

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost/siddhutest_db");

dataSource.setUsername("root");

dataSource.setPassword("");

JdbcTemplate template = new JdbcTemplate(dataSource);

template.update("update test_table set name = ? where id = ?", new Object[] {formData.getName(),formData.getId()});

ModelAndView modelAndView = new ModelAndView(new RedirectView(getSuccessView()));

return modelAndView;

}

public ModelAndView Delete(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {

LoginFormData formData = (LoginFormData)command;

request.getSession().setAttribute("FORM_DATA", formData);

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost/siddhutest_db");

dataSource.setUsername("root");

dataSource.setPassword("");

JdbcTemplate template = new JdbcTemplate(dataSource);

template.update("delete from test_table where id = ?", new Object[] {formData.getId()});

ModelAndView modelAndView = new ModelAndView(new RedirectView(getSuccessView()));

return modelAndView;

}

}

LoginFormData:

package Controller;

public class LoginFormData {

private String id;

private String name;

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

ResultPageController:

package Controller;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.AbstractController;

public class ResultPageController extends AbstractController {

@Override

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

return new ModelAndView("ResultPage");

}

}


ShowPage:

package Controller;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.AbstractController;

public class ShowPage extends AbstractController {

@Override

protected ModelAndView handleRequestInternal(HttpServletRequest request,

HttpServletResponse response) throws Exception {

return new ModelAndView("EnterData");

}

}

1 comment:

hero said...

Some " /> " tags were missing ....but i didn't bother about that and finally I got my code right..
Thanks ........You don't know how much have you helped me....you made my night........hope 2 c more tutorials like this ........