encountering a problem when attempting to transfer data from JavaScript to a scriptlet in a JSP

I am currently facing a requirement where I need to transfer a value from JavaScript to a Scriplet in a JSP. Despite being aware that JavaScript runs on the client side and JSP on the server side, I have been unsuccessful in finding a suitable solution for this issue even after extensive online research. Both JavaScript and scriplet codes are included within the same JSP file.

 <script type="text/javascript">
   var strUrl = window.location.href;
   var aps = strUrl.toLowerCase().indexOf("values");
   var modifiedString = strUrl.substring(aps+8);
   var v = strUrl.indexOf(modifiedString);
   document.write(v);
</script>
 <%
    String st="<script>document.writeln(v)</script>";
    out.println("-----"+st);
    int pareseValue = Integer.parseInt(st);
    if(st.equals("0")){
      out.println("test");
     %>                     

   <h1><div class="xyz">
     <fmt:message>header.txt</fmt:message>
   </div></h1>                              

   <%
     }else{
   %>           

    <div class="pqr">
        <fmt:message>header1.txt</fmt:message>
   </div>
   <%
    }
   %>

The code above shows my attempt to pass a value from JavaScript to a scriplet. However, when trying to parse and convert the string into an integer, I encounter a NumberFormatException. It seems that the variable 'st' is not of a string type.

    String st="<script>document.writeln(v)</script>";
    out.println("-----"+st);
    int pareseValue = Integer.parseInt(st)

I am seeking guidance on identifying the problem with the code and resolving the issue at hand.

Thank you, Vikeng

Answer №1

When attempting to parse

"<script>document.writeln(v)</script>"
as an integer, it fails because the string contains non-numeric characters.

Despite appearances, the presence of <script> tags does not make the content executable or convertible into a numerical value. Enclosed in quotes, it is simply treated as a string by the parser. Therefore,

"<script>document.writeln(v)</script>"
is fundamentally equivalent to
"tic/v)neiwtm>oprs<citdun.rtl(<rp>"
.

This limitation arises from the unidirectional nature of scriptlets, which do not allow for passing values back and forth.

To establish communication between your page and Java, you must transmit parameters while invoking a designated handler.

As an illustration, asynchronous JavaScript can be utilized:

    var asyncHR = new XMLHttpRequest();
    var URL = "https://www.yourserver.com/intparser?st=v";
    asyncHR.open("GET", URL, true);
    asyncHR.send(); 

Subsequently, the request handler is responsible for handling the parameter st, processing it accordingly, updating the model with the new data, and triggering a page reload using JavaScript.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When an element is transferred to a different <div>, it does not automatically inherit its new CSS styles

There's an element with existing behavior that needs to be moved to meet new requirements without losing its original styles. The challenge is applying new styles to the element after it's been moved. For example: <div id="existingStructure" ...

Updating the contents of one specific div without affecting all other divs with the same class

Below is the HTML code snippet in question: <a class="btn test-btn test-btn-1"> <span>Content 1</span> </a> This particular code block appears multiple times on the page. The number at the end of test-btn- is dynamically generat ...

Having issues with unchecking checkboxes in ReactJS

I created a task management app and I thought of improving it by displaying all completed tasks when the "Show completed tasks" box is checked. https://i.stack.imgur.com/RkXsw.png The issue I'm facing is that while checking "Show completed tasks ...

Working with JSON data in JavaScript is proving to be challenging

Here is a json encoded result: { "result":[ { "CODE":"STC\/R\/935", "WAY":"In", "DATE":"2016-02-19", "TYPE":"Re-Entry", "TKTP":"NA", "TIME":"2016-02-23 17: ...

The error message "consts is not defined in React Carousel renderArrow" indicates

While working with the react-elastic-carousel package, I encountered an issue when attempting to implement my own custom arrows. This is the code snippet I used, which was borrowed from the documentation: function App() { return ( <div> ...

Tips for retrieving a value returned by a Google Maps Geocoder

geocoder.geocode( { 'address': full_address}, function(results, status) { lat = results[0].geometry.location.lat(); lng = results[0].geometry.location.lng(); alert(lat); // displays the latitude value correctly }); alert(lat); // does ...

Combining shared table rows with embedded ruby code in Javascript - is it possible?

I'm a new Javascript learner and I'm attempting to create a function that will merge rows with the same value (year in this case) and add their numbers together. Although my code isn't functioning as expected, it also doesn't seem to be ...

Implementing a Response to an AJAX POST Request with Servlets

I have a unique situation where I need to validate a username input in a text box. The process involves sending the entered username to a server for checking if it has already been taken by another user. If the username is available, I want to change the b ...

Tips for simulating a service in Angular unit tests?

My current service subscription is making a promise: getTaskData = async() { line 1 let response = this.getTaskSV.getTaskData().toPromise(); line 2 this.loading = false; } I attempted the following approach: it('should load getTaskData', ...

Creating a JSON object hashtable using jsHashtable: A step-by-step guide

I have a good understanding of how to create a hashtable from scratch using jshashtable. For instance: <script type="text/javascript" src="jshashtable.js"></script> <script type="text/javascript"> var typesHash = new Hashtable(); ...

Surprising symbol encountered: JavaScript, Node.js, and MongoDB

                 I am facing an unexpected identifier error while running the code below when trying to check if the documents' state has changed. Despite exhausting my Google search and looking for documentation on MongoDB, I am yet to find ...

"Mastering the art of route handling with Node.js and

I am seeking some assistance with routing in my Node/Express application. Initially, I successfully create a new business from the Business model. After creating the business, I intend to have a separate route that adds the current FX rates offered by that ...

Modify the href value by matching it with the parent div attribute

I am working on an HTML project <div class="1" style="" title="NeedthisText TextIDontneed"> <div class="2> <div class="3"> <a target="_blank" href="/NeedToChange/DispForm.aspx?ID=1"></a> </div> </div> &l ...

Static files fail to load in FastAPI

Recently, I decided to switch my project from using node.js to python FastAPI. While everything was running smoothly with node, I encountered an issue with my static files not being found in FastAPI. Here is the code snippet that I am using: from fastapi i ...

What are the steps for creating a JSON array in JavaScript?

Hello, I'm facing an issue with the following code: javascript var cadena="["; $('.box').each(function(){ var clase=$(this).attr("class"); var id_t=$(this).attr("id"); if(clase=="box ...

What is the best way to retrieve a specific value from a nested array that is within an array of objects

My goal is to extract a specific field value from a nested array within an object array. Using the map method, I attempted to achieve this but ended up with two empty arrays nested inside two empty objects. Though I am aware of this mistake, it indicates t ...

The Jquery function for setting the active navigation tab based on the URL is currently over-selecting and choosing more options

I have a customized Jquery function that assigns the 'active' class to my navigation anchors based on the URL. While this function generally works, the issue arises when tab 1 is active - tabs 10, 11, and 12 also get marked as active. The code s ...

Integrating Node.js with static HTML documents

I'm currently exploring methods for making node.js API calls from static HTML. While I've considered using Express and similar template engines, I am hesitant since they would require me to adjust my existing HTML to fit their templates. Typicall ...

Show information in a text field from JSON in SAPUI5

How can I populate a text box with data from JSON using SAPUI5? // Sample JSON data var data = { firstName: "John", lastName: "Doe", birthday: {day:01,month:05,year:1982}, address:[{city:"Heidelberg"}], enabled: true }; // Create a JS ...

Managing changes to object properties in Angular

I am encountering a situation where I have an object containing both an 'id' and 'name' property, structured like this: function format(id){ return '(' + id + ')'; } function MyObject(id){ this.id = id; this. ...