Tuesday, May 14, 2013

Spring MVC


Step(1): Create Dynamic web project and add following libraries

Step(2): Add the following files
Student.java

package com.kamal.model;
public class Student {
  private String name;
  private String address;
  private Integer age;
  private String phone;
  private Integer id;

public Integer getId() {
  return id;
}

public void setId(Integer id) {
  this.id = id;
}

public String getName() {
  return name;
}

public void setName(String name) {
  this.name = name;
}

public String getAddress() {
  return address;
}

public void setAddress(String address) {
  this.address = address;
}

public Integer getAge() {
  return age;
}

public void setAge(Integer age) {
  this.age = age;
}

public String getPhone() {
  return phone;
}

public void setPhone(String phone) {
  this.phone = phone;
  }
}




StudentService.java

package com.kamal.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.kamal.model.Student;

public interface StudentService {
@Transactional
public Student getStudent(int id);
public void delete(int id);
public void update(int id, Student s);
public void create(Student s);
@Transactional
public List<Student> getAll();
}



StudentServiceImpl.java

package com.kamal.service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import com.kamal.model.Student;

@Service("studentService")
public class StudentServiceImpl extends
org.springframework.jdbc.core.JdbcTemplate
implements StudentService {
//returns the list of students
@Override
public List<Student> getAll() {
      String sql = "SELECT * FROM Student";
      List<Student> std = query(sql, new RowMapper<Student>() {
@Override
public Student mapRow(ResultSet rs, int rowNum) 
                   throws SQLException {
                         Student s = new Student();
                         s.setAddress(rs.getString("address"));
                         s.setName(rs.getString("name"));
                         s.setAge(rs.getInt("age"));
                         s.setId(rs.getInt("id"));
                         s.setPhone(rs.getString("phone"));
                        return s;
                   }
});
              return std;
}

//create student

@Override
public void create(Student s) {
String sql = "INSERT INTO Student  (name, address, age, phone) VALUES(?,?,?,?)";
update(sql, new Object[] { s.getName(), s.getAddress(), s.getAge(), s.getPhone() });
}




//update student with given id
@Override
public void update(int id, Student s) {
String sql = "UPDATE Student SET name=?, address=?, age=?, phone=? WHERE id=?";
update(sql, new Object[] { s.getName(), s.getAddress(), s.getAge(),
s.getPhone(), id });
}


//delete student with given id
@Override
public void delete(int id) {
String sql = "DELETE FROM Student WHERE id=?";
update(sql, id);
}

//returns student with given id
@Override
public Student getStudent(int id) {
String sql = "SELECT * FROM Student where id=?";
Student std = queryForObject(sql, new Object[] { id },
                             new RowMapper<Student>() {
                          public Student mapRow(ResultSet rs, int rowNum)
                               throws SQLException {
                              Student s = new Student();
                              s.setAddress(rs.getString("address"));
                              s.setName(rs.getString("name"));
                              s.setAge(rs.getInt("age"));
                              s.setId(rs.getInt("id"));
                              s.setPhone(rs.getString("phone"));
                 return s;
          }
});
             return std;
   }
}




 
MainController.java

package com.kamal.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.kamal.model.Student;
import com.kamal.service.StudentService;

@Controller
@RequestMapping(value = "/student")
public class MainController {
@Autowired
private StudentService studentService;

@RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView showForm(Model model) {

return new ModelAndView("form", "command", new Student());
}

@RequestMapping(value="/add", method = RequestMethod.POST)
public String getFromForm(@RequestParam(value = "name") String name, @RequestParam(value="address") String address,
@RequestParam(value = "phone") String phone,
@RequestParam(value = "age") int age, Model model) {
           Student std = new Student();
           std.setAddress(address);
           std.setAge(age);
           std.setName(name);
           std.setPhone(phone);
           studentService.create(std);
        List<Student> students = studentService.getAll();
        model.addAttribute("student", students);
   return "redirect:view";
}

@RequestMapping(value="/edit", method = RequestMethod.GET)
public String editForm(Model model,@RequestParam("id")int id) {
Student student = studentService.getStudent(id);
model.addAttribute("student", student);
return "edit";
}


@RequestMapping(value="/edit", method = RequestMethod.POST)
public String editFormPost(Model model, @RequestParam("id") int id,
@RequestParam(value = "name", required = true) String name,
@RequestParam(value = "address", required = true) String address,
@RequestParam(value = "phone", required = true) String phone,
@RequestParam(value = "age", required = true) int age) {
         Student student = new Student();
         student.setId(id);
         student.setName(name);
         student.setAddress(address);
         student.setPhone(phone);
         student.setAge(age);
         studentService.update(id, student);
         List<Student> students = studentService.getAll();
         model.addAttribute("student", students);
         return "redirect:view";
   }

@RequestMapping(value = "/view")
public String dispResult( Model model) {
     List<Student> listOfStudent = studentService.getAll();
     model.addAttribute("student", listOfStudent);
     return "view";
}


@RequestMapping(value="/delete",method = RequestMethod.GET)
public String editFormPost(Model model, @RequestParam("id") Integer id) {
       studentService.delete(id);
       List<Student> students = studentService.getAll();
       model.addAttribute("student", students);
      return "redirect:view";
   }
}


form.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!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>Add Student Form</title>
   </head>
  <body>
    <table>
     <form:form method="post" action="add">
   <tr>
     <td><form:label path="name">Name</form:label></td>
     <td><form:input path="name"></form:input></td>
  </tr>
  <tr>
   <td><form:label path="address">Address</form:label></td>
   <td><form:input path="address"></form:input></td>
  </tr>
  <tr>
    <td><form:label path="age">Age</form:label></td>
    <td><form:input path="age"></form:input></td>
  </tr>
  <tr>
   <td><form:label path="phone">Phone</form:label></td>
   <td><form:input path="phone"></form:input></td>
</tr>
<tr>
  <td><input type="submit" value="add"></td>
</tr>
   </form:form>
  </table>
 </body>
</html>





edit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@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=UTF-8">
<title>Edit Form</title>
 </head>
  <body>
   <form method="post" action="edit">
<table>
<tr>
  <td><input name="id" type="hidden"value="${student.id}"></td>
</tr>
<tr>
  <td>Name</td>
  <td><input type="text" name="name" value="${student.name}"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" id="address"
value="${student.address}"></td>
</tr>
<tr>
<td>Phone</td>
<td><input type="text" name="phone" value="${student.phone}"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="${student.age}"></td>
</tr>
<tr>
<td><input type="submit" value="update"></td>
</tr>
</table>
</form>
</body>
</html>



view.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@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=UTF-8">
<title>Student List</title>
</head>
<body>
<a href="add">Add</a>
<table>
  <thead>
    <tr>
      <td>Id</td>
      <td>Name</td>
      <td>Address</td>
      <td>Age</td>
      <td>Phone</td>
   </tr>
  </thead>
<tbody>
   <c:forEach var="student" items="${student}">
   <tr>
     <td>${student.id}</td>
     <td>${student.name}</td>
     <td>${student.address}</td>
     <td>${student.age}</td>
     <td>${student.phone}</td>
     <td><a href="edit?id=${student.id}">Edit</a></td>
     <td><a href="delete?id=${student.id}">Delete</a></td>
  </tr>
  </c:forEach>
</tbody>
 </table>
  </body>
</html>



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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SpringTutorial</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</context-param>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>



spring-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" 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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<context:component-scan base-package="com.kamal"></context:component-scan>
<bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url">
<value>jdbc:mysql://localhost:3306/studentdb</value>
</property>
<property name="username"><value>root</value></property>
<property name="password"><value></value> </property>
</bean>

<bean id="studentService" class="com.kamal.service.StudentServiceImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<tx:annotation-driven transaction-manager="txManager" />
</beans>







3 comments:

  1. please provide me the CRUD operation with complete SPring Framework implementation.thanx in advance

    ReplyDelete
  2. Thank you so much ..it would be nice if you provide project as zip..or all bundle in zip..as its tedious for me to find all..thnqu anyway

    ReplyDelete
  3. remove spring-asm


    org.springframework
    spring-webmvc
    ${spring.web.version}


    spring-asm
    org.springframework


    ReplyDelete