您的位置:首页 > 编程语言 > Java开发

Spring MVC 3 Controller for MyBatis CRUD operation

2013-10-31 00:27 405 查看

Spring MVC 3 Controller for MyBatis CRUD operation

by
Rahul Mondal
on May 3rd,2012
| Filed in:
Enterprise Java
Tags: CRUD,MyBatis,Spring,
Spring MVC

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.

Creating
DAO class using MyBatis 3 that will help to perform CRUD operations on database.
Setting Environment for
integrating MyBatis 3 and Spring MVC 3 frameworks.
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:

The Spring Form Validator
The Spring MVC Controller
The jsp page andJavaScriptfiles used to perform UI creation
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:

view source

print?

01
package
com.raistudies.validator;
02
 
 
03
import
org.springframework.stereotype.Component;
04
import
org.springframework.validation.Errors;
05
import
org.springframework.validation.ValidationUtils;
06
import
org.springframework.validation.Validator;
07
 
 
08
import
com.raistudies.domain.User;
09
 
 
10
@Component
11
public
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:

view source

print?

1
field.name.empty=Name field is mandatory.
2
field.standard.empty=Standard field is mandatory.
3
field.age.empty=Age field is mandatory.
4
field.sex.empty=Sex field is mandatory.
5
 
 
6
field.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:

view source

print?

01
package

com.raistudies.controllers;
02
 
 
03
import

java.util.List;
04
import

java.util.UUID;
05
 
 
06
import

org.springframework.beans.factory.annotation.Autowired;
07
import

org.springframework.stereotype.Controller;
08
import

org.springframework.ui.ModelMap;
09
import

org.springframework.validation.BindingResult;
10
import

org.springframework.web.bind.annotation.ModelAttribute;
11
import

org.springframework.web.bind.annotation.RequestMapping;
12
import

org.springframework.web.bind.annotation.RequestMethod;
13
import

org.springframework.web.servlet.ModelAndView;
14
 
 
15
import
com.raistudies.domain.User;
16
import

com.raistudies.persistence.UserService;
17
import

com.raistudies.validator.RegistrationValidator;
18
 
 
19
@Controller
20
@RequestMapping
(value=
"/registration"
)
21
public
class
RegistrationController {
22
 
 
23
        
private

RegistrationValidatorvalidator = 
null
;
24
        
private

UserService userService =
null
;
25
 
 
26
        
@Autowired
27
        
public

void
setUserService(UserService userService) {
28
                
this
.userService = userService;
29
        
}
30
 
 
31
        
public

RegistrationValidatorgetValidator() { 
32
                
return

validator;
33
        
}
34
 
 
35
        
@Autowired
36
        
public

void
setValidator(RegistrationValidatorvalidator) {
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:

view source

print?

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

type
=
"reset"

name
=
"newUser"

value
=
"New User"

onclick
=
"setAddForm();"

disabled
=
"disabled"
/>
38
                        
 <
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 :

view source

print?

01
</
div
>
02
<
div
>
03
<
pre
><?
xml

version
=
"1.0"

encoding
=
"UTF-8"
?>
04
<
beans

xmlns
=
"http://www.springframework.org/schema/beans"
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="
09
                
http://www.springframework.org/schema/beans    
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
10
                
http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd
11
                
http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
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!!


Creating
DAO class using MyBatis 3 that will help to perform CRUD operations on database.
Setting Environment for
integrating MyBatis 3 and Spring MVC 3 frameworks.
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: