Spring RequestMapping with a regular expression for all levels

53 views Asked by At

Let's say I need to map requests which don't have . to add a suffix for them, for example:

/a
/a/b
/a/b/c

but not

/a.html
/a/b.html
/a/b/c.html

I am able to map it with a a particular level, with something like the below, but that means a new mapping for each level, and I don't think this is the correct way.

I tried to use /** but then how to handle the values which I am not interested it (e.g. the ones with .?

@Controller
public class HtmlController {

  @RequestMapping("/{page:^[^.]*$}")
  public String oneLevel(@PathVariable("page") String page) {
    return '/' + page + ".html";
  }

  @RequestMapping("/{first}/{page:^[^.]*$}")
  public String twoLevels(@PathVariable("first") String first, @PathVariable("page") String page) {
    return '/' + first + '/' + page + ".html";
  }

 ...
}

1

There are 1 answers

1
Azadi Yazdani On

I suggest you to use an interceptor that extends HandlerInterceptorAdapter and in the preHandle method of it, you can reject all the requests which contain '.' in their URLs