If you are developing a Rich Internet application using any of modern JavaScript MVC framework (like ExtJS etc) then you usually send an Asynchronous request to server and get the request processed. If you send an Ajax request with some parameter, on server side you will get that parameter values by request.getParameter() method. Sending multiple parameter may need to invoke getParameter method multiple times to get the param values.
Fortunately, SpringMVC comes with a very handy annotation @RequestBody which can be used to convert your incoming Json request to Model object. You just need to add @RequestBody annotation with your controller method and Spring will automatically convert all incoming Json request (application/json) into Model object defined in controller method. Optionally we can use @Valid or @Validate annotation to invoke automatic validation. In such a case Spring automatically performs the validation and in case of error MethodArgumentNotValidException is thrown.
Let me show you today how we can send a Json request to SpringMVC and use @RequestBody annotation to convert Json request into Domain model. Spring v3.x uses MappingJackson2HttpMessageConverter class as an Implementation of HttpMessageConverter that can read and write JSON using Jackson 2.x’s ObjectMapper. Please make sure you need Jackson-all-xx.jar library into classpath to make it happens.
I am using XML-Free approach to create this example.
First, create a Bootstrap class which implements WebApplicationInitializer interface.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
package org.techzoo.springmvc.bootstrap;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class MyWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(final ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.setServletContext(servletContext);
root.scan(“org.techzoo.springmvc.bootstrap”);
root.refresh();
final Dynamic servlet = servletContext.addServlet(“spring”, new DispatcherServlet(root));
servlet.setLoadOnStartup(1);
servlet.addMapping(“/*”);
}
}
|
Now, Controller configuration class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
package org.techzoo.springmvc.bootstrap;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = “org.techzoo.springmvc.controller”)
public class ControllerConfiguration extends WebMvcConfigurerAdapter {
@Bean
public InternalResourceViewResolver configureInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix(“/WEB-INF/views/”);
resolver.setSuffix(“.jsp”);
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(“/js/**”).addResourceLocations(“/js/”);
}
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable(“spring”);
configurer.enable();
}
}
|
Now we need a Request and Response Body Class as Follows.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
package org.techzoo.springmvc.vo;
public class UserVO {
private String name,pwd;
public UserVO(){}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getPwd() {return pwd;}
public void setPwd(String pwd) {this.pwd = pwd;}
@Override
public String toString()
{ return String.format(“User [%s, %s]”, name, pwd);}
}
|
Generic ResponseVO class used to capture response returning from Controller method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
package org.techzoo.springmvc.vo;
/**
* Author: Tousif Khan
**/
public class ResponseVO {
private boolean success;
private String message;
public ResponseVO(){}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
|
Spring Controller used to handle Request-Response flow.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
package org.techzoo.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.techzoo.springmvc.vo.ResponseVO;
import org.techzoo.springmvc.vo.UserVO;
@Controller
public class MyController {
@RequestMapping(value = “/index”)
public String index()
{
return “index”;
}
@RequestMapping (value = “/userAuthenticate”, method = RequestMethod.POST)
public @ResponseBody ResponseVO userAuthenticate(@RequestBody UserVO userVo)
{
ResponseVO respVo = new ResponseVO();
if(userVo.getName().equals(“tousif”))
{
respVo.setSuccess(true);
respVo.setMessage(“User is Authenticated”);
}
else
{
respVo.setSuccess(false);
respVo.setMessage(“User is Unauthenticated”);
}
return respVo;
}
}
|
And Now ExtJS Login Window.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
Ext.onReady(function() {
Ext.define(‘org.techzoo.LoginForm’, {
extend : ‘Ext.form.Panel’,
bodyPadding : 10,
width : 280,
frame : true,
title : ‘User Authentication’,
items : [ {
xtype : ‘textfield’,
name : ‘name’,
allowBlank : false,
msgTarget : ‘side’,
fieldLabel : ‘Name‘
}, {
xtype : ‘textfield’,
name : ‘pwd’,
allowBlank : false,
msgTarget : ‘side’,
minLength : 6,
fieldLabel : ‘Password‘,
inputType : ‘password’
}],
dockedItems : [{
xtype : ‘toolbar’,
padding : ‘2 0 2 0’,
dock : ‘bottom’,
ui : ‘footer’,
items : [{
xtype : ‘tbfill’
},{
text : ‘Authenticate User’,
listeners : {
click : function(btn) {
var frm = btn.up(‘form’);
if (frm.getForm().isValid()) {
Ext.Ajax.request({
url : ‘/SpringXMLFree/userAuthenticate’,
method: ‘POST’,
jsonData: frm.getForm().getValues(),
success : function(resp) {
var response = Ext.decode(resp.responseText);
if(response != null && response.success)
{
Ext.Msg.show({
title:‘User Authentication’,
msg: response.message,
icon: Ext.window.MessageBox.INFO,
buttons: Ext.Msg.OK
});
}
else if(response != null && !response.success)
{
Ext.Msg.show({
title:‘User Authentication’,
msg: response.message,
icon: Ext.window.MessageBox.ERROR,
buttons: Ext.Msg.OK
});
}
}
});
}
}//click
}
}]
}],
});
Ext.create(‘org.techzoo.LoginForm’, {renderTo : ‘output’});
});
|
The Output will look similar to following…
Download Source code (size: 17.7 Kb without jars)
Source techzoo.org