0

I am using Java servlets with Tomcat to display a table of Places in HTML. The data in the table's rows consists of info like name, location, etc. and are obtained by taking the servlet response data and injecting it into the tags. Once this is done however, I need to use Javascript to manipulate the "td" elements based their values. So if one of the locations which went into a "td" element was "USA," my Javascript function would do something specific to the "USA" element, like make the surrounding border red, white and blue.

I do not want to send a request using $.ajax. I simply want to, within the scope of a script element, access the attributes returned by the servlet response like I do in the following way with JSP scriptlets

<% request.getAttribute("location"); %>

I'm kind of surprised I haven't found how to do this online because it seems like an daily action of anyone working with servlets and JS, but I've searched on SO and Google to no avail.

almel
  • 7,178
  • 13
  • 45
  • 58

3 Answers3

5

As explained by @CarlosGavidia (peruvian fellow), scriplets run in server side while JavaScript (and other frameworks on top of it like jQuery or Dojo) runs in client side e.g. in browser client. Also, scriptlets usage is highly discouraged, detailed explanation here: How to avoid Java code in JSP files?

If you accessed to the last link, you would know that you should use EL and JSTL to access to your page context (PageContext), request (ServletRequest), session (HttpSession) and/or application (ServletContext) attributes (more related info: How to pass parameter to jsp:include via c:set? What are the scopes of the variables in JSP?).

With this background, now you're able to understand that you can't directly access to request attributes (or others from Java code) unless they are set as part of the DOM or injected in javascript code. Showing examples for both cases:

  1. Setting the request attribute as part of the DOM.

    <input type="hidden" id="hidReqAttr" value="${location}" />
    <script type="text/javascript">
        function foo() {
            var fromJavaSide = document.getElementById("hidReqAttr").value;
            //fromJavaSide value will be ${location}
        }
    </script>
    
  2. Injecting the request attribute directly on JavaScript.

    <script type="text/javascript">
        function foo() {
            var fromJavaSide = '<c:out value="${location}" />';
            //fromJavaSide value will be ${location} as string
        }
    </script>
    

Note that using any of these approaches means that you can manipulate the Java server variable value using JavaScript but will work only on JavaScript side and won't affect the request attribute value set in the server side. In other words:

<script type="text/javascript">
    function foo() {
        var fromJavaSide = '<c:out value="${location}" />';
        //fromJavaSide value will be ${location} as string
        fromJavaSide = fromJavaSide + '_modified';
        //last line affects only the JavaScript variable, not the request attribute value
    }
</script>

So if one of the locations which went into a "td" element was "USA," my Javascript function would do something specific to the "USA" element, like make the surrounding border red, white and blue.

Use a HTML component with an ID or apply a CSS class name to your <td> to know where you will get your desired value. Using "USA" as example:

<td class="${location eq 'USA' ? 'usaStyle' : 'commonStyle'}">${location}</td>
<script type="text/javascript">
    function foo() {
        var usaTDs = document.getElementsByClassName('usaStyle');
        //now you have all TDs with usaStyle that has your `USA` text
    }
</script>

Based on your comment, you also want to access to request parameters (probably from a query String). Use ${param.parameterName} to get them. More info in the EL link above, check the Implicit EL objects section that explains about getting request parameters and other functionalities.

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Excellent response Luiggi. I had read that SO page you posted before,but combined with your explanation it's clearer now, especially with your last example. Funny thing is right now I'm going through some old code and change all scriptlets to JSTL and EL! – almel Jul 18 '13 at 15:32
  • I took away the green checkmark because I went back to my problem and I realized what you told doesn't help me for my specific problem. This is what I want to do: once the HTML is loaded, I need to know how to use JS to access response parameters/attributes (I know they're different, but it could be either one for my purposes) that were set in the servlet, and then use some JS code to manipulate those parameters/attributes. – almel Jul 18 '13 at 17:35
  • @almel if you don't explain your specific problem, you can't get a straight answer. Please **edit your question** and explain the real problem instead of posting it in a comment on my answer so future readers can benefit form both a good question and an accurate answer. – Luiggi Mendoza Jul 18 '13 at 17:37
0

HTML DOM manipulation should be done with JavaScript. JSP/Servlets are server-side programming techniques and objects like HTTPServletRequest can´t be accessed through JavaScript: That instances live in the Servlet Container and JavaScript executes in the Client Browser.

On the other side, I see no problems in changing TD Tag contents through pure JavaScript. You can ease this task using a toolkit like Dojo or JQuery.

Carlos Gavidia-Calderon
  • 7,145
  • 9
  • 34
  • 59
  • Okay, specifically how would I use Jquery/Javascript to access the HTTPServletRequest? Please supply generic (but not pseudocode) for accessing HTTPServletRequest. Thanks Carlos – almel Jul 17 '13 at 17:05
  • @almel is your Servlet accessed through an ajax call or what? Can you clarify this in your question? – Luiggi Mendoza Jul 17 '13 at 17:09
  • @LuiggiMendoza Nope, it is not accessed through an ajax call. The user, when viewing a certain web page, clicks on a link that goes to a servlet, which then queries a database for Place values, sets them as attributes in the response, and then serves that response by redirecting the user to a .jsp file for viewing. That is how the servlet is accessed. In the jsp I can access the servlet's Places data by using JSP scriptlets, but I want to be able to use Javascript/Jquery to access the servlet data so that the page can be altered at runtime. – almel Jul 17 '13 at 17:53
0
using ajax cal we can cal directly to our servlet class and   servlet return string in json format(using gson lib) we can parse json using jquery parse method     
 $.ajax({
        url: "controller/url", 
         success: function(result){
                alert(result);
            }});
Pradip Wawge
  • 133
  • 4