Open In App

Serve Static Resources With Spring

It’s essential to know about static resources, which are the resources that do not change frequently on a web page. To serve these static resources, Spring Boot comes with an inbuilt class called ResourceHttpRequestHandler in conjunction with the ResourceHandlerRegistry class. You can keep these static resources under specific paths like ‘/public’, ‘/static’, ‘resources’, and ‘META-INF/resources/’. To change the default locations that serve the static resources, define them in the resources folder with

spring.resources.static-locations=/html, /css, /js



Sample Folder Structure:

sample folder structure

Guide to Serving Static Pages

We can customize the resource handling by configuring it with ResourceHandlerRegistry. We typically configure how our Spring Boot app deals with web stuff in a special class. This class can either be an old-style one called WebMvcConfigurerAdapter (which is a bit outdated but still commonly used) or directly implement WebMvcConfigurer. Here is the sample code






@Configuration
public class WebConfig implements WebMvcConfigurer {
  
    @Override
    public void
    addResourceHandlers(ResourceHandlerRegistry registry)
    {
        registry.addResourceHandler("/static/**")
            .addResourceLocations("classpath:/static/")
            .setCachePeriod(3900)//mention in seconds
            .resourceChain(true)
            .addResolver(new PathResourceResolver());
    }
}

Lets get to know what the ResourceHandlerRegistry does,




import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.VersionResourceResolver;
  
@Configuration
public class WebConfig implements WebMvcConfigurer {
  
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/")
                .setCachePeriod(3600)
                .resourceChain(true)
                .addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
    }
}

Sample Output:

sample output

Here we are using Thymeleaf here, you can use any other

<!– Thymeleaf example –>

<link rel=”stylesheet” th:href=”@{/static/css/style.css}” />

Let’s get to know what the PathResourceResolver does,

You may also have a question what will happen after the cache period? Let me tell you,

Guide to serving dynamic pages

Let’s get into a step-by-step guide on this demo for generating dynamic content using Thymeleaf where data are processed from the server.




@Controller
public class studentController {
    @Autowired 
      studentService service;
  
    // handler method to handle studnts
    @GetMapping("/students")
    public String listStudents(Model model)
    {
        model.addAttribute("index",
                           service.getAllStudents());
        return "index";
    }
  
    @GetMapping("/students/new")
    public String addStudents(Model model)
    {
        // object to hold the data of new student
        Student student = new Student();
        model.addAttribute("student", student);
        return "add_students";
    }
    @PostMapping("/students")
    public String
    saveStudent(@ModelAttribute("student") Student student)
    {
        service.saveStudent(student);
        return "redirect:/students";
    }
    @GetMapping("students/edit/{id}")
    public String editStudent(@PathVariable("id") Long id,
                              Model model)
    {
        model.addAttribute("student",
                           service.getStudentById(id));
        return "edit_student";
    }
}

In this piece of code that I’ve written you should know about Model Interface which is present in the package of org.springframework.ui.Model and Controller annotation and not RestController.

Model interface is used in controllers to pass data to views. It holds attributes that need to be displayed in the user interface. Controllers add data to the model, and views access and display that data. It’s a way to share information between the backend and frontend components of a web application.

Genrally the @RestController annotation is used to create a webservice that returns JSON/XML data, @Controller annotation that is used to create web controllers that returns views. You may have a question what views are, simply we could say the user interface output to the user request. To work completely with the dynamic content, just write the HTML pages using Thymeleaf and serve it through the controller, where the server sends the data to the view.


Article Tags :