Spring MVC Ajax Integration: Handling JSON Requests with Controllers

When implementing interceptors in Spring MVC, a common challlenge arises with Ajax requests: static resources like JavaScript, CSS, and image files get intercepted along with regular requests. This prevents proper loading of these resources in JSP pages. To address this, we need to configure our interceptors to exclude static resources.

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/**/*"/>
        <mvc:exclude-mapping path="/**/fonts/*"/>
        <mvc:exclude-mapping path="/**/*.css"/>
        <mvc:exclude-mapping path="/**/*.js"/>
        <mvc:exclude-mapping path="/**/*.png"/>
        <mvc:exclude-mapping path="/**/*.gif"/>
        <mvc:exclude-mapping path="/**/*.jpg"/>
        <mvc:exclude-mapping path="/**/*.jpeg"/>
        <mvc:exclude-mapping path="/**/*login*"/>
        <mvc:exclude-mapping path="/**/*Login*"/>
        <bean class="com.cyw.web.Intercepter.LoginIntercepter"></bean>
    </mvc:interceptor>
</mvc:interceptors>

View CodeConfiguring Static Resource Access

To properly serve static resources in a Spring MVC application, we need to configure resource handling. Here's how to set up access to JavaScript files and other static assets.

    <!-- Static resource handling - Option 1 (choose one) -->
    
    <mvc:default-servlet-handler />
    
    <!-- Static resource handling - Option 2 (choose one) -->
   
    <mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/> 
    <mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/> 
    <mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/>
    

View CodeIncluding Static Resources in JSP Pages

There are two primary methods for including JavaScript files in JSP pages: relative path and absolute path approaches.

<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-3.3.1.min.js"></script>
<%
      String path = request.getContextPath();
      String basePath = request.getScheme() + "://"
                  + request.getServerName() + ":" + request.getServerPort()
                  + path + "/";
%>
<script type= "text/javascript" src= "<%=basePath %>js/jquery-3.3.1.min.js"></script >

View CodeImplementing Ajax Requests with Spring MVC

  1. Creating an Ajax Request from JSP

The following example demonstrates how to send a JSON request from a JSP page to a Spring MVC controller using jQuery.

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-3.3.1.min.js"></script>
<%
      String path = request.getContextPath();
      String basePath = request.getScheme() + "://"
                  + request.getServerName() + ":" + request.getServerPort()
                  + path + "/";
%>
<script type= "text/javascript" src= "<%=basePath %>js/jquery-3.3.1.min.js"></script >
<script type="text/javascript">
$(document).ready(function(){
      $("#btnlogin").click(function(){
            var userData = {  
                    'username':$(':input[name=username]').val(),  
                'password':$(':input[name=password]').val(),
                'birthDate':'2018-05-01'
                };
                var requestData = JSON.stringify(userData);
                alert(requestData);  
                
                $.ajax({  
                type : 'POST',  
                contentType : 'application/json;charset=UTF-8',
                processData : false,  
                url : '<%=path%>/login/requestbodybind',  
                dataType : 'json',  
                data : requestData,  
                success : function(response) {  
                    alert('Username: '+response.username+'\nPassword: '+response.password);  
                },  
                error : function(error) {  
                    console.log(error.responseText);
                    alert(error.responseText);
                    
                }  
              }); 
      });
    });

</script>
<title>User Login</title>
</head>

<body>
<form action="../login/login.action" method="post">  
         Username: <input type="text" name="username"> <br><br>  
         Password:   <input type="text" name="password"> <br><br>  
       <input type="button" value="Login" id="btnlogin">    <input type="submit" value="Login">  
</form> 
</body>
</html>

View CodeWhen sending date parameters, note that the format matters. Initially using "2018/05/01" caused issues, but changing to "2018-05-01" resolved the problem.

  1. Receiving JSON Requests in Controller

Spring MVC provides two key annotations for handling JSON data: @RequestBody and @ResponseBody.

@RequestBody: Applied to method parameters, this annotation converts incoming JSON/XML data into Java objects using HttpMessageConverter.

@ResponseBody: Applied to methods, this annotation writes the return value directly to the HTTP response body, commonly used in AJAX scenarios. Without this annotation, Spring would interpret the return value as a view name.

    @RequestMapping(value="requestbodybind", method = {RequestMethod.POST})  
    @ResponseBody  
    public User handleJsonRequest(@RequestBody User user){  
          System.out.println("Processing request: " + user);  
          return user;  
    }

View Code3. Common Issues and Solutions

When testing the implementation, you might encounter HTTP 415 errors indicating unsupported media type. This typically means the Jackson libray is missing from your project dependencies.

HTTP Status 415 – Unsupported Media Type.The origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource.

 <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.5</version>
</dependency>

Key Takeaways

Understanding Spring MVC's JSON handling capabilities is crucial for modern web development. The combination of @RequestBody and @ResponseBody enables seamless communication between frontend and backend. Remember to properly configure your project dependencies and interceptors to insure smooth operation of both dynamic and static resources.

Tags: Spring MVC Ajax JSON @RequestBody @ResponseBody

Posted on Sat, 19 Sep 2026 16:45:54 +0000 by aftabn10