Project Dependencies
4.0.0
com.mkyong
spring4-mvc-maven-ajax-example
war
1.0-SNAPSHOT
spring4 mvc maven ajax example
1.8
4.2.2.RELEASE
2.6.3
1.1.3
1.7.12
1.2
3.1.0
org.springframework
spring-webmvc
${spring.version}
commons-logging
commons-logging
com.fasterxml.jackson.core
jackson-core
${jackson.version}
com.fasterxml.jackson.core
jackson-databind
${jackson.version}
javax.servlet
jstl
${jstl.version}
org.slf4j
jcl-over-slf4j
${jcl.slf4j.version}
ch.qos.logback
logback-classic
${logback.version}
javax.servlet
javax.servlet-api
${servletapi.version}
provided
org.apache.maven.plugins
maven-compiler-plugin
3.3
${jdk.version}
${jdk.version}
org.eclipse.jetty
jetty-maven-plugin
9.2.11.v20150529
10
/spring4ajax
org.apache.maven.plugins
maven-eclipse-plugin
2.10
true
true
2.0
spring4ajax
org.apache.maven.plugins
maven-war-plugin
2.6
false
org.wildfly.plugins
wildfly-maven-plugin
1.1.0.Alpha5
127.0.0.1
9990
admin
admin
spring4ajax.war
Example of Spring MVC Ajax JSON Response
In this section, we will go through an example of a Spring MVC Ajax JSON response. We will cover the environment setup, coding the application, and running and testing the application.
Setting Up the Environment
To set up the environment for this example, we need to have the following software installed:
- Java Development Kit (JDK)
- Eclipse IDE
- Apache Tomcat Server
- jQuery library
Once we have installed these software, we can proceed to the next step.
Coding the Application
In this step, we will create a simple Spring MVC application that will handle an Ajax request and return a JSON response.
- Create a new Spring MVC project in Eclipse IDE.
-
In the
web.xml
file, add the following configuration:
dispatcher
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation /WEB-INF/dispatcher-servlet.xml
dispatcher
-
Create a
dispatcher-servlet.xml
file in the
WEB-INF
directory and add the following configuration:
-
Create a new controller class named
AjaxController
in the
com.example.controller
package and add the following code:
@Controller public class AjaxController { @RequestMapping(value = "/ajax", method = RequestMethod.POST) public @ResponseBody Map
handleAjaxRequest() { Map
response = new HashMap
(); response.put("name", "John Doe"); response.put("age", 30); return response; } }
-
Create a new JSP file named
index.jsp
in the
WEB-INF/views
directory and add the following code:
Spring MVC Ajax JSON Response Example
Spring MVC Ajax JSON Response Example
Name:
Age:
Running and Testing the Application
To run and test the application, follow these steps:
- Deploy the application on the Apache Tomcat server.
-
Open a web browser and navigate to
http://localhost:8080/spring-mvc-ajax-json-example/
. - The page should display the name and age retrieved from the Ajax request.
That’s it! You have successfully created a Spring MVC Ajax JSON response example.
Download Source Code
References
About Author
Comments
Thanks. tutorial solved my problem
Thanks.This tutorial solved my problem
Hi Mkyong,I always found your examples clear and good,Thanks lot!
Hey guy, what example! So far the best tutorial i’ve ever seen. Thanks!!!
Thanks for the article . I am quite late but while working on this code, I get following issue.Multiple markers at this line– PostConstruct cannot be resolvedto a type– PostConstruct cannot be resolvedto a type
Anyone know how to resolve this?
Hi, is it possible to save an image in this way? how can I do it? Do you have any example? Thank you
Thank you mkYong for providing this good example.
I am able to deploy and start jetty with this project.
But I am getting below content on hitting http://localhost:2222/spring4ajax/ not showing search page.
Could you/someone please help me here.
Directory: /spring4ajax/spring4-mvc-maven-ajax-example-1.0-SNAPSHOT.war 13184243 bytes Apr 8, 2020 3:58:31 PM
method post not allowed
how to do CRUD operating in Spring MVC in eclipse without refreshing the page and connection with database
when i “$ mvn jetty:run “in the git bush it shows “No plugin found for prefix ‘jetty”‘
Could you please explain how can i do the same if i’m sending and receiving the data in XML instead of json?
Thanks
good tutorial, but i integration in my project and show this{“readyState”: 4,“responseText”: ”Estado HTTP 405 – Request method ‘POST’ not supportedtype Informe de estado
mensaje Request method ‘POST’ not supported
descripción El método HTTP especificado no está permitido para el recurso requerido.
Pivotal tc Runtime 3.1.5.RELEASE/8.0.36.A.RELEASE“,“status”: 405,“statusText”: “Método No Permitido”}
Could you please explain to me what the “$” sign mean in the following line:
jQuery(document).ready(function($) {And also why this line doesn’t start like:$(document) ?Thanks in advance!
this is a good example, thanks.
Hi Mkyong,
I have two questions. First, How to create layout file?And other question, Can we add annotation to validation for view class. i don’t want to write isValidSearchCriteria method.
thanks.
i got the following error while i execute the code …
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
“status”: 415,
“statusText”: “Unsupported Media Type”
this is a good example, thanks.
Thanks
Hi Mkyoung,i’m getting this error :HTTP ERROR 406 Not Acceptable.
i’m sure that the ‘result’ object from ‘AjaxResponseBody’ class having a value when returned back to ajax response but i always get that error.
I’m using:– spring 4.0.2– jackson 2.6.3– jetty server
HI Mkyong,I’m uable to run this project in Tomcat 8, I mean the Tomcat starts properly with this project, but when I hit the url, it gives me 404.
Thanks,Kapil
Hi Mkyong,
Am trying to get this application up and running in JBoss AS7 but am getting a 404 when accessing http://localhost:8080/spring4ajax/search/api/getSearchResult/
I have the same issue with one of my application which works well in Tomcat but not in JBoss AS7, just wondering if there is a workaround if you know off.
Thanks
Article is updated with wildfly-maven-plugin, use this command
mvn wildfly:deploy
to deploy this web application to WildFly.
I am new in javawhere should I run this command
1. 404 is resources not found. Make sure ‘spring4ajax’ is your deployed web context.
2. If you get this example and deploy directly, the default web context will be this – http://localhst:8080/spring4-mvc-maven-ajax-example-1.0-SNAPSHOT
3. To update the WildFly web context, try this tutorial – https://mkyong.com/maven/maven-deploy-web-application-to-wildfly/
P.S This web application is tested with WildFly 9, no error.
hey guys , find given solution to compile the project.
you need to add following plugin in pom.xml
maven-war-plugin
2.4
false
Hope it would work for you guys , cheers 🙂
Thanks, article is updated with maven-war-plugin.
still can not work please help.HTTP Status 500 – An exception occurred processing JSP page /welcome.jsp at line 11
can you try that link after starting jetty servermake sure your port should not be used before.http://localhost:8080/spring4ajax/
It is not compiling:
Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1]
Fixed, article is updated with maven-war-plugin.
Raul ,add this in your pom.xml
maven-war-plugin
2.4
false
Jeez, this is not a tutorial, but rather a template. It’s 400+ lines of code and merely a dozen lines of explanation.
Where is the web.xml file ? I have the following error:
org.xml.sax.SAXParseException; systemId: file:/C:/DEV/apache-tomcat-8.0.28/webapps/spring4-mvc-maven-ajax-example-1.0-SNAPSHOT/WEB-INF/web.xml; lineNumber: 1; columnNumber: 2; Premature end of file.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(Unknown Source)at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(Unknown Source)at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
For servlet container >= 3, web.xml is option. Code is updated, try clone the source code from GitHub again.
you need to add following plugin in pom.xml
maven-war-plugin
2.4
false
Hi Mkyong,
I reckon that you will find that using my library http://www.ajaxanywhere.com makes things a lot easier with a far more maintainable outcome. Ajaxanywhere is intended to provide declarative Ajax for apps that use server side rendering. Because it is declarative, by using HTML markup, you will find that you use very llittle to none javascript code. Please have a look at the examples: http://examples.ajaxanywhere.comI would appreciate your feedback a lot!Thanks!
Good stuff, but you should keep it more simple. Some details are not really needed here. For example, the @JsonView annotation only confused me more untill I figured it has nothing to do with the scope of this presentation. Just skip it.Also, some details are maybe missing. For example, in order to work, I had to add an extention in ajax url (“url: getSearchResult.ext”) and then add this in web.xml:
dispatcher*.ext
servlet-mappingservlet-name dispatcher /servlet-nameurl-pattern *.ext /url-pattern/servlet-mapping
Spring MVC – Refactoring a jQuery Ajax Post example
Reviewing a jQuery Ajax form POST and Spring MVC example, find out the following patterns :
In Spring MVC, use
@RequestParam
to accept the Ajax POST data.
@RequestMapping(value = "/path-to/hosting/save", method = RequestMethod.POST) @ResponseBody public String saveHosting( @RequestParam int id, @RequestParam String domain, @RequestParam String name, @RequestParam String desc, @RequestParam String tags, @RequestParam String afflink, @RequestParam boolean display, @RequestParam boolean hosting, @RequestParam boolean cdn, @RequestParam boolean paas, @RequestParam String imageUrl, @RequestParam String favUrl, @RequestParam String whoisPattern ) { //...do something }
The above code is working fine, just a bit weird and hard to maintain. Both Javascript
$.post
and Spring MVC
@RequestParam
is dealing with too many parameters.
You just search Person: ” + data.name + “
“; $(“#ajax-response”).html(result); } else { var result = “
No person found
“; $(“#ajax-response”).html(result); } }, error : function(e) { console.log(“ERROR: “, e); } }); }