See the below steps to create sample application using JQuery, Spring MVC @RequestBody and JSON :
1- Define dependency for Spring, JSON in pom.xml as below:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Demo</groupId>
<artifactId>Demo</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>Demo</name>
<description></description>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.0</version>
<configuration>
<webResources>
<resource>
<directory>WebContent</directory>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<spring.version>3.0.5.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</project>
2- Now define the model class for binding data as below:
User.java
package com.evon.model.user;
import java.io.Serializable;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class UserModel implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@JsonProperty
private Integer userId;
@JsonProperty
private String emailId;
@JsonProperty
private String password;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3- Define response class as below:
UserResponse.class
package com.evon.model.response;
import java.io.Serializable;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class UserResponse implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@JsonProperty
private String status ;
@JsonProperty
private String error ;
@JsonProperty
private String message;
private String errorType;
private Boolean success;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
/**
* @param errorType the errorType to set
*/
public void setErrorType(String errorType) {
this.errorType = errorType;
}
/**
* @return the errorType
*/
public String getErrorType() {
return errorType;
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
}
4- Now define registerUser function in your controller as below:
LoginController.java
import com.evon.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.flippadoo.model.response.UserResponse;
import com.flippadoo.model.user.UserModel;
@Controller
public class LoginController {
@RequestMapping(value = "/addPerson",
method = RequestMethod.POST,
headers = {"Content-type=application/json"})
@ResponseBody
Public UserResponse registerUser(HttpServletRequest request, HttpServletResponse response)
throws Exception {
UserResponse response = new UserResponse();
response.setStatus("Ok");
response.setMessage("User created successfully");
return response;
}
}
5- Define the below configuration in you servlet.xml file as below:
demo-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.evon.controller" />
<mvc:annotation-driven />
</beans>
6- web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>SpringExamples</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
7- Now define jsp page as below:
createUser.jsp
<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Registration Form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
//Ajax submit create user
function ajaxSubmitCreateUserForm()
{
$('#createUser').ajaxForm({
url: 'registerUser',
type: "POST",
data: JSON.stringify({ firstName: "Akash", lastName: "Singh", emailId: "akash@gmail.com" }),
contentType: 'application/json',
success: function(response) {
if(response.status == 'OK')
{
alert("User/Developer is created");
}
else
{
alert("FAILED, Try again ...");
}
},
error : function() { alert('System error occured, please try again ...'); }
});
$('#createUser').submit();
}
</script>
</head>
<body>
<div class="wrapper">
<div class="formContainer">
<form:form name="createUser" id="createUser" method="post" onsubmit="return false;">
<h2>User Create Form</h2>
<dl>
<dt>
Email
</dt>
<dd>
<input type="text" name="emailId" id="emailId" required="required">
<span class="separate">Please provide valid Email id</span>
</dd>
<dt>
First Name
</dt>
<dd>
<input type="text" name="firstName" id="firstName" required="required">
</dd>
<dt>
Last Name
</dt>
<dd>
<input type="text" name="lastName" id="lastName" required="required">
</dd>
</dl>
<div class="buttonBlock">
<button class="submitBTN" onclick="ajaxSubmitCreateUserForm();">Submit</button>
</div>
</form:form>
</div>
</div>
</body>
</html>
Hope this will help you :)
0 Comment(s)