Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Configuring Server-Side View Rendering with ModelAndView in Spring Boot

Tech May 12 2

Enabling server-side view rendering in Spring Boot requires configuring a view resolver that maps logical names returned from controllers to physical template files. The setup involves updating project dependencies, adjusting the application entry point for external container compatibility, defining path mappings, and implementing controllers that leverage the ModelAndView container.

Include the necessary dependencies in your build configuration. The embedded Tomcat Jasper library handles JSP compilation, while the core web starter provides the underlying MVC infrastructure. Legacy utilities such as devtools or alternate template engines can be omitted unless specifically required.

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
</dependencies>

Modify the primary application class to extend SpringBootServletInitializer. This adjustment ensures the application context initializes correctly when packaged as a WAR and deployed to external servlet containers like Apache Tomcat or Jetty.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(DemoApplication.class);
    }
}

Define the view resolution boundaries in your properties file. Setting the prefix and suffix eliminates the need to write full file paths in controller methods, allowing the fraemwork to concatenate these values automatically during dispatch.

spring:
  mvc:
    view:
      prefix: /WEB-INF/templates/
      suffix: .jsp

Implement request handlers using the @Controller annotation rather than @RestController. Returning a ModelAndView object allows you to decouple the response type from the payload data. The framework extracts the view name, resolves it against the configured prefix/suffix, and populates the request scope with attached attributes.

package com.example.app.handlers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/portal")
public class PageDispatcher {

    @GetMapping("/welcome")
    public ModelAndView loadWelcomePage(Model model) {
        ModelAndView viewResponse = new ModelAndView("portal/main");
        
        viewResponse.addObject("sessionToken", "abc-123-xyz");
        viewResponse.addObject("userRole", "administrator");
        viewResponse.addObject("timestamp", System.currentTimeMillis());
        
        return viewResponse;
    }

    @PostMapping("/submit-form")
    public String handleFormSubmission(@RequestParam String formData) {
        return "portal/confirmation";
    }
}

The ModelAndView instance functions as a composite carrier for both routing instructions and model data. During the processing cycle, Spring extracts each attribute, makes it accessible via ${key} expressions in the target template, and invokes the servlet forward mechanism. Switching to MappingJackson2JsonView within the same method signature transforms the response payload into serialized JSON instead of executing a template lookup.

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.