Spring MVC 3 Controller for MyBatis CRUD operation

Spring MVC 3 Controller for MyBatis CRUD operation

Till now we have created CRUD database service for the domain class “ User” and alsointegratedMyBatis configuration with Spring Configuration file. Next, we will create an web page using Spring MVC to use MyBatis CRUD service to perform operations to database.

  1. Creating DAO class using MyBatis 3 that will help to perform CRUD operations on database.
  2. Setting Environment for integrating MyBatis 3 and Spring MVC 3 frameworks.
  3. Creating Spring MVC 3 controller for performing CRUD operation.

So, in this part we will go through following sessions that will make us able to create the user interface for the example using Spring MVC and MyBatis CRUD service:

  1. The Spring Form Validator
  2. The Spring MVC Controller
  3. The jsp page andJavaScriptfiles used to perform UI creation
  4. And the last Spring MVC configuration file

The Spring Form Validator

First of all we will see the form validator used in this example. Here is the code:

01package com.raistudies.validator;
02  
03import org.springframework.stereotype.Component;
04import org.springframework.validation.Errors;
05import org.springframework.validation.ValidationUtils;
06import org.springframework.validation.Validator;
07  
08import com.raistudies.domain.User;
09  
10@Component
11public class RegistrationValidator implements Validator {
12  
13        public boolean supports(Class<?> c) {
14                return User.class.isAssignableFrom(c);
15        }
16  
17        public void validate(Object command, Errors errors) {
18                ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "field.name.empty");
19                ValidationUtils.rejectIfEmptyOrWhitespace(errors, "standard", "field.standard.empty");
20                ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "field.age.empty");
21                ValidationUtils.rejectIfEmptyOrWhitespace(errors, "sex", "field.sex.empty");
22                User usrBean = (User)command;
23                if(!isNumber(usrBean.getAge().trim()))
24                        errors.rejectValue("age", "field.age.NAN");
25        }
26  
27        private boolean isNumber(String str){
28            for (int i = 0; i < str.length(); i++) {
29  
30                //If we find a non-digit character we return false.
31                if (!Character.isDigit(str.charAt(i)))
32                return false;
33                }
34  
35                return true;
36        }
37}

As you can see, we have put some restrictions on the form values like every field should have values and the value in “ age” field should be number. You can add more restrictions on the form values as you need from the validate() method of this class. The contain of the error message values are defined in the property file messages.properties, which is as bellow:

1field.name.empty=Name field is mandatory.
2field.standard.empty=Standard field is mandatory.
3field.age.empty=Age field is mandatory.
4field.sex.empty=Sex field is mandatory.
5  
6field.age.NAN=Age should be a number.

That is all for the form validation part, now we will see controller part.

The Spring MVC Controller

The controller will project the request from browser to MyBatis services. Bellow is the code:

01package com.raistudies.controllers;
02  
03import java.util.List;
04import java.util.UUID;
05  
06import org.springframework.beans.factory.annotation.Autowired;
07import org.springframework.stereotype.Controller;
08import org.springframework.ui.ModelMap;
09import org.springframework.validation.BindingResult;
10import org.springframework.web.bind.annotation.ModelAttribute;
11import org.springframework.web.bind.annotation.RequestMapping;
12import org.springframework.web.bind.annotation.RequestMethod;
13import org.springframework.web.servlet.ModelAndView;
14  
15import com.raistudies.domain.User;
16import com.raistudies.persistence.UserService;
17import com.raistudies.validator.RegistrationValidator;
18  
19@Controller
20@RequestMapping(value="/registration")
21public class RegistrationController {
22  
23        private RegistrationValidator validator = null;
24        private UserService userService = null;
25  
26        @Autowired
27        public void setUserService(UserService userService) {
28                this.userService = userService;
29        }
30  
31        public RegistrationValidator getValidator() {
32                return validator;
33        }
34  
35        @Autowired
36        public void setValidator(RegistrationValidator validator) {
37                this.validator = validator;
38        }
39  
40        @RequestMapping(method=RequestMethod.GET)
41        public String showForm(ModelMap model){
42                List<User> users = userService.getAllUser();
43                model.addAttribute("users", users);
44                User user = new User();
45                user.setId(UUID.randomUUID().toString());
46                model.addAttribute("user", user);
47                return "registration";
48        }
49  
50        @RequestMapping(value="/add", method=RequestMethod.POST)
51        public ModelAndView add(@ModelAttribute(value="user") User user,BindingResult result){
52                validator.validate(user, result);
53                ModelAndView mv = new ModelAndView("registration");
54                if(!result.hasErrors()){
55                        userService.saveUser(user);
56                        user = new User();
57                        user.setId(UUID.randomUUID().toString());
58                        mv.addObject("user", user);
59                }
60                mv.addObject("users", userService.getAllUser());
61                return mv;
62        }
63  
64        @RequestMapping(value="/update", method=RequestMethod.POST)
65        public ModelAndView update(@ModelAttribute(value="user") User user,BindingResult result){
66                validator.validate(user, result);
67                ModelAndView mv = new ModelAndView("registration");
68                if(!result.hasErrors()){
69                        userService.updateUser(user);
70                        user = new User();
71                        user.setId(UUID.randomUUID().toString());
72                        mv.addObject("user", user);
73                }
74                mv.addObject("users", userService.getAllUser());
75                return mv;
76        }
77  
78        @RequestMapping(value="/delete", method=RequestMethod.POST)
79        public ModelAndView delete(@ModelAttribute(value="user") User user,BindingResult result){
80                validator.validate(user, result);
81                ModelAndView mv = new ModelAndView("registration");
82                if(!result.hasErrors()){
83                        userService.deleteUser(user.getId());
84                        user = new User();
85                        user.setId(UUID.randomUUID().toString());
86                        mv.addObject("user", user);
87                }
88                mv.addObject("users", userService.getAllUser());
89                return mv;
90        }
91}

The controller is using two beans for the CRUD operations, one is RegistrationValidator that we say above to validate the form data and other is UserService that we created in our previous part using MyBatis 3 to perform database operations on the form data. Both the beans will beauto wiredby spring using setter injection.

The controller have following operation methods that handles CRUD requests on form data:

  • showForm() :This operations will show up the form for the first time that is why we have put method type as RequestMethod.GET The method will also provide all available users in database using getAllUser() method of UserService to show up on the table bellow the form.
  • add() : This operation will handle the create operation. First of all it will validate the form data and if no erroroccurthen it will save form data to database to create a new user usingsaveUser()method of UserService. It will also bind a new User object with the form.
  • update() : update method will update the user detail to the database using updateUser() method of UserService and before that it will validate the data using RegistrationValidator.
  • delete() :This method is used to delete the user from database and take helps from the deleteUser() method of UserService for this.

The jsp page and JavaScript files used to perform UI creation

In this session, we will see user interface part of the example. We are to create a web page like the following :

Spring MVC and MyBatis 3 Integration – User Form

UI functionality:

  • The “Save Changes” button will be used to create a new user or to update an existing user.
  • The “New User” button will be used to set the form to create a new user.
  • The “Delete User” button will be used to delete a user who’s details are showing in the form
  • Clicking on any row will bring the corresponding row data to form fields for update or delete.

Let us see jsp code corresponding to the web page:

01</div>
02<div>
03<pre><!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04<%@ page session="true" %>
05<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
06<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
07<html xmlns="http://www.w3.org/1999/xhtml">
08        <head>
09                <title>Hello World with Spring 3 MVC</title>
10                <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
11                <script type="text/javascript" src='<c:url value="/resources/common.js"/>'></script>
12                <script type="text/javascript" src='<c:url value="/resources/registration.js"/>'></script>
13                <script type="text/javascript">
14                        var projectUrl = '<c:url value="/"/>';
15                        if(projectUrl.indexOf(";", 0) != -1){
16                                projectUrl = projectUrl.substring(0, projectUrl.indexOf(";", 0));
17                        }
18                </script>
19        </head>
20        <body>
21                <fieldset>
22                <legend>Registration Form</legend>
23                <center>
24                <form:form commandName="user" action="/SpringMVCMyBatisCRUDExample/app/registration/add" name="userForm">
25  
26                <form:hidden path="id"/>
27                <table>
28                        <tr><td colspan="2" align="left"><form:errors path="*" cssStyle="color : red;"/></td></tr>
29                        <tr><td>Name : </td><td><form:input path="name" /></td></tr>
30                        <tr><td>Standard : </td><td><form:input path="standard" /></td></tr>
31                        <tr><td>Age : </td><td><form:input path="age" /></td></tr>
32                        <tr><td>Sex : </td><td><form:select path="sex">
33                                        <form:option value="Male"/>
34                                        <form:option value="Female"/>
35                        </form:select></td></tr>
36                        <tr><td colspan="2"><input type="submit" value="Save Changes"/>
37                        &nbsp;<input type="reset" name="newUser" value="New User" onclick="setAddForm();" disabled="disabled"/>
38                        &nbsp;<input type="submit" name="deleteUser" value="Delete User" onclick="setDeleteForm();" disabled="disabled"/></td></tr>
39                </table>
40                </form:form>
41                </center>
42                </fieldset>
43                <c:if test="${!empty users}">
44  
45                        <br />
46                        <center>
47                                <table width="90%">
48                                        <tr style="background-color: gray;">
49                                                <th>Name</th>
50                                                <th>Standard</th>
51                                                <th>Age</th>
52                                                <th>Sex</th>
53                                        </tr>
54                                        <c:forEach items="${users}" var="user">
55                                                <tr style="background-color: silver;" id="${user.id}" onclick="setUpdateForm('${user.id}');">
56                                                        <td><c:out value="${user.name}"/></td>
57                                                        <td><c:out value="${user.standard}"/></td>
58                                                        <td><c:out value="${user.age}"/></td>
59                                                        <td><c:out value="${user.sex}"/></td>
60                                                </tr>
61                                        </c:forEach>
62                                </table>
63                                </center>
64                        <br />
65  
66                </c:if>
67        </body>
68</html></pre>
69</div>
70<div>

As you can see, the default action of the form is to add the form detail to database using add method of the controller. On click of “Delete User”, it will call a JavaScript function that will change the form url to delete the user. We have used<c:forEach/> jstl for showing all the users on the table and every row hasdeclaredon click even which will bring the table row data to form and also will change the form submit url to call update() method of controller.

Spring MVC configuration file

At last we will see the Spring MVC configuration that has been using to configure the controller and all other things. Following is the configuration file :

01</div>
02<div>
03<pre><?xml version="1.0" encoding="UTF-8"?>
05        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
06        xmlns:context="http://www.springframework.org/schema/context"
07        xmlns:mvc="http://www.springframework.org/schema/mvc"
08        xsi:schemaLocation="
12  
13        <!-- Application Message Bundle -->
14        <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
15                <property name="basename" value="/WEB-INF/messages" />
16                <property name="cacheSeconds" value="3000" />
17        </bean>
18  
19        <!-- Scans the classpath of this application for @Components to deploy as beans -->
20        <context:component-scan base-package="com.raistudies" />
21  
22        <!-- Configures the @Controller programming model -->
23        <mvc:annotation-driven />
24  
25        <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
26        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
27                <property name="prefix" value="/WEB-INF/jsp/"/>
28                <property name="suffix" value=".jsp"/>
29        </bean>
30  
31        <import resource="jdbc-context.xml"/>
32</beans></pre>
33</div>
34<div>

The configuration file includes themessages.properties as resource bundle and also includejdbc-context.xml configuration files which contains configuration for integration MyBatis 3 with Spring.

While running the example you will get the above screen as out put that will also show all the records present in database. Click on the “Save Changes” button you will get following screen that will show you validation errors on the blank form values:

Spring MVC and MyBatis 3 Integration – User Form with validation errors 

Now fill the form with valid data and and click on the “Save Changes” button, it will bring the form data to bellow table.

That is all from this example. Hope that you have enjoyed the learning!! :)

  1. Creating DAO class using MyBatis 3 that will help to perform CRUD operations on database.
  2. Setting Environment for integrating MyBatis 3 and Spring MVC 3 frameworks.
  3. Creating Spring MVC 3 controller for performing CRUD operation.

You can download the source code and war file from following links:

Source (Eclipse Project without jars) :Download

War (With jars) :Download

Reference: Spring MVC 3 controller for performing CRUD operation using MyBatis(iBatis) 3 from our JCG partner Rahul Mondal at the Rai Studies blog.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值