javaspring-mvcannotationstuckey-urlrewrite-filtercohesion

Can routing urls in Spring framework be done easier?


Routing for a webapp in one place in one file e.g. yaml, xml or properties file to define the routing and urls for a webapp and connecting the urls with individual methods or functions seems like a good idea.Why doesn't Spring do it? The framework webapp2 is like that and easy to handle that way. A url routing scheme with a regex can look like good readability defined in yaml

handlers:
- url: /(amazonas.*|acre.*|alagoas.*|roraima-*|mato_grosso_do_sul*|pernambuco.*|bahia.*|rio_grande_do_sul.*|sao_paulo.*|goias.*|paraiba.*|piaui.*|ceara.*|amapa.*|tocantins.*|rondonia.*|sergipe.*|para.*|maranhao.*|rio_de_janeiro.*|rio_grande_do_norte.*|distrito_federal.*|espirito_santo.*|minas_gerais.*|parana.*|santa_catarina.*|rio_grande_do_sul.*)
  script: br.app

- url: /obrigado.txt
  static_files: static/obrigado.txt
  upload: static/obrigado.txt
  secure: optional
  expiration: "24h"

- url: /ai/cat_tmpl/0
  script: montao.app

Struts was also like that using xml for routing. Spring however does not have a good way to collect all your routing in one place. There's some in xml files, some as annotations (written directly above the method declaration in handlers) and some can be overridden with plugins such as the urlrewrite.

Why can't routing be gathered in one place for a Spring webapp? Wouldn't that be better design and a higher cohesion? It's also sometimes a problem that you can't have more than one webcontext for a webapp. It seems to be that the servlet specification doesn't allow more than one webcontext for a webapp and that it must be a bijection. Why?


Solution

  • Spring MVC is flexible enough to allow plugging another routing infrastructure. You should take a look at springmvc-router.

    Reverse routing is available as of Spring 4.1 (see SPR-5579) - but you can still vote for SPR-5757 if you'd like to see something like this in the framework.