Transferring a variable from a scriplet to JSP with the issue of a null

Seeking assistance with passing a variable from a scriptlet in one jsp to the 'calling jsp'

The scenario involves assetedit.jsp posting a binary stream to upload.jsp. However, despite the processing of the stream in upload.jsp and determination of a filepath, I am unable to access this value in assetedit.jsp as it returns null pointer.

I have attempted various solutions, including using asynchronous calls within the post method to potentially slow down the process, but nothing seems to work.

Your thoughts on the matter would be greatly appreciated.

Snippet of assetedit.jsp -

//post binary to upload.jsp
$.ajax({
url: '/wz/upload.jsp',
data: decodedstring,
type: 'POST',
contentType: false,
processData: false,
}).done(function(data) {
console.log(data);
});     

Partial code from upload.jsp (for clarity) -

<%
try {
String root = getServletContext().getRealPath("/uploads/"); 
BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
String nm = System.currentTimeMillis() + ".jpg";
String filepath = root + "/" + nm;
String realpath = (filepath.substring(filepath.lastIndexOf("/") - 7));
System.out.println("realpath is   "  + realpath);
pageContext.setAttribute("pathtogo", realpath);

}
fos.close();
bis.close();
);
} catch (Exception ex) {
ex.printStackTrace();
}
%>

Another snippet from assetedit.jsp -

<%
String str = request.getAttribute("pathtogo").toString();
System.out.println("pathtogo is   "  + str);
%>  

Additional attempt made in assetedit.jsp -

<%
        String name=(pageContext.getAttribute("pathtogo").toString()); 
        System.out.println("pathtogo is "+name); 
%>

However, these attempts result in an error - Uncaught TypeError: getElemRefs(...) is null

I welcome any suggestions or insights on whether another post action in upload.jsp is needed to send pathtogo back to assetedit.jsp?

Thanks for your help,

Answer №1

Have you considered using Session Scope to pass variables between different JSP Pages efficiently?

pageContext.setAttribute("pathtogo",realPath,PageContext.SESSION_SCOPE);  
    
pageContext.getAttribute("pathtogo",PageContext.SESSION_SCOPE);  

Check out the documentation for more information.

---- Edited ----

Let's explore another approach:

upload.jsp

session.setAttribute("pathtogo",realPath);

assetedit.jsp -

<%
String str = (String)session.getAttribute("pathtogo");

System.out.println("pathtogo is   "  + str);
%>  

Alternatively, use

String.valueOf(session.getAttribute("pathtogo"));

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

The mongoose fails to establish a connection with the Mongo Db Atlas

I am having issues with my simple node express app when trying to connect to MongoDB atlas. Despite deleting node_modules and re-downloading all packages, I am still encountering the same error. The specific error message reads as follows: Cannot read pro ...

"Exploring the possibilities of Ajax in conjunction with Sol

I recently completed a tutorial on Ajax Solr and followed the instructions in step one. Below is the code I wrote: header.php: <script type="text/javascript" src="static/js/ajax-solr/core/Core.js"></script> <script type="text/javascript" s ...

Invoking a redux action from one store slice within a different store slice

I am still learning about using redux. One feature I have implemented in my app is the use of async actions with redux thunk. For instance, one of my actions involves loading movies from an API: export const loadMovies = (url) => async (dispatch) => ...

Encountered an error: data.map is not functioning as expected in the React component

Hi there, I've encountered a small issue with my modal component. The error message I'm getting is: Uncaught TypeError: meatState.map is not a function. Any suggestions on what may be causing this problem? Your assistance would be greatly appreci ...

Encountering an issue in next js where attempting to access properties of an undefined variable is resulting in an error with the

"next": "13.0.7" pages version An error occurred in production mode, displaying the following message in the console: TypeError: Cannot read properties of undefined (reading 'push') Additionally, an application error popped ...

Having trouble starting the server? [Trying to launch a basic HTML application using npm install -g serve]

I am in the process of creating a PWA, but I haven't reached that stage yet. Currently, I have only created an index.html file and an empty app.js. To serve my project locally, I installed serve globally using npm install -g serve When I run the co ...

Issue with AngularJS ng-if causing hidden elements to not respond to ng-select event

In my code, there is a hidden select input that is initially hidden using ng-if. Inside this hidden select, I have included a ng-change tag, which triggers a function to display an img element that is also hidden by ng-if. The element hiddenNinja is hidd ...

Implementing mousePressed function for illuminating elements in processing

While exploring animation in processing, I encountered a query regarding the implementation of lights. Typically, my code tends to be lengthy, but this time I have simplified it for beginners to understand as well. void setup() { size(400, 400, P3D); ...

Live calculation feature for dropdown menus

I have a form where I need to calculate the total result after submission. The package and event ID should be added together, and the guest field should always be calculated (guest value * 5). The final result should be displayed in <div id="result"> ...

I am experiencing issues with utilizing Array Filters in my Node.js backend when working with MongoDB

Utilizing it with Node.js in my backend. Encountered the following query: db.conversations.update( { convoId: convoId }, { $set: { "ids.$[elem].read" : true } }, { arrayFilters: [ { "elem.id": userId } ] }, (err, data) => { if(err) { ...

What is the process for uploading a text file into JavaScript?

I'm currently facing an issue with importing a text file from my local computer into JavaScript in order to populate HTML dropdowns based on the content of the file. Despite spending considerable time searching for solutions on stack overflow, I haven ...

Substitute phrases with hyperlinks using JavaScript (or Ruby)

After researching numerous resources on SO, I have managed to come up with a solution that is very close to working. My goal is to replace words/phrases within a <p> tag with links using jQuery after the page has loaded (although I am open to a Ruby ...

Submitting form by double clicking and pressing enter at the same time

When using jQuery Validate to validate forms, I encounter a problem where double-clicking the submit button results in my application making two entries with the same data. This issue also occurs when pressing enter multiple times. Despite researching dif ...

Is the SAX Parser designed to store all data in memory?

I am currently working on a requirement where I need to split a large XML document and process it further. Here is a sample of the XML. It may appear all in one line: <?xml version="1.0"?><company><staff><firstname>yong</firstn ...

The full execution of Jquery show() does not pause until it finishes

Here is the sequence I want to achieve: Show a div element with the CSS class yellow Execute a function for about 5 seconds Remove the yellow class and add the green CSS class "state Ok" However, when running my code, the div container does not appear u ...

Is it possible to access an external JavaScript file in the main.js by importing it?

In this scenario, I have defined an array of countries in an external Javascript file. const countries = [ "Australia", "Brazil", "China", "Denmark", "Egypt", "France", "Germany", "Hungary", "Italy", "Japan", ...

Control other inputs according to the chosen option

Here is the HTML code snippet: <fieldset> <label for="tipoPre">Select prize type:</label> <select id="tipoPre"><option value="Consumer Refund">Consumer Refund</option> <option value="Accumulated Prize Ref ...

Is there a way to establish a continuous session between the frontend (AngularJS) and the backend (Java or C#)?

In the process of building a web application, I am utilizing angularjs in the frontend and considering either Java or C# for the backend, with REST communication being essential. My main query revolves around maintaining session continuity between the fro ...

The pathway of information within an AngularJS modal window

Recently, I developed a small demo to demonstrate how to open a modal window in Angular using a directive as the template. However, I have some doubts about the way I am passing data and functions to the modal. Here is the code snippet from the opening c ...

The image retrieved from Blob Data does not meet the specifications of a valid PNG file for download

After piecing together data and scripts from various sources, I have come so close to getting everything working perfectly. However, I've hit a snag on the final stretch... My current task involves using the dom-to-image library to convert my Contain ...