where should we place HIDDEN variable in JSP
I need to use hidden variables in my JSP for session tracking. This is the code:
<input type="hidden" name="REQ_TOKEN" value="<%=session.getAttribute("SESN_TOKEN").toString()%>" />
I am using this to compare the request token with session token, so only when both are equal I will evaluate that request otherwise I will throw an error.
Now the problem is, when I place this cod开发者_运维技巧e inside <form></form>
tags, it is working fine. Unfortunately there are some JSPs in my application where we dont have <form>
tag (I know that sounds weird!). Where can I place my code so that it will work?
Can't i use Hidden variables without <form>
tag?
It sounds like the hidden value you're describing is what is more commonly refered to as a nonce, which (when talking about web forms) is a value used to verify that a form is submitted only once, and by the same session that requested the form. See these notes on preventing cross-site request forgery.
Firstly, how are you submitting requests without a <form>
? Is the user simply clicking a link? If so, you can append the nonce to the query string, but if you're using GET requests for something destructive that actually requires verification of a nonce, you're doing it wrong. These types of requests should only be made via POST, which implies generating a <form method="post">
.
Secondly, no, you can't use <input type="hidden" />
outside of a form. A given form only submits its own values, that is, elements between <form>
and </form>
.
If you want your hidden value to be included in the data being posted back, your must include the hidden input within the form being submitted. If, as you say, you cannot include the needed <form>
tags in your JSP files, you could dynamically make the request via Javascript, but this introduces a dependency on Javascript that you should avoid for something so simple and fundamental.
As far as I know you need to have the hidden field in a form tag for it to work correctly. Still looking it up, will repost
. The sites so far that I have found say that they should be within the form.
EDIT* roseindia.net/jsp/jspsession/HiddenForm
If it is just for CSRF prevention, then you don't need it at all at formless pages. Simply because there's nothing to protect :) The point is to include it in each <form method="post">
, not in each page.
That said, "session tracking" is an entirely different concept. The HttpSession
already does exactly that behind the scenes with help of a cookie or URL rewriting. That's why I found your question initially confusing and posted a comment for clarification. You here just want "request tracking" with help of a request based token which you store in the session scope (and remove immediately once the request has passed) so that you can prevent CSRF.
Update: you may find this answer useful to learn more about what CSRF actually is.
精彩评论