1

I have a URI mapping in my custom controller given below :

http://localhost:8080/abc/{id}

Now, for normal values in id, it's not creating any problem.

When id contains a #, the content gets trimmed.

For example: for id = 123#qqq, then @PathVariable makes it 123

How to resolve this issue ?

Andrzej Sydor
  • 1,373
  • 4
  • 13
  • 28
NVJ
  • 39
  • 1
  • 6
  • 4
    `#` is a special character. You need to uri escape it. – dan1st Sep 25 '20 at 05:06
  • why do you need to insert `#` ? if you want to append multiple value, use `queryString` – user404 Sep 25 '20 at 05:07
  • 2
    Basically, something like `index.html#abc` means `index.html` at id `abc`. The same is the case with query strings. – dan1st Sep 25 '20 at 05:07
  • 3
    Isn't '#' an anchor...a place within the resource, like a place on a web page.? So then it is being stripped because it isn't part of the specification of the resource itself. Maybe this will be enough justification to escape it. – CryptoFool Sep 25 '20 at 05:28
  • 1
    The same (explanations) would hold for `/` in a path variable. Though for URL parameters one could use `URLEncoder.encode(pathVar, "UTF-8")` here I would definitely refrain from problematic chars. – Joop Eggen Sep 25 '20 at 05:31
  • 1
    This is fundamental to how URIs and HTTP work and has nothing to do with Spring. If you examine your Network tab, you'll see that your browser doesn't even transmit that part. – chrylis -cautiouslyoptimistic- Sep 25 '20 at 06:07

1 Answers1

0

You basically have 2 options:

1) Keep id as Path Variable and escape the #

As already mentioned in the comments # is a special character in URIs normally reserved to refer anchor positions on the webpage. If you want to use it as a path variable you will have to escape it:

http://localhost:8080/abc/123%23qqq 

Will yield your desired id = 123#qqq

2) Use a Request Parameter instead

This seems to to me the cleaner solution. If you have to have the # as part of your id, you should propably just encode it as a String in a request parameter:

public void fooBar(@Requestparam String id) {
   // do stuff
}

This way you won't have to worry about URI encodings since your # character will be interpreted as a String.

T A
  • 1,677
  • 4
  • 21
  • 29