java – Reading a JSP variable from JavaScript-ThrowExceptions

Exception or error:

How can I read/access a JSP variable from JavaScript?

How to solve:



or full example

<script language="javascript"> 

function access(){ 
  <% String str="Hello World"; %>
   var s="<%=str%>"; 


<body onload="access()"> 


Note: sanitize the input before rendering it, it may open whole lot of XSS possibilities


The cleanest way, as far as I know:

  1. add your JSP variable to an HTML element’s data-* attribute
  2. then read this value via Javascript when required

My opinion regarding the current solutions on this SO page: reading “directly” JSP values using java scriplet inside actual javascript code is probably the most disgusting thing you could do. Makes me wanna puke. haha. Seriously, try to not do it.

The HTML part without JSP:

<body data-customvalueone="1st Interpreted Jsp Value" data-customvaluetwo="another Interpreted Jsp Value">
    Here is your regular page main content

The HTML part when using JSP:

<body data-customvalueone="${beanName.attrName}" data-customvaluetwo="${beanName.scndAttrName}">
    Here is your regular page main content

The javascript part (using jQuery for simplicity):

<script type="text/JavaScript" src="//"></script>
<script type="text/javascript">
        var valuePassedFromJSP = $("body").attr("data-customvalueone");
        var anotherValuePassedFromJSP = $("body").attr("data-customvaluetwo");

        alert(valuePassedFromJSP + " and " + anotherValuePassedFromJSP + " are the values passed from your JSP page");

And here is the jsFiddle to see this in action



Assuming you are talking about JavaScript in an HTML document.

You can’t do this directly since, as far as the JSP is concerned, it is outputting text, and as far as the page is concerned, it is just getting an HTML document.

You have to generate JavaScript code to instantiate the variable, taking care to escape any characters with special meaning in JS. If you just dump the data (as proposed by some other answers) you will find it falling over when the data contains new lines, quote characters and so on.

The simplest way to do this is to use a JSON library (there are a bunch listed at the bottom of ) and then have the JSP output:

<script type="text/javascript">
    var myObject = <%= the string output by the JSON library %>;

This will give you an object that you can access like:


in the JS.


   <% String s="Hi"; %>
   var v ="<%=s%>"; 


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>JSP Page</title>
          <% String name = "" ;%> // jsp vari
         var name = "<%=name %>" // call var to js
         $("#id").html(name); //output to html

    <h1 id='id'>!</h1>

Leave a Reply

Your email address will not be published. Required fields are marked *