Spring MVC and AJAX integration example

Table of Contents

1. Introduction

SpringMVC

AJAX

2. Environment settings & related configurations

3. Create Spring MVC project

4. Create Controller

5. Front-end page design

6. Display data:


1. Introduction

Spring MVC

Spring MVC is a module in the Spring framework for developing web applications based on the Model-View-Controller (MVC) architecture. It provides a flexible and powerful way to build scalable web applications, achieving decoupling and maintainability by mapping requests to specific processor methods and rendering responses using view technology.

The main components of Spring MVC include:

  • Controller: Responsible for processing user requests and returning corresponding views or data.
  • View Resolver: Maps logical view names to specific view implementations.
  • Model: Encapsulates the data required to process the request and passes it to the view for rendering.
  • Handler Mapper: Maps requests to specific processor methods.
  • View: Responsible for rendering model data into the final response.

AJAX

AJAX (Asynchronous JavaScript and XML) is a technology for asynchronous data interaction in web applications. While traditional web applications typically require a complete page refresh between the user and the server, AJAX allows partial data to be updated without refreshing the entire page.

The main features of AJAX include:

  • Asynchronous communication: AJAX uses an asynchronous method to communicate with the server and does not block the operation of the user interface.
  • Data interaction: Through AJAX, you can get data from the server, send data to the server or update part of the page content without refreshing the entire page.
  • Front-end technology: AJAX uses JavaScript and XMLHttpRequest objects to implement asynchronous communication and data processing.

AJAX is widely used in web development. It improves user experience, speeds up page loading, and supports dynamic content updates.

2. Environment settings & related configurations

2.1. The environment used in this case is Eclipse2018. The server is: tomcat8.5. The Java version is: jdk8.

2.2. Use AJAX to complete asynchronous requests through the JQuery library

Import method: Enter the following content in the jsp interface to complete the online download and use of the JQuery library:

<script src="//i2.wp.com/code.jquery.com/jquery-3.6.0.min.js"></script>

2.3. Jar package download: (In order to deal with the problem of sending different types of responses to the client, that is, the support issue of serialization and deserialization)

The @ResponseBody annotation is used to indicate that the object returned by the method should be written directly to the HTTP response body (rather than the view parser rendering the view).

Therefore, when processing AJAX requests, you usually need to use the @ResponseBody annotation to ensure that the returned data is sent directly to the front end in JSON format. However, @ResponseBodyprocesses String type by default. If the web page returned is an entity object, a 500 error will be reported.

When dealing with non-character data (such as returning JSON, binary data, etc.), you need to ensure that the object is correctly serialized and sent to the client as a response. This requires the introduction of the corresponding jar package to provide serialization and deserialization support.

Solution:

  • Add maven dependencies:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.4</version> <!--Replace with the version you need -->
</dependency>
  • Download the corresponding jar package to the lib directory of the project:

These jar packages can be downloaded from the following links:

jackson-core2.9.4: jackson-core-2.9.4

jackson-databind2.9.4: jackson-databind-2.9.4

jackson-annotations2.9.4: jackson-annotation-2.9.4

3. Create Spring MVC project

You can refer to other blogs for the creation process: link

4. Create Controller

Create a Controller for handling AJAX requests:

See comments for specific instructions.

@RequestMapping("/selectone")
@ResponseBody //@ResponseBody annotation is used to indicate that the object returned by the method should be written directly into the HTTP response body
//@RequestParam("Name") is used to obtain the data sent from the front end and bind it to name.
public Apple selectone(@RequestParam("Name") String name,Model model) {
Apple app=appleMapper.selectByPrimaryKey(name); //Get data from the database.
model.addAttribute("app",app); //Add the obtained data to the model
System.out.println(app); //Print information
return app; //Return the client's response information.
}

5. Front-end page design

Front-end page example:

Detailed code explanation:

  1. $(document).ready(function() {...});: This code uses jQuery’s $(document).ready() function, in the DOM Execute the code after loading is complete.
  2. $("#but").click(function(event) {...});: Execute the code when the element with the id “but” is clicked.
  3. event.preventDefault();: Prevent the default submission behavior of the form, that is, prevent the page from refreshing or jumping.
  4. var appleName = $("#selName").val();: Get the value of the input box with the id “selName” and assign it to the variable appleName.
  5. $.ajax({ ... });: Use jQuery’s ajax function to send an asynchronous request.
  • url: "${pageContext.request.contextPath}/selectone": Specifies the URL of the request. ${pageContext.request.contextPath} is the way to obtain the context path in JSP. , /selectone is the specific path for processing requests.
  • type: "post": Specifies the HTTP request type as POST.
  • data: {Name: appleName}: Data sent to the server, where Name is the parameter name and appleName is the parameter value.
  • success: function(response) {...}: Define the callback function when the request is successful, where response is the data returned from the server.
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here

<script src="//i2.wp.com/code.jquery.com/jquery-3.6.0.min.js"></script>




    


6. Display data: