Spring MVC Response Handling Techniques
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.