Close

Spring MVC - WebMvcConfigurer Examples

Spring MVC 

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig implements WebMvcConfigurer {

@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/views/", ".jsp");
}


@Override
public void addViewControllers(ViewControllerRegistry registry) {
//this will map uri to jsp view directly without a controller
registry.addViewController("/hi")
.setViewName("hello");
}
}
Original Post




import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig implements WebMvcConfigurer {

@Override
public void addViewControllers(ViewControllerRegistry registry) {
//mapping '/' to index view name without a controller
ViewControllerRegistration r = registry.addViewController("/");
r.setViewName("index");
}

@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp();//default prefix=/WEB-INF/", suffix=".jsp"
}


@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//specifying static resource location for themes related files(css etc)
registry.addResourceHandler("/themes/**")
.addResourceLocations("/app-themes/");
}
}
Original Post




import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.*;

@EnableWebMvc
@Configuration
@ComponentScan
public class MyWebConfig implements WebMvcConfigurer {

@Bean
public MessageSource messageSource() {
//this is only needed for text messages and not needed for theme internationalization
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasenames("texts/msg");
return messageSource;
}

@Override
public void addViewControllers(ViewControllerRegistry registry) {
//mapping '/' to index view name without a controller
ViewControllerRegistration r = registry.addViewController("/");
r.setViewName("index");
}

@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp();//default prefix=/WEB-INF/", suffix=".jsp"
}
}
Original Post




See Also