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 code 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.