Joris
Joris

Reputation: 309

Set a Spring REST Controller welcome-file

I'm building a RESTful API and have a Spring REST Controller (@RestController) and an annotation-based configuration. I'd like to have my project's welcome-file be a .html or .jsp file with the API documentation.

In other web projects I would place a welcome-file-list in my web.xml, but in this particular project I can't seem to get it to work (preferrably using Java and annotations).

This is my WebApplicationInitializer

public class WebAppInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(ApplicationConfig.class);
        context.setServletContext(servletContext);

        ServletRegistration.Dynamic dynamic = servletContext.addServlet("dispatcher", 
           new DispatcherServlet(context));
        dynamic.addMapping("/");
        dynamic.setLoadOnStartup(1);
    }
}

This is my WebMvcConfigurerAdapter

@Configuration
@ComponentScan("controller")
@EnableWebMvc
public class ApplicationConfig extends WebMvcConfigurerAdapter {

    @Bean
    public Application application() {
        return new Application("Memory");
    }

}

And this is a small part of my REST Controller

@RestController
@RequestMapping("/categories")
public class CategoryRestController {

    @Autowired
    Application application;

    @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map<Integer, Category>> getCategories(){
        if(application.getCategories().isEmpty()) {
            return new ResponseEntity<Map<Integer, Category>>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<Map<Integer, Category>>(application.getCategories(), HttpStatus.OK);
    }

}

So far I've tried:

Upvotes: 1

Views: 2703

Answers (1)

M. Deinum
M. Deinum

Reputation: 124526

When specifying a controller to handle your index page you should use a @Controller not a @RestController. Although the @RestController is a @Controller it doesn't resolve to a view but returns the result as is to the client. When using a @Controller when returning a String it will resolve to the name of a view.

@Controller
public class IndexController {

    @RequestMapping("/")
    public String index() {
        return "index";
    }
}

However there is an easier way to configure this and you don't need a controller for it. Configure a view controller. In your configuration class simply override/implement the addViewControllers method.

public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("index");
}

That way you don't even need to create a class for it.

Upvotes: 1

Related Questions