Posts Tagged ‘Spring MVC’
  • Fully configurable mappings for Spring MVC

    Spring Boot logog

    As I wrote some weeks earlier, I’m trying to implement features of the Spring Boot actuator in a non-Boot Spring MVC applications. Developing the endpoints themselves is quite straightforward. Much more challenging, however, is to be able to configure the mapping in a properties file, like in the actuator. This got me to check more closely at how it was done in the current code. This post sums up my “reverse-engineering” attempt around the subject.

    Standard MVC


    In Spring MVC, in a class annotated with the @Controller annotation, methods can be in turn annotated with @RequestMapping. This annotation accepts a value attribute (or alternatively a path one) to define from which path it can be called.

    The path can be fixed e.g. /user but can also accepts variables e.g. /user/{id} filled at runtime. In that case, parameters should can be mapped to method parameters via @PathVariable:

    @RequestMapping(path = "/user/{id}", method = arrayOf(RequestMethod.GET))
    fun getUser(@PathVariable("id") id:String) = repository.findUserById(id)

    While adapted to REST API, this has to important limitations regarding configuration:

    • The pattern is set during development time and does not change afterwards
    • The filling of parameters occurs at runtime


    With the above, mappings in @Controller-annotated classes will get registered during context startup through the DefaultAnnotationHandlerMapping class. Note there’s a default bean of this type registered in the context. This is summed up in the following diagram:

    DefaultAnnotationHandlerMapping sequence diagram

    In essence, the magic applies only to @Controller-annotated classes. Or, to be more strict, quoting the DefaultAnnotationHandlerMapping’s Javadoc:

    Annotated controllers are usually marked with the Controller stereotype at the type level. This is not strictly necessary when RequestMapping is applied at the type level (since such a handler usually implements the org.springframework.web.servlet.mvc.Controller interface). However, Controller is required for detecting RequestMapping annotations at the method level if RequestMapping is not present at the type level.



    Spring Boot actuator allows for configuring the path associated with each endpoint in the file (or using alternative methods for Boot configuration).

    For example, the metrics endpoint is available by default via the metrics path. But’s it possible to configure a completely different path:

    Also, actuator endpoints are by default accessible directly under the root, but it’s possible to group them under a dedicated sub-context:


    With the above configuration, the metrics endpoint is now available under the /manage/mymetrics.


    Additional actuator endpoints should implements the MvcEndpoint interface. Methods annotated with @RequestMapping will work in the exact same way as for standard controllers above. This is achieved via a dedicated handler mapping, EndpointHandlerMapping in the Spring context.

    HandlerMapping to map Endpoints to URLs via Endpoint.getId(). The semantics of @RequestMapping should be identical to a normal @Controller, but the endpoints should not be annotated as @Controller (otherwise they will be mapped by the normal MVC mechanisms).

    The class hierarchy is the following:

    MvcEndpoint class diagram

    This diagram shows what’s part of Spring Boot and what’s not.


    Actuator endpoints reuse some from the existing Spring MVC code to handle @RequestMapping. It’s done in a dedicated mapping class so as to separate standard MVC controllers and Spring Boot’s actuator endpoint class hierarchy. In order to achieve fully configurable mappings in Spring MVC, this is the part of the code study, to duplicate and to adapt should one wants fully configurable mappings.

    Categories: JavaEE Tags: Spring MVCactuatorSpring Boot
  • Metrics, metrics everywhere

    With DevOps, metrics are starting to be among the non-functional requirements any application has to bring into scope. Before going further, there are several comments I’d like to make:

    1. Metrics are not only about non-functional stuff. Many metrics represent very important KPI for the business. For example, for an e-commerce shop, the business needs to know how many customers leave the checkout process, and in which screen. True, there are several solutions to achieve this, though they are all web-based (Google Analytics comes to mind) and metrics might also be required for different architectures. And having all metrics in the same backend mean they can be correlated easily.
    2. Metrics, as any other NFR (e.g. logging and exception handling) should be designed and managed upfront and not pushed in as an afterthought. How do I know that? Well, one of my last project focused on functional requirement only, and only in the end did project management realized NFR were important. Trust me when I say it was gory - and it has cost much more than if designed in the early phases of the project.
    3. Metrics have an overhead. However, without metrics, it's not possible to increase performance. Just accept that and live with it.

    The inputs are the following: the application is Spring MVC-based and metrics have to be aggregated in Graphite. We will start by using the excellent Metrics project: not only does it get the job done, its documentation is of very high quality and it’s available under the friendly OpenSource Apache v2.0 license.

    That said, let’s imagine a “standard” base architecture to manage those components.

    First, though Metrics offer a Graphite endpoint, this requires configuration in each environment and this makes it harder, especially on developers workstations. To manage this, we’ll send metrics to JMX and introduce jmxtrans as a middle component between JMX and graphite. As every JVM provides JMX services, this requires no configuration when there’s none needed - and has no impact on performance.

    Second, as developers, we usually enjoy develop everything from scratch in order to show off how good we are - or sometimes because they didn’t browse the documentation. My point of view as a software engineer is that I’d rather not reinvent the wheel and focus on the task at end. Actually, Spring Boot already integrates with Metrics through the Actuator component. However, it only provides GaugeService - to send unique values, and CounterService - to increment/decrement values. This might be good enough for FR but not for NFR so we might want to tweak things a little.

    The flow would be designed like this: Code > Spring Boot > Metrics > JMX > Graphite

    The starting point is to create an aspect, as performance metric is a cross-cutting concern:

    public class MetricAspect {
        private final MetricSender metricSender;
        public MetricAspect(MetricSender metricSender) {
            this.metricSender = metricSender;
        @Around("execution(**(..)) ||execution(**(..))")
        public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
            StopWatch stopWatch = metricSender.getStartedStopWatch();
            try {
                return pjp.proceed();
            } finally {
                Class<?> clazz = pjp.getTarget().getClass();
                String methodName = pjp.getSignature().getName();
                metricSender.stopAndSend(stopWatch, clazz, methodName);

    The only thing outside of the ordinary is the usage of autowiring as aspects don’t seem to be able to be the target of explicit wiring (yet?). Also notice the aspect itself doesn’t interact with the Metrics API, it only delegates to a dedicated component:

    public class MetricSender {
        private final MetricRegistry registry;
        public MetricSender(MetricRegistry registry) {
            this.registry = registry;
        private Histogram getOrAdd(String metricsName) {
            Map<String, Histogram> registeredHistograms = registry.getHistograms();
            Histogram registeredHistogram = registeredHistograms.get(metricsName);
            if (registeredHistogram == null) {
                Reservoir reservoir = new ExponentiallyDecayingReservoir();
                registeredHistogram = new Histogram(reservoir);
                registry.register(metricsName, registeredHistogram);
            return registeredHistogram;
        public StopWatch getStartedStopWatch() {
            StopWatch stopWatch = new StopWatch();
            return stopWatch;
        private String computeMetricName(Class<?> clazz, String methodName) {
            return clazz.getName() + '.' + methodName;
        public void stopAndSend(StopWatch stopWatch, Class<?> clazz, String methodName) {
            String metricName = computeMetricName(clazz, methodName);

    The sender does several interesting things (but with no state):

    • It returns a new StopWatch for the aspect to pass back after method execution
    • It computes the metric name depending on the class and the method
    • It stops the StopWatch and sends the time to the MetricRegistry
    • Note it also lazily creates and registers a new Histogram with an ExponentiallyDecayingReservoir instance. The default behavior is to provide an UniformReservoir, which keeps data forever and is not suitable for our need.

    The final step is to tell the Metrics API to send data to JMX. This can be done in one of the configuration classes, preferably the one dedicated to metrics, using the @PostConstruct annotation on the desired method.

    public class MetricsConfiguration {
        private MetricRegistry metricRegistry;
        public MetricSender metricSender() {
            return new MetricSender(metricRegistry);
        public void connectRegistryToJmx() {
            JmxReporter reporter = JmxReporter.forRegistry(metricRegistry).build();

    The JConsole should look like the following. Icing on the cake, all default Spring Boot metrics are also available:

    Sources for this article are available in Maven “format”.

    To go further:

  • Sanitizing webapp outputs as an an afterthought

    For sure, software security should be part of every developer’s requirements: they should be explained and detailed before development. Unfortunately, it happens in real life that this is not always the case. Alternatively, even when it is, developers make mistakes and/or have to make with tight (read impossible) plannings. In the absence of security checks automated tools, sooner or later, an issue will appear.

    I’ve been thinking about a way to sanitize the output of a large-scale legacy Spring MVC application in a reliable way (i.e. not go on each page to fix issues). Basically, there are 4 ways output is displayed in the HTML page.

    # Name Sample snippet Description
    1 Form taglib <form:input path="firstName"> Outputs a bean attribute
    2 Spring taglib <spring:message code=""> Outputs a message from a properties file
    3 Java Standard Taglib Library <c:out value="${pageContext.request.requestURI}" /> Outputs a value
    4 Expression Language <span>${pageContext.request.requestURI}</span> Outputs a value

    Spring taglibs

    Spring taglibs are a breeze to work with. Basically, Spring offers multiple ways to sanitize the output, each scope parameter having a possibility to be overridden by a narrower one:

    1. Application scoped, with the boolean defaultHtmlEscape context parameter {% highlight xml %} defaultHtmlEscape true {% endhighlight %}
    2. Page scoped (i.e. all forms on page), with the <spring:defaultHtmlEscape> tag
    3. Tag scoped, with the htmlEscape attribute of the tag

    There’s only one catch; the <spring:message> tag can take not only a code (the key in the property file) but also arguments - however, those are not escaped:

    Hello, ${0} ${1}

    A possible sanitization technique consists of the following steps:

    1. Create a new SanitizeMessageTag:
      • Inherit from Spring's MessageTag
      • Override the relevant revolveArguments(Object) method
      • Use the desired sanitization technique (Spring uses its own HtmlUtils.htmlEscape(String))
    2. Copy the existing Spring TagLib Descriptor and create a new one out of it
    3. Update it to bind the message tag to the newly created SanitizeMessageTag class
    4. Last but not least, override the configuration of the taglib in the web deployment descriptor: {% highlight xml %} /WEB-INF/tld/sanitized-spring-form.tld {% endhighlight %} By default, the JavaEE specifications mandates for the container to look for TLDs insides JARs located under the WEB-INF/lib directory. It is also possible to configure them in the web deployment descriptor. However, the configuration takes precedence over automatic scanning.

    This way, existing JSP using the Spring taglib will automatically benefit from the new tag with no page-to-page update necessary.


    The <c:out> tag works the same way as the <spring:message> one, the only difference being there’s no global configuration parameter, only a escapeXml tag attribute which defaults to false.

    The same technique as above can be used to default to true instead.


    The EL syntax enables output outside any taglib so that the previous TLD override technique cannot be used to solve this.

    Not known to many developers, EL snippets are governed by so-called EL resolvers. Standard application servers (including servlet containers like Tomcat) provide standard EL resolvers, but it is also possible to add others at runtime.

    Note: though only a single EL resolver can be set in the JSP context, the resolver hierarchy implements the Composite pattern, so it’s not an issue.

    Steps required to sanitize EL syntax by default are:

    1. Subclasses relevant necessary EL resolvers - those are ScopedAttributeELResolver, ImplicitObjectELResolver and BeanELResolver, since they may return strings
    2. For each, override the getValue() method:
      • Call super.getValue()
      • Check the return value
      • If it is a string, sanitize the value before returning it, otherwise, leave it as it is
    3. Create a ServletContextListener to register these new EL resolvers {% highlight java %} public class SanitizeELResolverListener implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); JspFactory jspFactory = JspFactory.getDefaultFactory(); JspApplicationContext jspApplicationContext = jspFactory.getJspApplicationContext(context); ELResolver sber = new SanitizeBeanELResolver(); jspApplicationContext.addELResolver(sber); // Register other EL resolvers } } {% endhighlight %}


    Trying to sanitize the output of an application after it has been developed is not the good way to raise developers concerns about security. However, dire situations require dire solutions. When the application has already been developed, the above approaches - one for taglibs, one for EL, show how to achieve this in a way that does not impact existing code and get the job done.

    Categories: JavaEE Tags: JSTLsecuritySpring MVC
  • Chaining URL View resolvers in Spring MVC

    Standard Java EE forward to internal resources go something like this:

    public class MyServlet extends HttpServlet {
      public void doGet(HttpServletRequest req, HttpServletResponse resp) {
        req.getRequestDispatcher("/WEB-INF/page/my.jsp").forward(req, resp);

    Admittedly, there’s no decoupling between the servlet code and the view technology, even not with the JSP location.

    Spring MVC introduces the notion of ViewResolver. The controller just handles logical names, mapping between the logical name and the actual resource is handled by the ViewResolver. Even better, controllers are completely independent from resolvers: just registering the latter in the Spring context is enough.

    Here’s a very basic controller, notice there’s no hint as to the final resource location.

    public class MyController {
      public String displayLogicalResource() {
        return "my";

    Even better, there’s nothing here as to the resource nature; it could be a JSP, an HTML, a Tiles, an Excel sheet, whatever. Each has a location strategy based on a dedicated ViewResolver. The most used resolver is the InternalResourceViewResolver; it meant to forward to internal resources, most of the time, JSPs. It is initialized like this:

      public ViewResolver pageViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
      return resolver;

    Given this view resolver available in the Spring context, the logical name "my" will tried to be resolved with the "/WEB-INF/page/my.jsp" path. If the resource exists, fine, otherwise, Spring MVC will return a 404.

    Now, what if I’ve different folders with JSP? I expect to be able to configure two different view resolvers, one with a certain prefix, the other with a different one. I also expect them to be checked in a determined order, and to fallback from the first to the last. Spring MVC offers multiple resolvers with deterministic order, with a big caveat: it does not apply to InternalResourceViewResolver!

    Quoting Spring MVC Javadoc:

    When chaining ViewResolvers, an InternalResourceViewResolver always needs to be last, as it will attempt to resolve any view name, no matter whether the underlying resource actually exists.

    This means I cannot configure two InternalResourceViewResolver in my context, or more precisely I can but the first will terminate the lookup process. The reasoning behind (as well as the actual code), is that the resolver gets an handle on the RequestDispatcher configured with the resource path. Only much later is the dispatcher forwarded to, only to find that it does not exist.

    To me, this is not acceptable as my use-case is commonplace. Furthermore, configuring only "/WEB-INF" for prefix and returning the rest of the path ("/page/my")  is out of the question as it ultimately defeats the purpose of decoupling the logical name from the resource location. Worst of all, I’ve seen controller code such as the following to cope with this limitation:

    return getViews().get("my"); // The controller has a Map view property with "my" as key and the complete path as the "value"

    I think there must be some more Spring-ish way to achieve that and I’ve come to what I think is an elegant solution in the form of a ViewResolver that checks if the resource exists.

    public class ChainableUrlBasedViewResolver extends UrlBasedViewResolver {
      public ChainableUrlBasedViewResolver() {
      protected AbstractUrlBasedView buildView(String viewName) throws Exception {
        String url = getPrefix() + viewName + getSuffix();
        InputStream stream = getServletContext().getResourceAsStream(url);
        if (stream == null) {
          return new NonExistentView();
        return super.buildView(viewName);
      private static class NonExistentView extends AbstractUrlBasedView {
        protected boolean isUrlRequired() {
            return false;
        public boolean checkResource(Locale locale) throws Exception {
          return false;
        protected void renderMergedOutputModel(Map<String, Object> model,
                                               HttpServletRequest request,
                                               HttpServletResponse response) throws Exception {
          // Purposely empty, it should never get called

    My first attempt was trying to return null within the buildView() method. Unfortunately, there was some NPE being thrown later in the code. Therefore, the method returns a view that a. tells caller that the underlying resource does not exist b. does not allow for its URL to be checked (it also fails at some point if this is not set).

    I’m pretty happy with this solution, as it enables me to configure my context like that:

    @ComponentScan(basePackages = "")
    public class WebConfig {
      public ViewResolver pageViewResolver() {
        UrlBasedViewResolver resolver = new ChainableUrlBasedViewResolver();
        return resolver;
      public ViewResolver jspViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        return resolver;

    Now, I’m pretty well inside Spring philosophy: I’m completely decoupled, and I’m using Spring nominal resolver ordering. The only con is that one resource can shadow another another by having the same logical name pointing to different resources given different view resolvers. As it is already the case with multiple view resolvers, I’m ready to accept the risk.

    A showcase project can be found here in IntelliJ IDEA/Maven format.

    Categories: JavaEE Tags: Spring MVC
  • Spring 3.2 sweetness

    Even the most extreme Spring opponents have to admit it is all about making developers life easier. Version 3.2 of Spring MVC brings even more sweetness to the table.

    Sweetness #1: No web.xml

    The ability to run a webapp without any web deployment descriptor comes from Servlet 3.0.

    One option would be to annotate your servlet with the @WebServlet annotation to set mapping and complementary data. When you get your servlet for free, like Spring’s DispatcherServlet, you’d need to subclass you servlet for no other purpose than adding annotation(s).

    Alternatively, Servlet 3.0 offers a way to both programmatically register servlets in the container and to offer hooks at startup through the ServletContainerInitializer interface. The container will call the onStartup() method of all concrete implementation at webapp startup. The Spring framework leverages this feature to do so for WebApplicationInitializer instances.

    Spring MVC 3.2 provides such an implementation - AbstractContextLoaderInitializer, to programmatically register the DispatcherServlet. This means that as soon as the spring-webmvc jar is in the WEB-INF/lib folder of the webapp, you’ve got the Dispatcher servlet up and ready.

    This replaces both the servlet and servlet mapping and the context listener declarations in the web.xml.

    Sweetness #2: Easy Java configuration integration

    Java configuration is the way to configure Spring injection explicitly in a typesafe way. I won’t go into the full demonstration of it, as I already wrote about that some time ago.

    Earlier Spring versions provided a way to use Java configuration classes instead of XML files in the web deployment descriptor. Spring 3.2 offers AbstractAnnotationConfigDispatcherServletInitializer, a AbstractContextLoaderInitializer subclass with hooks for Java configuration classes.

    Your own concrete subclass has to implement methods to define servlet mappings, as well as root and web Java configuration classes:

    public class SugarSpringWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
        protected Class<?>[] getRootConfigClasses() {
            return new Class[] { JavaConfig.class };
        protected Class<?>[] getServletConfigClasses() {
            return new Class[] { WebConfig.class };
        protected String[] getServletMappings() {
            return new String[] { "/" };

    At this point, you just need to create those configuration classes.

    Sweetness #3: integration testing at the mapping level

    Your code should be unit-tested, that is tested in isolation to ensure that each method is bug-free, and integration-tested to ensure that collaboration between classes yield expected results.

    Before v. 3.2, the Spring test framework let you assemble your configuration classes / files easily enough. The problem lay in the way you would call entry-points - the controllers. You could call methods of those controllers, but not the mappings, leaving those untested.

    With v. 3.2, Spring Test brings a whole MVC testing framework which entry-points are mappings. This way, instead of testing method x() of controller C, you would test a request to /z, letting Spring MVC handle it so we can check for expected results.

    The framework also provide expectations for view returning, forwarding, redirecting, and model attribute setting, all with the help of a specific DSL:

    public class SayHelloControllerIT extends AbstractTestNGSpringContextTests {
        private MockMvc mockMvc;
        public void setUp() {
            mockMvc = webAppContextSetup((WebApplicationContext) applicationContext).build();
        @Test(dataProvider = "pathParameterAndExpectedModelValue")
        public void accessingSayhelloWithSubpathShouldForwardToSayHelloJspWithModelFilled(String path, String value) throws Exception {
            mockMvc.perform(get("/sayHello/Jo")).andExpect(view().name("sayHello")).andExpect(model().attribute("name", "Jo"));

    The project for this article can be downloaded in Eclipse/Maven format.

    To go further:

    • The entire set of new features is available here
    Categories: JavaEE Tags: integration testingspringSpring MVC