Book Image

Mastering Spring MVC 4

By : Geoffroy Warin
Book Image

Mastering Spring MVC 4

By: Geoffroy Warin

Overview of this book

<p>Spring MVC is the ideal tool to build modern web applications on the server side. With the arrival of Spring Boot, developers can really focus on the code and deliver great value, leveraging the rich Spring ecosystem with minimal configuration.</p> <p>Spring makes it simple to create RESTful applications, interact with social services, communicate with modern databases, secure your system, and make your code modular and easy to test. It is also easy to deploy the result on different cloud providers.</p> <p>Mastering Spring MVC will take you on a journey from developing your own web application to uploading it on the cloud.</p> <p>You begin by generating your own Spring project using Spring Tool suite and Spring Boot.</p> <p>As you develop an advanced-level interactive application that can handle file uploads as well as complex URLs, you will dive into the inner workings of Spring MVC and the principles of modern web architectures.</p> <p>You will then test, secure, and optimize your Spring web application and design RESTful services that will be consumed on the frontend.</p> <p>Finally, when everything is ready, you will release your application on a cloud provider and invite everyone to see.</p>
Table of Contents (17 chapters)
Mastering Spring MVC 4
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Error and encoding configuration


Remember when we first launched our application without adding a controller? We got a funny Whitelabel Error Page output.

Error handling is a lot trickier than it looks, especially when you don't have a web.xml configuration file and want your application to be portable across web servers. The good news is that Spring Boot takes care of that for us! Let's look at ErrorMvcAutoConfiguration:

ConditionalOnClass({ Servlet.class, DispatcherServlet.class })
@ConditionalOnWebApplication
// Ensure this loads before the main WebMvcAutoConfiguration so that the error View is
// available
@AutoConfigureBefore(WebMvcAutoConfiguration.class)
@Configuration
public class ErrorMvcAutoConfiguration implements EmbeddedServletContainerCustomizer,
        Ordered {

    @Value("${error.path:/error}")
    private String errorPath = "/error";

    @Autowired
    private ServerProperties properties;

    @Override
    public int getOrder() {
        return 0;
    }

    @Bean
    @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
    public DefaultErrorAttributes errorAttributes() {
        return new DefaultErrorAttributes();
    }

    @Bean
    @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
    public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
        return new BasicErrorController(errorAttributes);
    }

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.addErrorPages(new ErrorPage(this.properties.getServletPrefix()
                + this.errorPath));
    }

    @Configuration
    @ConditionalOnProperty(prefix = "error.whitelabel", name = "enabled", matchIfMissing = true)
    @Conditional(ErrorTemplateMissingCondition.class)
    protected static class WhitelabelErrorViewConfiguration {

        private final SpelView defaultErrorView = new SpelView(
                "<html><body><h1>Whitelabel Error Page</h1>"
                        + "<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>"
                        + "<div id='created'>${timestamp}</div>"
                        + "<div>There was an unexpected error (type=${error}, status=${status}).</div>"
                        + "<div>${message}</div></body></html>");

        @Bean(name = "error")
        @ConditionalOnMissingBean(name = "error")
        public View defaultErrorView() {
            return this.defaultErrorView;
        }

        // If the user adds @EnableWebMvc then the bean name view resolver from
        // WebMvcAutoConfiguration disappears, so add it back in to avoid disappointment.
        @Bean
        @ConditionalOnMissingBean(BeanNameViewResolver.class)
        public BeanNameViewResolver beanNameViewResolver() {
            BeanNameViewResolver resolver = new BeanNameViewResolver();
            resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
            return resolver;
        }

    }
}

What does this piece of configuration do?

  • It defines a bean, DefaultErrorAttributes, which exposes helpful error information via special attributes such as the status, error code, and associated stack trace.

  • It defines a BasicErrorController bean, which is an MVC controller in charge of displaying the error page we've seen.

  • It allows us to deactivate Spring Boot whitelabel error page by setting error.whitelable.enabled to false in our configuration file, application.properties.

  • We can also leverage our templating engine to provide our own error page. It will be named error.html, for example. This is what the condition ErrorTemplateMissingCondition checks.

We'll see how to properly handle errors later in this book.

As far as encoding is concerned, the very simple HttpEncodingAutoConfiguration function will handle it by providing Spring's CharacterEncodingFilter class. It is possible to override the default encoding ("UTF-8") with spring.http.encoding.charset and disable this configuration with spring.http.encoding.enabled.