Chuyển tới nội dung
Home » Spring Mvc Ajax Json | Jquery Ajax

Spring Mvc Ajax Json | Jquery Ajax

How to integrate JQuery Ajax POST/GET & Spring MVC | Spring Boot | Java Techie

Spring Components

Only the important classes will be displayed.

4.1

@RestController

to handle the Ajax request. Read the comments for self-explanatory.


package com.mkyong.web.controller; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.annotation.JsonView; import com.mkyong.web.jsonview.Views; import com.mkyong.web.model.AjaxResponseBody; import com.mkyong.web.model.SearchCriteria; import com.mkyong.web.model.User; @RestController public class AjaxController { List

users; // @ResponseBody, not necessary, since class is annotated with @RestController // @RequestBody - Convert the json data into object (SearchCriteria) mapped by field name. // @JsonView(Views.Public.class) - Optional, filters json data to display. @JsonView(Views.Public.class) @RequestMapping(value = "/search/api/getSearchResult") public AjaxResponseBody getSearchResultViaAjax(@RequestBody SearchCriteria search) { AjaxResponseBody result = new AjaxResponseBody(); if (isValidSearchCriteria(search)) { List

users = findByUserNameOrEmail(search.getUsername(), search.getEmail()); if (users.size() > 0) { result.setCode("200"); result.setMsg(""); result.setResult(users); } else { result.setCode("204"); result.setMsg("No user!"); } } else { result.setCode("400"); result.setMsg("Search criteria is empty!"); } //AjaxResponseBody will be converted into json format and send back to the request. return result; } private boolean isValidSearchCriteria(SearchCriteria search) { boolean valid = true; if (search == null) { valid = false; } if ((StringUtils.isEmpty(search.getUsername())) && (StringUtils.isEmpty(search.getEmail()))) { valid = false; } return valid; } // Init some users for testing @PostConstruct private void iniDataForTesting() { users = new ArrayList

(); User user1 = new User("mkyong", "pass123", "[email protected]", "012-1234567", "address 123"); User user2 = new User("yflow", "pass456", "[email protected]", "016-7654321", "address 456"); User user3 = new User("laplap", "pass789", "[email protected]", "012-111111", "address 789"); users.add(user1); users.add(user2); users.add(user3); } // Simulate the search function private List

findByUserNameOrEmail(String username, String email) { List

result = new ArrayList

(); for (User user : users) { if ((!StringUtils.isEmpty(username)) && (!StringUtils.isEmpty(email))) { if (username.equals(user.getUsername()) && email.equals(user.getEmail())) { result.add(user); continue; } else { continue; } } if (!StringUtils.isEmpty(username)) { if (username.equals(user.getUsername())) { result.add(user); continue; } } if (!StringUtils.isEmpty(email)) { if (email.equals(user.getEmail())) { result.add(user); continue; } } } return result; } }






4.2 The “json data” will be converted into this object, via

@RequestBody

.


package com.mkyong.web.model; public class SearchCriteria { String username; String email; //getters and setters }

4.2 Create a dummy class for

@JsonView

, to control what should be returned back to the request.


package com.mkyong.web.jsonview; public class Views { public static class Public {} }

4.3 User object for search function. Fields which annotated with

@JsonView

will be displayed.


package com.mkyong.web.model; import com.fasterxml.jackson.annotation.JsonView; import com.mkyong.web.jsonview.Views; public class User { @JsonView(Views.Public.class) String username; String password; @JsonView(Views.Public.class) String email; @JsonView(Views.Public.class) String phone; String address; //getters, setters and contructors }

4.4 This object will be converted into json format and return back to the request.


package com.mkyong.web.model; import java.util.List; import com.fasterxml.jackson.annotation.JsonView; import com.mkyong.web.jsonview.Views; public class AjaxResponseBody { @JsonView(Views.Public.class) String msg; @JsonView(Views.Public.class) String code; @JsonView(Views.Public.class) List

result; //getters and setters }

The


@JsonViewbelongs to Jackson library, not Spring framework.

jQuery Ajax

In JSP, create a simple search form and send the form request with jQuery

$.ajax

.


<%@page session="false"%> <%@taglib prefix="spring" uri="http://www.springframework.org/tags"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Search Form



How to integrate JQuery Ajax POST/GET & Spring MVC | Spring Boot | Java Techie
How to integrate JQuery Ajax POST/GET & Spring MVC | Spring Boot | Java Techie

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.

  1. Create a new Spring MVC project in Eclipse IDE.
  2. In the

    web.xml

    file, add the following configuration:




dispatcher


org.springframework.web.servlet.DispatcherServlet

contextConfigLocation /WEB-INF/dispatcher-servlet.xml



dispatcher


  1. Create a

    dispatcher-servlet.xml

    file in the

    WEB-INF

    directory and add the following configuration:
  1. 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; } }



  1. Create a new JSP file named

    index.jsp

    in the

    WEB-INF/views

    directory and add the following code:


<br /> Spring MVC Ajax JSON Response Example<br />

Spring MVC Ajax JSON Response Example

Name:

Age:



Running and Testing the Application

To run and test the application, follow these steps:

  1. Deploy the application on the Apache Tomcat server.
  2. Open a web browser and navigate to

    http://localhost:8080/spring-mvc-ajax-json-example/

    .
  3. 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.

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

JSON and Ajax in Spring MVC Framework
JSON and Ajax in Spring MVC Framework

Ajax JSON Response in Spring MVC

Spring MVC provides an easy way to handle Ajax requests and send JSON responses. In this section, we will discuss how to configure Ajax in Spring MVC and create JSON responses.

Configuring Ajax in Spring MVC

To handle Ajax requests in Spring MVC, we need to configure the

DispatcherServlet

to enable handling of annotated controllers. We can do this by adding the following configuration in the

web.xml

file:




dispatcher


org.springframework.web.servlet.DispatcherServlet

contextConfigLocation /WEB-INF/spring/dispatcher-servlet.xml



dispatcher


Next, we need to create a Spring controller to handle the Ajax request. We can annotate the controller method with

@RequestMapping

and

@ResponseBody

to indicate that the method should handle Ajax requests and return a JSON response.

Creating JSON Response

To create a JSON response in Spring MVC, we can use the

@ResponseBody

annotation. This annotation indicates that the method should return the response body directly to the client instead of rendering a view.

We can create a JSON response by returning a Java object that can be serialized to JSON. Spring MVC will automatically serialize the object to JSON and send it as the response body.

Here’s an example of a Spring controller method that returns a JSON response:


@RequestMapping(value = "/getPerson", method = RequestMethod.GET) @ResponseBody public Person getPerson() { Person person = new Person(); person.setName("John"); person.setAge(30); return person; }

In this example, we create a

Person

object and set its name and age. We then return the

Person

object, which Spring MVC will automatically serialize to JSON and send as the response body.

In conclusion, Spring MVC provides an easy way to handle Ajax requests and send JSON responses. By configuring the

DispatcherServlet

and using the

@ResponseBody

annotation, we can create controllers that handle Ajax requests and return JSON responses.

Get ahead

VMware offers training and certification to turbo-charge your progress.

Learn more

In my last entry, I walked you through several enhancements in Spring 3 for web application development. A number of you expressed interest in a follow-up entry focused on Ajax remoting. Spring 3 provides a lot in this area to take advantage of. Read on, and I’ll walk you through it.

For the purposes of this article, when I say Ajax, I’m talking about the web browser’s ability to communicate with a web server asynchronously using JavaScript. On the server-side, Spring provides the programming model for defining web services, including services consumed by JavaScript clients. On the client-side, nobody rolls their own Ajax framework these days, either. Most use an established JavaScript framework such as jQuery or Dojo.

Until version 3, Spring did not ship support for Ajax remoting. That didn’t stop our users from extending Spring to get it, or integrating other options themselves. Some used DWR, especially in the period before the rise of the JavaScript frameworks. More recently, REST-style remoting with JSON as the data exchange format has become more popular, especially because jQuery and co. make it so easy to do.

Now that Spring 3 is out, official support for Ajax remoting with JSON is provided as part of Spring MVC. This includes support for generating JSON responses and binding JSON requests using the Spring MVC @Controller programming model. In this article, I’m going to focus on using this support to implement several Ajax use cases. Like my last post, I’ll do this by walking you through a sample application you can experiment with yourself.

mvc-ajax has been designed to illustrate Spring MVC’s JSON support. The project is available in our spring-samples Subversion repository, is buildable with Maven, and is importable into STS / Eclipse. mvc-ajax has the same structure as the mvc-basic project presented in my previous entry. In fact, the Spring configuration is identical between the two.

Start your review by deploying the project to your servlet container and accessing the welcome page at localhost:8080/mvc-ajax. Since I use STS, I did this by first importing the project into the IDE, then deploying it to the built-in Tomcat / tc-server instance.

From the welcome page, activate the “Ajax @Controller Example” link. You will see a form to create a new Account. When you tab out of the Name field, your browser will ask the server if the name you just entered is available. If it is not, an error message will be displayed and the form will remain disabled until you enter a name that is available. The client-side JavaScript handling this resides in /WEB-INF/views/account/createForm.jsp and looks like:


$(document).ready(function() { // check name availability on focus lost $('#name').blur(function() { checkAvailability(); }); }); function checkAvailability() { $.getJSON("account/availability", { name: $('#name').val() }, function(availability) { if (availability.available) { fieldValidated("name", { valid : true }); } else { fieldValidated("name", { valid : false, message : $('#name').val() + " is not available, try " + availability.suggestions }); } }); }

Nothing Spring-specific here, just standard jQuery JavaScript.

On the server-side, the Controller for the account/availability resource is standard Java with some Spring MVC annotations:


@RequestMapping(value="/availability", method=RequestMethod.GET) public @ResponseBody AvailabilityStatus getAvailability(@RequestParam String name) { for (Account a : accounts.values()) { if (a.getName().equals(name)) { return AvailabilityStatus.notAvailable(name); } } return AvailabilityStatus.available(); }

AvailabilityStatus is a plain Java Value Object with two properties: an availability flag that tells the client if the user name is available, and an array of alternatives to suggest if the name you want is not available. The @ResponseBody annotation instructs Spring MVC to serialize the AvailabilityStatus to the client. Spring MVC automatically serializes to JSON because the client accepts that content type.

Underneath the covers, Spring MVC delegates to a HttpMessageConverter to perform the serialization. In this case, Spring MVC invokes a MappingJacksonHttpMessageConverter built on the Jackson JSON processor. This implementation is enabled automatically when you use the mvc:annotation-driven configuration element with Jackson present in your classpath.

Pretty cool, huh? Try creating an Account, then creating another one with the same name. You should see an error message suggesting alternate names. Turn on Firefox’s Firebug or Safari’s Web Inspector to debug the asynchronous interaction.

Spring MVC also provides support for sending JSON to the server. I have found the need for this to be less common, simply because posting form parameters is often sufficient. Nevertheless, JSON provides a flexible data-interchange format that richer JavaScript clients can conveniently work with. The ability to map JSON to a server-side Java Object for processing can be a useful feature in those cases.

In the sample, a JavaScript event handler intercepts the form submit event and posts the form data as JSON. The server returns the id of the newly created Account, which is then used to display a modal confirmation dialog:


$("#account").submit(function() { var account = $(this).serializeObject(); $.postJSON("account", account, function(data) { $("#assignedId").val(data.id); showPopup(); }); return false; });

On the server-side, the Controller is more standard Java with Spring MVC annotations:


@RequestMapping(method=RequestMethod.POST) public @ResponseBody Map

create(@RequestBody Account account, HttpServletResponse response) { Set

> failures = validator.validate(account); if (!failures.isEmpty()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return validationMessages(failures); } else { accounts.put(account.assignId(), account); return Collections.singletonMap("id", account.getId()); } }


Here, the @RequestBody annotation instructs Spring MVC to map the body of the HTTP request to an Account object. Spring MVC knows to map from JSON because the client set the request Content Type to application/json.

The create method also validates the Account object. If there are validation errors, a HTTP 400 is returned with the error messages, otherwise a HTTP 200 is returned with the assigned account ID.

Spring 3 provides first-class Ajax support with JSON as part of the Spring MVC module. This includes support for generating JSON responses and binding JSON requests using the Spring MVC @Controller programming model in conjunction with the Jackson JSON processor. In this article, I showed you how this support works. I hope you found this post useful, and look forward to hearing more of your experiences putting Spring 3 to work in your own applications!

SpringMVC - Ajax and JSON
SpringMVC – Ajax and JSON

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


<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″
pageEncoding=”ISO-8859-1″%>
<%@taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core”%>

//CanvasjsChartController.java
package com.canvasjs.chart.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping(“/canvasjschart”)
public class CanvasjsChartController {
@RequestMapping(method = RequestMethod.GET)
public String springMVC(ModelMap modelMap) {
return “chart”;
}
}
//RestController.java
package com.canvasjs.chart.controllers;
import org.springframework.beans.factory.annotation.Autowired;
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 javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.canvasjs.chart.services.CanvasjsChartService;
@Controller
@RequestMapping(value = “/restfull-service”)
public class RestController extends HttpServlet {
private static final long serialVersionUID = 1L;
@Autowired
private CanvasjsChartService canvasjsChartService;
@RequestMapping(value = “/letter-frequency-of-vowels-in-english.json”, method = RequestMethod.GET)
public @ResponseBody String getDataPoints(HttpServletRequest request, HttpServletResponse response) throws Exception {
return canvasjsChartService.getCanvasjsChartData();
}
}

//CanvasjsChartService.java
package com.canvasjs.chart.services;
public interface CanvasjsChartService {
String getCanvasjsChartData();
}
//CanvasjsChartServiceImpl.java
package com.canvasjs.chart.services;
import org.springframework.beans.factory.annotation.Autowired;
import com.canvasjs.chart.daos.CanvasjsChartDao;
public class CanvasjsChartServiceImpl implements CanvasjsChartService {
@Autowired
private CanvasjsChartDao canvasjsChartDao;
public void setCanvasjsChartDao(CanvasjsChartDao canvasjsChartDao) {
this.canvasjsChartDao = canvasjsChartDao;
}
@Override
public String getCanvasjsChartData() {
return canvasjsChartDao.getCanvasjsChartData();
}
}

//CanvasjsChartDao.java
package com.canvasjs.chart.daos;
public interface CanvasjsChartDao {
String getCanvasjsChartData();
}
//CanvasjsChartDaoImpl.java
package com.canvasjs.chart.daos;
import com.canvasjs.chart.data.CanvasjsChartData;
public class CanvasjsChartDaoImpl implements CanvasjsChartDao {
@Override
public String getCanvasjsChartData() {
return CanvasjsChartData.getCanvasjsDataList();
}
}

//CanvasjsChartData.java
package com.canvasjs.chart.data;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONArray;
public class CanvasjsChartData {
static JSONArray json = null;
static {
try {
json = readJsonFromUrl(“https://canvasjs.com/data/gallery/spring-mvc/letter-frequency-of-vowels-in-english.json”);
} catch (Exception e) {
e.printStackTrace();
}
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONArray readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName(“UTF-8”)));
String jsonText = readAll(rd);
JSONArray json = new JSONArray(jsonText);
return json;
} finally {
is.close();
}
}
public static String getCanvasjsDataList() {
return json.toString();
}
}

I have two entities: Word and Notebook. I’m trying to save word to the database using

jQuery ajax method.

Spring MVC can be setup to automatically bind incoming JSON string into a Java object and it works great. But there is a question associated with foreign key. What if my Word entity depends on Notebook entity.

Here is how i sent request to Controller


$.ajax({ type: "POST", url: "/doAddWord", data: JSON.stringify({ word: word, translation: translation, transcription: transcription, example: examples }), contentType: 'application/json', success: function() { alert('success'); } });

Here is method in controller:


@RequestMapping(value = "/doAddWord", method = RequestMethod.POST, headers = {"Content-type=application/json"}) @ResponseBody public void addWord(@RequestBody Word word, HttpSession session) { Integer userId = (Integer)session.getAttribute("userId"); Notebook notebook = notebookService.findByName("default", userId); word.setNotebook(notebook); wordService.add(word); }

So as you can see in my Controller i get notebook from data base by notebook name (now it is hardcoded “default”) and by user id. In my jquery code i should send notebook name. I can not just add notebook name to my json cause i’m getting 500 Erorr and cause it’s not just String it is Object.

Is there any way how to send to controller multi data: json and some value or may be some other tips how i can implement it.

Thanks in advance.

score:51

hey enjoy the following code.

javascript ajax call


function searchtext() { var search = { "pname" : "bhanu", "lname" :"prasad" } $.ajax({ type: "post", contenttype : 'application/json; charset=utf-8', datatype : 'json', url: "/gdirecotry/ajax/searchuserprofiles.html", data: json.stringify(search), // note it is important success :function(result) { // do what ever you want with data } }); }

spring controller code


requestmapping(value="/gdirecotry/ajax/searchuserprofiles.htm",method=requestmethod.post) public @responsebody string getsearchuserprofiles(@requestbody search search, httpservletrequest request) { string pname = search.getpname(); string lname = search.getlname(); // your logic next }

following search class will be as follows


class search { private string pname; private string lname; // getter and setters for above variables }

advantage of this class is that, in future you can add more variables to this class if needed.
eg. if you want to implement sort functionality.

score:-3


u take like this var name=$("name").val(); var email=$("email").val(); var obj = 'name='+name+'&email'+email; $.ajax({ url:"simple.form", type:"get", data:obj, contenttype:"application/json", success:function(response){ alert(response); }, error:function(error){ alert(error); } });

spring controller


@requestmapping(value = "simple", method = requestmethod.get) public @responsebody string emailcheck(@requestparam("name") string name, @requestparam("email") string email, httpsession session) { string meaaseg = "success"; return meaaseg; }

score:0

i hope, you need to include the datatype option,


datatype: "json"

and you could get the form data in controller as below,


public @responsebody string getsearchuserprofiles(@requestparam("pname") string pname ,httpservletrequest request) { //here i got null value }

score:0

if you can manage to pass your whole json in one query string parameter then you can use rest template on the server side to generate object from json, but still its not the optimal approach

score:8

use this method if you dont want to make a class you can directly send json without stringifying. use default content type.
just use

@requestparam

instead of

@requestbody

.

@requestparam

name must be same as in

json

.

ajax call


function searchtext() { var search = { "pname" : "bhanu", "lname" :"prasad" } $.ajax({ type: "post", /*contenttype : 'application/json; charset=utf-8',*/ //use default contenttype datatype : 'json', url: "/gdirecotry/ajax/searchuserprofiles.htm", data: search, // note it is important without stringifying success :function(result) { // do what ever you want with data } });

spring controller


requestmapping(value="/gdirecotry/ajax/searchuserprofiles.htm",method=requestmethod.post) public @responsebody string getsearchuserprofiles(@requestparam string pname, @requestparam string lname) { string pnameparameter = pname; string lnameparameter = lname; // your logic next }

Source: stackoverflow.com

Related Query
  • How to pass Json object from ajax to spring mvc controller?
  • How to pass hidden value from jQuery to Spring MVC controller without Ajax
  • How to pass FormData and JSON object in ajax to Spring MVC Controller?
  • How to pass parameter from ajax to spring mvc controller
  • How to pass array in jquery ajax call and how to receive same from spring mvc controller
  • Pass json object to Spring mvc controller using Ajax
  • Spring MVC / JSP – How to pass nested list of object to controller from a select form
  • pass JSON object from javascript function to a java controller class using spring MVC
  • Spring MVC : How to pass Model object from one method in controller to another method in same controller?
  • How to pass model attributes from one Spring MVC controller to another controller?
  • Pass array data from javascript in browser to spring mvc controller using ajax
  • How to use Spring MVC @JsonView when returning an object hierarchy from a Rest Controller
  • Spring MVC & JSP: How to pass a parameter from the controller to JSP?
  • How to pass an object from Spring 3.0 controller to JSP view and test with JSTL
  • How do I render a JSON view/response via AJAX using Spring MVC annotation-based controller for portlets?
  • Ajax pass a “Map” object to Spring MVC Controller
  • How to Pass List using Ajax call to Spring MVC Controller
  • how to pass a java object from jsp to spring controller on clicking a link
  • How to return Bean class Object as JSON in Rest Controller in Spring MVC
  • Returning model object from Controller to Ajax jquery not working in Spring mvc
  • How to pass the object from one controller to another in Spring without using Session
  • In Spring MVC How to get form object in JSP from controller ?
  • Pass array of arrays from javascript to spring mvc controller using ajax
  • return json object list from spring mvc controller
  • How to pass array variable from view to controller in spring mvc
  • How to get the multiple data objects from ajax to my controller in spring mvc
  • How to pass JSON array from AngularJS Controller to the Spring Controller?
  • How to pass data to browser javascript from Spring MVC controller
  • How to pass list containing hash map from jsp to controller on page submit in spring mvc
  • Spring MVC – how to pass an inheriting type from jsp to controller
More Query from same tag
  • To do Spring MVC Framework , Eclipse indigo is enough to do the project based Spring MVC?
  • Spring MVC – SEVERE: Exception starting filter Spring OpenEntityManagerInViewFilter
  • Spring Ldap LDAP: error code 32 – 0000208D
  • NullPointerException at org.springframework.security.web.FilterChainProxy.getFilters
  • Case-insensitive query string request parameters
  • How to directly visit JSP pages with Spring loaded?
  • Arithmetic Operation in Thymeleaf
  • Is it good practice to throw exception from DAO layer to controller?
  • Mixing Java Config and XML Spring 4
  • Java Map issue in Spring MVC
  • File not found Issue with Spring project
  • HTTP Status 500 – Expected session attribute ‘consent’
  • How to reduce database query when using stateless framework like Spring MVC
  • How to validate the size of @RequestParam of type List
  • JSON request formatting issue
  • org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter doesn’t have the setAlwaysUseFullPath method
  • Wrong time when using @JsonFormat (+1 hour)
  • Spring MVC 3 Return Content-Type: text/plain
  • Swagger-Codegen/Spring-MVC: Where are the mustache files filled?
  • Spring MVC External JS not working
  • BeanCreationException throwed when trying to run my project
  • JPA – ConstraintViolationException on delete
  • ModelAttribute object fields are null in the controller
  • Duplicate entry exception hibernate
  • Spring MVC exception handling with HandlerExceptionResolver
  • Could not Upload File using MongoDb GridFs
  • File location listener in Java – Spring application
  • How to solve “org.springframework.dao.DataIntegrityViolationException: could not execute query; SQL”
  • How to use specific custom objectMapper/JsonSerializer for specific requestMapping
  • Convert fields before sending to the page

You just add new Person

” + “Name: ” + data.name + “
” + “Age: ” + data.age; $(“#ajax-response”).html(result); }, error : function(e) { console.log(“ERROR: “, e); } }); } function searchViaAjax() { var name = $(“#query”).val(); $.ajax({ type : “GET”, contentType : “application/json”, url : “${home}home/search/”, data : { name : name }, dataType : ‘json’, timeout : 100000, success : function(data) { console.log(“SUCCESS: “, data); if (data != null) { var result = ”

Ajax in Spring MVC Framework
Ajax in Spring MVC Framework

Quick Reference

1.1 In HTML, use jQuery

$.ajax()

to send a form request.


jQuery(document).ready(function($) { $("#search-form").submit(function(event) { // Prevent the form from submitting via the browser. event.preventDefault(); searchViaAjax(); }); }); function searchAjax() { var data = {} data["query"] = $("#query").val(); $.ajax({ type : "POST", contentType : "application/json", url : "${home}search/api/getSearchResult", data : JSON.stringify(data), dataType : 'json', timeout : 100000, success : function(data) { console.log("SUCCESS: ", data); display(data); }, error : function(e) { console.log("ERROR: ", e); display(e); }, done : function(e) { console.log("DONE"); } }); }

1.2 Spring controller to handle the Ajax request.


@Controller public class AjaxController { @ResponseBody @RequestMapping(value = "/search/api/getSearchResult") public AjaxResponseBody getSearchResultViaAjax(@RequestBody SearchCriteria search) { AjaxResponseBody result = new AjaxResponseBody(); //logic return result; } }

I want to send a json with Ajax to the Spring MVC controller but I can not get anything, I do not know what I’m failing

Javascript:


var search = { "pName" : "bhanu", "lName" :"prasad" } var enviar=JSON.stringify(search); $.ajax({ type: "POST", contentType : 'application/json; charset=utf-8', url: 'http://localhost:8080/HelloSpringMVC/j', data: enviar, // Note it is important success :function(result) { // do what ever you want with data } });

Spring MVC:


@RequestMapping(value ="/j", method = RequestMethod.POST) public void posted(@RequestBody Search search) { System.out.println("Post"); System.out.println(search.toString()); }

In this article, we will discuss how to implement AJAX and JSON in a Spring MVC application. AJAX is a powerful tool for creating dynamic web applications by allowing data to be loaded asynchronously from a server without requiring a page refresh. JSON, or JavaScript Object Notation, is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.

In a Spring MVC application, AJAX can be used to send requests to a server and retrieve data in JSON format. This allows for a more responsive user interface and reduces the amount of data that needs to be transferred between the client and server. By using AJAX and JSON in combination with Spring MVC, we can create web applications that are both powerful and efficient.

In this article, we will provide a step-by-step guide on how to implement AJAX and JSON in a Spring MVC application. We will cover everything from setting up the necessary dependencies to creating the controller and view components. By the end of this article, you will have a solid understanding of how to use AJAX and JSON in your Spring MVC applications.

Link download source code

https://www.dropbox.com/s/ov7wzcs49m3zgyx/viblo-spring-learn-ajax.zip?dl=0

All rights reserved

Spring 4 MVC Ajax Hello World Example

In this tutorial, we will show you how to create a Spring MVC web project and submit a form via Ajax.

Technologies used :

  1. Spring 4.2.2.RELEASE
  2. Jackson 2.6.3
  3. Logback 1.1.3
  4. jQuery 1.10.2
  5. Maven 3
  6. JDK 1.8
  7. Tomcat 8 or Jetty 9
  8. Eclipse 4.5
  9. Boostrap 3

P.S If the Jackson library is found in the project classpath, Spring will use Jackson to handle the json data to / from object conversion automatically.

Try this – Spring Boot Ajax example

Spring boot Jquery Ajax Crud
Spring boot Jquery Ajax Crud

Frequently Asked Questions

How to get JSON response in Ajax call using Spring MVC?

To get a JSON response in an AJAX call using Spring MVC, you can use the

@ResponseBody

annotation in your controller method. This will indicate to Spring that the method should return the response as JSON. You can then use jQuery’s

$.ajax()

method to make the AJAX call and handle the JSON response.

How to send JSON data to Spring MVC controller using AJAX?

To send JSON data to a Spring MVC controller using AJAX, you can use the

contentType

and

data

options in jQuery’s

$.ajax()

method. Set the

contentType

option to

'application/json'

and the

data

option to a JavaScript object representing the JSON data you want to send. Spring will automatically deserialize the JSON data into a Java object that can be used in your controller method.

How to return JSON data from Spring MVC controller?

To return JSON data from a Spring MVC controller, you can use the

@ResponseBody

annotation in your controller method. This will indicate to Spring that the method should return the response as JSON. You can then return a Java object that will be automatically serialized to JSON by Spring.

How to show data using AJAX in Spring MVC?

To show data using AJAX in Spring MVC, you can use jQuery’s

$.ajax()

method to make the AJAX call to your Spring controller. In the success callback function, you can then use jQuery’s DOM manipulation functions to update the HTML elements on your page with the data returned by the controller.

How to implement Ajax call in Spring security?

To implement an AJAX call in Spring Security, you will need to configure Spring Security to allow AJAX requests. You can do this by adding a CSRF token to your AJAX requests and configuring Spring Security to accept requests with the CSRF token. You can also configure Spring Security to return a JSON response for AJAX requests by using the

@ResponseBody

annotation in your controller methods.

How to use jQuery to make a REST API POST request in Spring MVC?

To use jQuery to make a REST API POST request in Spring MVC, you can use the

$.ajax()

method with the

type

option set to

'POST'

and the

url

option set to the URL of your REST API endpoint. You can then use the

data

option to specify the data you want to send in the POST request, and the

contentType

option to set the content type to

'application/json'

. In your Spring MVC controller, you can use the

@RequestBody

annotation to automatically deserialize the JSON data into a Java object.

Spring MVC AJAX Hello World Example – Kiến thức cơ bản HTTP và AJAX

Bài đăng này đã không được cập nhật trong 2 năm

Khi tìm hiểu về giao thức HTTP mình có đọc 1 số bài hướng dẫn trả lời phỏng vấn về giao thức HTTP như:

Phương thức POST bảo mật hơn GET vì dữ liệu được gửi ngầm bằng mắt thường không thể nhìn thấy được


Phương thức GET luôn luôn nhanh hơn POST vì dữ liệu gửi đi được Browser giữ lại trong cache


Phương thức GET dữ liệu được gửi tường minh, chúng ta có thể thấy trên URL nên nó không bảo mật.

Các câu trả lời ở bên trên chưa chính xác là do bạn chưa hiểu đúng về giao thức HTTP

**Trong bài hướng dẫn này mình sẽ nói đến các vấn đề sau**

1) Các khái niệm cơ bản về giao thức HTTP (GET, POST)

2) Tạo 1 web application sử dụng Spring MVC với AJAX

Giao thức HTTP( Hyper Text Transfer Protocol) là gì ? HTTP là giao thức quy ước chung để cho 2 đối tượng A và B có thể giao thông ( giao tiếp ) với nhau. Cụ thể là giao tiếp với nhau bằng 1 định dạng sử dụng chữ (text)

Ta đã biết phép căn bản của phần mềm là 2 phép đọc (read) và ghi (write) dữ liệu (Phần mềm viết ra là để xử lý dữ liệu) – phép ghi còn tách ra làm 3 phép thêm, sửa, xóa. Khi người ta thiết kế ra giao thức HTTP cũng xoay quanh các phép căn bản này của phần mềm. Từ 4 phép căn bản này sẽ tạo ra 7 HTTP method:

  • 4 phép đại diện cho đọc (read):
  1. GET
  2. Trace: đọc lỗi
  3. Option
  4. Head: đọc phần header
  • 3 phép đại diện cho ghi (write):
  1. PUT
  2. POST
  3. DELETE

Nhưng trong quá trình làm việc chúng ta gần như chỉ sử dụng 1 phép đại diện cho đọc là GET, 1 phép đại diện cho ghi là POST. Từ đây dẫn đến sự khác nhau giữa GET và POST:

  1. Ví dụ A muốn gửi 1 thông điệp (message) rằng A muốn đọc dữ liệu (GET) của B, như vậy A không cần mang dữ liệu lên B. Nhưng khi A muốn gửi (POST) 1 bức ảnh đến B, A phải mang dữ liệu lên B. Như vậy GET đại diện cho phép đọc sẽ không có phần body mà chỉ có header, còn POST đại diện cho phép ghi sẽ có phần body (đưa dữ liệu vào body)
  2. Sự khác nhau giữa cấu trúc của GET và POST sẽ ảnh hưởng đến điểm mạnh điểm yếu của POST và GET.
  • GET sẽ

    nhanh

    hơn POST: GET sẽ đi nhanh hơn POST trong môi trường mạng vì nó k có body. Phần server khi xử lý message này sẽ nhanh hơn vì GET chỉ có header (khi nói đến

    nhanh

    ta phải nhắc đến 2 khía cạnh: traffic và performance)
  • Điểm mạnh của POST là đưa được data lên. Nếu muốn đưa 1 đoạn video, 1 bức ảnh GET sẽ k thể nào làm được => Nhưng vì GET đi nhanh hơn nên người ta có xu hướng dùng GET nhiều hơn, thế nên những dữ liệu mà mang lên server đủ nhỏ thì người ta có thể chuyển dữ liệu theo đường GET
  • GET và POST đều có tính bảo mật như nhau, vì đối với GET ta có thể sử dụng kỹ thuật ajax để parametter k hiển thị lên trên url

**Tạo 1 project sử dụng Spring MVC + Ajax bằng maven, server chạy bằng jetty **

Ajax là gì ? Ajax là một khái niệm có thể mới lạ với những bạn newbie mới học lập trình web nên đôi lúc các bạn nghĩ nó là một ngôn ngữ lập trình mới. Nhưng thực tế không như vậy, ajax là một kỹ thuật viết tắt của chữ AJAX = Asynchronous JavaScript and XML, đây là một công nghệ giúp chung ta tạo ra những Web động mà hoàn toàn không reload lại trang nên rất mượt và đẹp. Đối với công nghệ web hiện nay thì ajax không thể thiếu, nó là một phần làm nên sự sinh động cho website

Các công nghệ sẽ sử dụng trong phần hg dẫn này:

  1. Spring 4.2.2.RELEASE
  2. Jackson 2.6.3
  3. Logback 1.1.3
  4. jQuery 1.10.2
  5. Maven 3
  6. JDK 1.8
  7. Tomcat 8 or Jetty 9
  8. Eclipse 4.5
  9. Boostrap 3

**Cấu trúc project **

**1)Project dependency: **


4.0.0


com.viblo


viblo-spring-learn-ajax
war
1.0-SNAPSHOT


viblo-spring-learn-ajax Maven Webapp


http://maven.apache.org

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





viblo-spring-learn-ajax

org.apache.maven.plugins


maven-surefire-plugin


2.12.4



true


-Xmx2524m


org.apache.maven.plugins


maven-compiler-plugin


3.1


1.8

1.8


UTF-8


true



-XDignore.symbol.file



org.eclipse.jetty


jetty-maven-plugin


9.3.0.M1



-Xmx2048m -Xms1536m -XX:PermSize=128m -XX:MaxPermSize=512m


manual




lib


${basedir}/target/viblo-spring-learn-ajax/WEB-INF/lib




8080
60000




${basedir}/src/main/webapp


${basedir}/src/main/webapp/WEB-INF/web.xml


${basedir}/target/classes

2)AjaxController AjaxController sẽ xử lý các ajax request từ phía client như thêm, hoặc tìm kiếm ! Sau đó trả về kết quả dưới dạng json cho client.


@Controller @RequestMapping("/home") public class AjaxController { private List listPerson = new ArrayList (); @RequestMapping(method = RequestMethod.GET) public ModelAndView home() { ModelAndView mv = new ModelAndView("web.home"); return mv; } @RequestMapping(value = "/addnew", method = RequestMethod.GET) public @ResponseBody String addNew(HttpServletRequest request) { String name = request.getParameter("name"); String age = request.getParameter("age"); Person person = new Person(name, Integer.parseInt(age)); listPerson.add(person); ObjectMapper mapper = new ObjectMapper(); String ajaxResponse = ""; try { ajaxResponse = mapper.writeValueAsString(person); } catch (JsonProcessingException e) { e.printStackTrace(); } return ajaxResponse; } @RequestMapping(value = "/search", method = RequestMethod.GET) public @ResponseBody String searchPerson(HttpServletRequest request) { String query = request.getParameter("name"); Person person = searchPersonByName(query); ObjectMapper mapper = new ObjectMapper(); String ajaxResponse = ""; try { ajaxResponse = mapper.writeValueAsString(person); } catch (JsonProcessingException e) { e.printStackTrace(); } return ajaxResponse; } public Person searchPersonByName(String query) { for (Person p : listPerson) { if (p.getName().equals(query)) { return p; } } return null; }

**3)Model Class ** Person class có nhiệm vụ đóng gói dữ liệu của người dùng nhập vào hoặc dữ liệu được trả về của server !


public class Person { private String name; private int age; public Person() { } public Person(String name, int age) { this.name=name; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }

**4)Jquery Ajax **
Trong file JSP, ta tạo 2 form thêm và tìm kiếm đơn giản gửi ajax request bằng

$.ajax


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<br /> Spring Ajax Example<br />


Add New Person

Search Person by name




5)Demo
Bật terminal hoặc lên, đưa con trỏ vào vị trí của project và gõ lệnh

mvn jetty:run

**5.1) Nhập tên và tuổi **

**5.2) Kết quả ajax trả về từ server **

Ta đã sử dụng HTTP method GET nhưng dữ liệu vẫn k bị hiển thị lên url => việc nói POST bảo mật hơn GET vì dữ liệu không được đưa lên url là chưa đúng !

08: How to pass JSON data to server side using jQuery AJAX ?
08: How to pass JSON data to server side using jQuery AJAX ?

Common Issues and Solutions

Debugging Ajax Issues in Spring MVC

When working with Ajax requests in Spring MVC, it is common to encounter issues related to the request not being sent or received properly. Here are some common issues and solutions:

  • Incorrect URL: Ensure that the URL in the Ajax request matches the URL in the Spring MVC controller. Check for any typos or missing slashes in the URL.
  • Missing Request Parameters: Check if all the required request parameters are being sent in the Ajax request. Use the browser’s developer tools to inspect the request and response headers and data.
  • Cross-Origin Resource Sharing (CORS): If the Ajax request is being sent from a different domain than the one hosting the Spring MVC application, then CORS restrictions may apply. Check if the server is configured to allow CORS requests.

Optimizing JSON Response

Sending JSON data in Spring MVC can be optimized to improve the performance of the application. Here are some tips to optimize the JSON response:

  • Minimize the JSON payload: Only send the required data in the JSON response. Remove any unnecessary data to reduce the payload size.
  • Use GZIP compression: Compress the JSON response using GZIP compression to reduce the payload size and improve the response time.
  • Use caching: Cache the JSON response on the client-side or server-side to reduce the number of requests and improve the response time.

By following these tips, we can optimize the JSON response and improve the performance of the Spring MVC application.

Understanding Spring MVC

Spring MVC is a web application framework developed by the Spring Framework. It provides a model-view-controller (MVC) architecture that is used to develop web applications. The framework provides a lot of features that make the development of web applications easy and efficient. In this section, we will discuss the role of Spring MVC in web applications and its key features.

Role of Spring MVC in Web Applications

Spring MVC is a powerful framework that provides a lot of features that are essential for developing web applications. The framework provides a model-view-controller architecture that is used to separate the application into three parts:

  • Model: This represents the data and business logic of the application.
  • View: This represents the user interface of the application.
  • Controller: This is responsible for handling the user requests, processing the data, and returning the response.

The main role of Spring MVC in web applications is to provide a flexible and powerful framework that can be used to develop web applications that are easy to maintain and extend. The framework provides a lot of features that make the development process easy and efficient.

Key Features of Spring MVC

Spring MVC provides a lot of key features that make it a powerful framework for developing web applications. Some of the key features are:

  • Powerful Request Handling: Spring MVC provides a powerful request handling mechanism that can handle different types of requests, including GET, POST, PUT, DELETE, and more.
  • Flexible Configuration: Spring MVC provides a flexible configuration mechanism that allows developers to configure the framework according to their needs.
  • Built-in Validation: Spring MVC provides built-in validation support that allows developers to validate the user input easily.
  • Internationalization Support: Spring MVC provides internationalization support that allows developers to develop applications that can be easily localized.
  • Integration with Other Technologies: Spring MVC can be easily integrated with other technologies, such as Hibernate, MyBatis, and more.

In conclusion, Spring MVC is a powerful framework that provides a lot of features that make the development of web applications easy and efficient. The framework provides a model-view-controller architecture that is used to separate the application into three parts: model, view, and controller. The framework provides a lot of key features that make it a powerful framework for developing web applications.

.NET Core MVC CRUD  using .NET Core Web API and ajax call | Consume secured  .NET Core API in MVC
.NET Core MVC CRUD using .NET Core Web API and ajax call | Consume secured .NET Core API in MVC

Keywords searched by users: spring mvc ajax json

Spring Mvc Ajax Json Response Example: A Professional Guide - Makemychance
Spring Mvc Ajax Json Response Example: A Professional Guide – Makemychance
Github - Stevehanson/Spring-Mvc-Ajax: Sample Spring Mvc Application  Demonstrating Json Ajax Requests With Java Spring Mvc Back-End.
Github – Stevehanson/Spring-Mvc-Ajax: Sample Spring Mvc Application Demonstrating Json Ajax Requests With Java Spring Mvc Back-End.
Code-With-The-Flow: Jquery Ajax Requests In Spring Mvc Example
Code-With-The-Flow: Jquery Ajax Requests In Spring Mvc Example
Spring Boot Xử Lý Request Trong Controller Như Thế Nào (Phần 1)
Spring Boot Xử Lý Request Trong Controller Như Thế Nào (Phần 1)
Asp.Net Core Mvc Ajax Form Requests Using Jquery-Unobtrusive | Software  Engineering
Asp.Net Core Mvc Ajax Form Requests Using Jquery-Unobtrusive | Software Engineering
Spring 3 Mvc Autocomplete With Jquery & Json Tutorial & Example
Spring 3 Mvc Autocomplete With Jquery & Json Tutorial & Example
Spring Mvc Ajax Hello World Example - Kiến Thức Cơ Bản Http Và Ajax
Spring Mvc Ajax Hello World Example – Kiến Thức Cơ Bản Http Và Ajax
Jquery Ajax Call To Mvc Controller With Parameters - Sensible Dev
Jquery Ajax Call To Mvc Controller With Parameters – Sensible Dev
How To Use Ajax And Jquery In Spring Web Mvc (.Jsp) Application • Crunchify
How To Use Ajax And Jquery In Spring Web Mvc (.Jsp) Application • Crunchify
Spring 4 Mvc Rest Controller Service Example (Json Crud Tutorial)
Spring 4 Mvc Rest Controller Service Example (Json Crud Tutorial)
Asp.Net Ajax Json Crud - Youtube
Asp.Net Ajax Json Crud – Youtube
Spring - Rest Json Response - Geeksforgeeks
Spring – Rest Json Response – Geeksforgeeks
How To Integrate Jquery Ajax Post/Get & Spring Mvc | Spring Boot | Java  Techie - Youtube
How To Integrate Jquery Ajax Post/Get & Spring Mvc | Spring Boot | Java Techie – Youtube
Spring Boot Ajax Jquery Example - Learning To Write Code For Beginners With  Tutorials
Spring Boot Ajax Jquery Example – Learning To Write Code For Beginners With Tutorials
Sử Dụng Jquery Ajax Trong Asp.Net Mvc
Sử Dụng Jquery Ajax Trong Asp.Net Mvc
Part 5 # Spring Mvc Application With Ajax | Ashok It - Youtube
Part 5 # Spring Mvc Application With Ajax | Ashok It – Youtube

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *