9

When loading a page, I have the following in my controller:

request.setAttribute("myAtt", "Testing");

I want to access this in my JSP file. In the HTML section, I am familiar with using things like:

${myAtt} ${requestScope.myAtt}

and the like. However, I've never been sure how to access request parameters in JavaScript. I've tried a number of things, such as:

var jsAtt = ${myAtt};
var jsAtt = '${myAtt}';
var jsAtt = eval(${myAtt});
var jsAtt = eval('${myAtt}');

etc, but nothing seems to work.

Is there a way to grab request attributes via JavaScript? Please no jQuery, servlets, etc. I want pure JavaScript code.

I am kind of amazed I didn't find this already asked. So sorry if it is a duplicate and I just didn't see the orignal.

4 Answers 4

17

Using the following should work.

var jsAtt = '${myAtt}';

I think I stumbled across issues because of trying to dynamically generate the string based off my needs, which JavaScript seems to not like. For example, this would have issues:

var counter = 1;
var jsAtt = '${myAtt' + counter + '}';

JavaScript seems to recognize the request parameter syntax, but only if it's completely predetermined.

Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work , I tried in this way. > var jsAtt = '${queryCategory}'; > console.log("value is :"+jsAtt); output: value is :${queryCategory}
0

For GET requests you can get the values from the QueryString. Check this page: http://www.thimbleopensource.com/tutorials-snippets/get-request-parameters-using-javascript

I am not sure about POST requests though.

Comments

0

Put the following code inside the head tag of your jsp page (not in a js file) :

<script type="text/javascript">
var jsAtt = '<%= request.getAttribute("myAtt") %>';
</script>

But your string must NOT contains the simple quote because it will break the interpretation of the String in the jsp.

If you need String with simple quote, you will need, for example, to replace them on the server side by "&#39;" :

request.setAttribute("myAtt", myAtt.replaceAll("'", "&#39;"));

And replace it again in your JSP :

<script type="text/javascript">
var jsAtt = '<%= request.getAttribute("myAtt") %>';
jsAtt = jsAtt.replace(/&#39;/g, "'");
</script>

For Object instead of String, you can use JSON to pass them as a String.

Comments

-1

I have not tested this but have you tried this?

${pageContext.request.myAtt}

1 Comment

No luck. I don't think JavaScript likes the ${...} syntax at all.

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.