Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Spring MVC Response Handling Techniques

Tech 1

When a controller method processes a request, Spring MVC provides multiple approaches to handle the repsonse.

Void Return Type

@RequestMapping("/processVoid")
public void handleVoidRequest() throws Exception {
    System.out.println("Void handler method executed");
}

When a controller method returns void, Spring MVC attempts to locate a view matching the method name. Without view resolver configuration, this may result in 404 errors.

Servlet API Forward and Redirect

@RequestMapping("servletDemo")
public void handleServletResponse(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    // Request forwarding
    // req.getRequestDispatcher("/target.jsp").forward(req, resp);
    
    // Response redirect
    resp.sendRedirect(req.getContextPath() + "/redirect.jsp");
}

Using HttpServletResponse directly bypasses DispatcherServlet's standard response handling.

Forward Keyword Approach

@RequestMapping("forwardDemo")
public String handleForward() throws Exception {
    // Explicit forward
    // return "forward:/destination.jsp";
    
    // Implicit forward (forward keyword omitted)
    return "/targetPage.jsp";
}

The forward keyword can be omitted when performing request forwarding.

Redirect Keyword Approach

@RequestMapping("redirectDemo")
public String handleRedirect() throws Exception {
    return "redirect:/newLocation.jsp";
}

The redirect keyword is mandatory for response redirection.

View Interface Implementation

@RequestMapping("viewDemo")
public View handleViewResponse(HttpServletRequest request) {
    View resultView = null;
    
    // Internal resource view (forwarding)
    // resultView = new InternalResourceView("/internal.jsp");
    
    // Redirect view
    resultView = new RedirectView(request.getContextPath() + "/external.jsp");
    
    return resultView;
}

RedirectView handles URL redirection and supports data preservation through FlashMap.

ModelAndView Aprpoach

@RequestMapping("modelViewDemo")
public ModelAndView handleModelAndView(HttpServletRequest req) {
    ModelAndView modelView = new ModelAndView();
    
    // Forward using view name
    // modelView.setViewName("forward:/page.jsp");
    
    // Forward using View object
    // modelView.setView(new InternalResourceView("/resource.jsp"));
    
    // Redirect using view name
    // modelView.setViewName("redirect:/newPage.jsp");
    
    // Redirect using View object
    modelView.setView(new RedirectView(req.getContextPath() + "/external.jsp"));
    
    return modelView;
}

ModelAndView encapsulates both data model and view information for comprehensive response handling.

JSON Response with @ResponseBody

For AJAX requests, Spring MVC can directly return JSON data instead of view resolution.

Dependency Configuration

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.1</version>
</dependency>

Controller Implementation

@ResponseBody
@RequestMapping("ajaxHandler")
public Animal processAjaxRequest(User user) throws JsonProcessingException {
    System.out.println(user);
    Animal animal = new Animal("Max", "dog");
    return animal;
}

@ResponseBody instructs Spring MVC to treat the return value as direct response data rather than view information.

Client-Side Implementation

<script>
    $(function(){
        $("#ajaxButton").click(function(){
            $.get("ajaxHandler", {username:"john", age:"25"}, function(response){
                console.log(response.animalName);
                console.log(response.animalSpecies);
            });
        });
    });
</script>

@RestController Annotation

@RestController
public class RestApiController {
    @RequestMapping("restEndpoint")
    public Animal handleRestCall(User person) throws JsonProcessingException {
        System.out.println(person);
        Animal pet = new Animal("Buddy", "dog");
        return pet;
    }
}

@RestController combines @Controller and @ResponseBody functionality, automatically serializing return values to JSON. This annotation prevents JSP/HTML view resolution.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.