2

Given the following request mapping on a Spring MVC controller:

@RequestMapping(method=GET, value="/users/{name}")
ModelAndView findUser(@PathVariable String name) {
    ...
}

How can I make it accept a @PathVariable with a dash in it?

The following works, passing in fred as the name:

GET /users/fred

However the following does not work, passing in null in place of the name:

GET /users/u-fred

I would appreciate suggestions on how to define the @PathVariable so it can accept dashed strings, for example, u-fred.

Thanks.

2
  • 1
    Just curious... do you have somesort of @InitBinder that will cause this problem? A string with dash(es) in it works fine for me, I use it a lot in my projects. Commented Jan 28, 2011 at 23:57
  • Dashes and underscores are perfectly legal characters if URL encoding is not used. I suppose you could do {foo}-{bar} and have 2 params, but that is completely unnecessary. Commented Jan 29, 2011 at 4:43

1 Answer 1

2

I just tested that with my spring-mvc 3.0.5 application and it works fine with a dash:

  • make sure you are running the latest version
  • make sure you are tracking the correct request (and not some fake one, for example a forgotten ajax request)
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. I want a variable containing a dash ("-") not a slash ("/"). I am on the latest version of Spring and am doing straight HTTP calls (no ajax, etc.).
@SingleShot - sorry, a typo - I tried with a dash and it worked.
Yes, spring-mvc 3.0.5 works with dash. I have just tested it two days ago.
Yep I can verify that too. One of our applications uses dashes in every request.
This also works fine for me. I was very confused by the 404 page I was receiving until I worked out that I had forgotten to add @ResponseBody to my method signature. I was mistaking a 404 for Spring failing to find my method. Just adding this in case anyone is doing a similarly idiotic thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.