Enable Web MVC support for your spring app using Java Config

Hello everyone,

This is not a Spring MVC tutorial. I think there are plenty of those on the internet. I just want to show you how you can enable MVC support and create an API for your app.

Sometimes you might have a simple Spring app or even a JSF+Spring web app and want to expose an API. One way to do this is to use Spring MVC Controllers. It takes only 1 minute, I promise.

Let’s see:

1 Register the Spring’s DispatcherServlet in your web.xml :

<!-- Spring servlet -->
 
<servlet>
     <servlet-name>springServlet</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <init-param>
          <param-name>contextClass</param-name>
          <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
     </init-param>
</servlet>
<servlet-mapping>
     <servlet-name>springServlet</servlet-name>
     <url-pattern>/api/*</url-pattern>
</servlet-mapping>

You can see there that the url-pattern is set to “/api/*” . Use this only when you want to expose like an API for your app. If you want the dispatcher servlet to intercept all urls then use “/*”

Also you need to set the context config location to point to your java config class (if you don’t have it already):

<!-- @Configuration classes or package -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>com.awesomeapp.config.AppConfig</param-value>
</context-param>

2 Now you have to add the EnableWebMvc annotation to your Spring java config class.

VERY IMPORTANT: If your url-pattern is set to something else other than “/*” then you need to customise the request mapping handler mapping. But in order to do this your java config class should extend WebMvcConfigurationSupport. So your spring java config class should look something like this:


@Configuration
@ComponentScan({"com.webmvctemplate"})
@EnableWebMvc()
@Import({PersistenceJPAConfig.class, AsyncConfig.class, SecurityConfig.class}) // if you want to separate the types of configs
public class AppConfig extends WebMvcConfigurationSupport {
 
    @Bean
    @Override
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
        handlerMapping.setAlwaysUseFullPath(true);
        return handlerMapping;
 
    }
 
}

3 Now you have to add the maven dependencies. Dependencies for Spring Web and for Jackson. Spring uses Jackson to send JSON response in the rest call response:

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
</dependency>
 
<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.2</version>
</dependency>
<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.5.2</version>
</dependency>

4 That’s pretty much it! Now you can just create a controller using “/api” as root context mapping:


@Controller
@RequestMapping("/api")
public class MainController implements Serializable {
 
    private static final long serialVersionUID = 1725889878808740L;
 
    @RequestMapping(value = "/healthCheck", method = RequestMethod.GET)
    @ResponseBody
    public String healthCheck(Model model) {
        return "Everything is up and running smoothly, sir!";
    }
}

NOTE: If you use Spring Security then you have to permit access to your new API, otherwise you have to implement some sort of authentication, like basic auth, oauth, simple username and password, simple secret, anything 🙂

If you want to give access to anyone to your api then add this in your spring security java config class:


http.antMatchers("/api/**").permitAll();

So, how was it? Fine, you’re right, it took more than 1 minute… maybe 5 tops 🙂

Have fun spreading joy!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s