What is the behavior of Hash(#) in query string

柔情痞子 提交于 2019-12-09 09:30:21

问题


I am sending the below url with query string. In the query string one parameter "approverCmt" has value with hash(#).

    "/abc/efd/xyz.jas?approverCmt=Transaction Log #459505&batchNm=XS_10APR2015_082224&mfrNm=Timberland"

In server side when I tried to retrieve it from the request I get

    approverCmt = Transaction Log  -----> "#459505" is missing
    batchNm = null
    mfrNm = null

And If I remove hash(#) from query string or If I replace # with %23 every thing works fine

I don't understand why I am getting null for one parameter if another parameter contains a hash(#) symbol.

Appreciate if any one can explain.


回答1:


This is known as the "fragment identifier".

As mentioned in wikipedia:

The fragment identifier introduced by a hash mark # is the optional last part of a URL for a document. It is typically used to identify a portion of that document.

The part after the # is info for the client. It is not sent to the server. Put everything only the browser needs here.

You can use the encodeURIComponent() function in JavaScript to encode special characters in a URL, so that # characters are converted to other characters that way you can be sure your whole URL will be sent to the server.




回答2:


The Hash value is for the anchor, so it is only client-side, it is often used in client-side framework like angular for client-side routing.

The anchor is NOT available server-side.

In your case you don't need an anchor, but a parameter value with a # break the query string the value is "Transaction Log #459505".

EDIT Naive solution that doesn't work, just let it ther for history, See Real solution below

The solution is to encode client-side and decode serveur-side

Encoding in javascript

   encodeURI("Transaction Log #459505")
   //result value "Transaction%20Log%20#459505"

Decode in Java

 java.net.URLDecoder.decode("Transaction%20Log%20#459505");
  //result  "Transaction Log #459505"

EDIT: But: Javascript doesn't encode in the same way than Java So the correct answer (I hope) is to manually replace all your # with %23, then Java will decode it normally, or to use encodeURIComponent as suggested in comments. For your need the replace solution seem to be enough.

Encode in Javascript:

encodeURI("yourUrl/Transaction Log #459505").replace(/#/,"%23")
//result: yourUrl/Transaction%20Log%20%23459505

The decode in Java doesn't change

java.net.URLDecoder.decode("Transaction%20Log%20#459505")
// result (java.lang.String) Transaction Log #459505

Sorry for long post, I didn't see the difference bettween Java and the JavaScrip Url encoding




回答3:


the hash is an anchor:

see wikipedia for more information



来源:https://stackoverflow.com/questions/29841137/what-is-the-behavior-of-hash-in-query-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!