Fixing Null Pointer Exception when Posting Form Data using Jersey MultiFormData in JavaScript

I'm currently attempting to send form data using JavaScript to a Jersey Resource. The JavaScript code I have is as follows:

var form = document.getElementById('form');
            var formdata = new FormData(form);

            if (window.XMLHttpRequest)
              {// code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp=new XMLHttpRequest();
              }
            else
              {// code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
              }
            xmlhttp.onreadystatechange=function()
              {
              if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("xmlTextBox").innerHTML=xmlhttp.responseText;
                }
              }
            xmlhttp.open("POST", "PostXml", true);
            xmlhttp.setRequestHeader('Content-Type', 'multipart/form-data');
            xmlhttp.setRequestHeader("Content-length", formdata.length);
            xmlhttp.setRequestHeader("Connection", "close");
            xmlhttp.send(formdata);

The structure of the Jersey Resource is shown below:

@Path("/Resource")
public class MyClass {

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_XML)
public String postXML(@FormDataParam("param1") String param1, 
@FormDataParam("param2") String param2){

return "test";

}

This example showcases a simplified version with only two parameters, while the actual implementation involves more params and additional code. Despite this, the annotations remain unchanged. However, when testing on Tomcat, an exception is thrown:

java.lang.NullPointerException
    at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.unquoteMediaTypeParameters(MultiPartReaderClientSide.java:227)
    at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readMultiPart(MultiPartReaderClientSide.java:154)
    at com.sun.jersey.multipart.impl.MultiPartReaderServerSide.readMultiPart(MultiPartReaderServerSide.java:80)
    at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:144)
    at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:82)
    at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:488)
    at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:552)

By examining the source causing the exception, it appears that the parameter is not being transmitted successfully:

224     for (final String parameterName : parameters) {
225         String parameterValue = mediaType.getParameters().get(parameterName);
226
227         if (parameterValue.startsWith("\"")) {
228             parameterValue = parameterValue.substring(1, parameterValue.length() - 1);
229             unquotedParams.put(parameterName, parameterValue);
230         }
231     }

In my investigation using Firebug, I noticed differences in how names and values are handled between JavaScript and conventional HTML posts. The content type in the HTML request headers is structured within an upload stream:

Request Headers From Upload Stream
Content-Length  1756
Content-Type    multipart/form-data; boundary=---------------------------1523409566516443041527622966

However, the JavaScript method seems to perform a standard post. Is there a way to replicate the multi-form data post behavior using JavaScript?

Despite creating what seems like successful passes, I am encountering issues. When testing with a regular HTML form submission, everything functions correctly. It appears the problem lies specifically with the JavaScript approach.

Answer №1

Get rid of the setRequestHeader

var form = document.getElementById('form');
var formData = new FormData(form);

var xhr=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
    if (xhr.readyState==4 && xhr.status==200) {
        document.getElementById("xmlTextBox").innerHTML=xhr.responseText;
    }
}
xhr.open("POST", "PostXml", true);
xhr.send(formData);

http://jsfiddle.net/8NWB7/ working
http://jsfiddle.net/8NWB7/1/ not working

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

What steps are involved in transitioning from one mesh to another?

I am working with mesh1 and Mesh2, both of which have extrusion properties. mesh1 ->100 vertices mesh2 ->200 vertices In my programming code, I perform the following operations: mesh1.geometry.verticesNeedUpdate = true; mesh1 = Mesh2; mesh1.geomet ...

Utilize the onClick event to access a method from a parent component in React

Looking for guidance on accessing a parent component's method in React using a child component? While props can achieve this, I'm exploring the option of triggering it with an onClick event, which seems to be causing issues. Here's a simple ...

AJAX should prevent page refresh, but sometimes it forces it

This AJAX test page is a simple demonstration using JQuery. When the page is loaded, it displays a button (BUTTON1). Upon clicking on BUTTON1, it will execute react.php using script.js. The react.php will then replace BUTTON1 with BUTTON2 using a span elem ...

What is the best way to clear a datatable before applying filters?

var dataTable = $('#timesheetTable').DataTable({ 'processing': true, 'serverSide': true, 'serverMethod': 'post', 'searching': false, // Set false to ...

What is the technique to make a *ngFor render items in a random order?

I'm working on creating an application that needs to display elements in a random order. However, due to restrictions within the application, I am unable to modify the ngFor directive. How can I achieve displaying ngFor content randomly? ...

What is the best way to handle passing the "img" object to an onload event handler in ReactJS JSX?

I am currently working on an img element that I want to be able to listen for the onLoad event. However, I also need access to the image object itself in order to check properties like width and height. Since these images are generated dynamically, I won&a ...

Ajax is functional, however the server is not responding

After many attempts to resolve the issue with my website, I am turning to this community in hopes of finding a solution. The problem lies in the fact that while the ajax success function appears to be working and shows a status code of 200 in the network ...

Encountering a npm failure during the installation process of polymer

I'm currently attempting to test sensors using HTML and JavaScript, following the example provided here. However, I encountered an issue when trying to install polymer as instructed in the readme file. The error I received is as follows: kupu@kupu:~/ ...

Is there a way to retrieve the `this.$route` data while using vue-apollo?

Currently working on building a GraphQL query with vue-apollo and graphql-tag. When I manually set the ID, everything runs smoothly. However, I'm aiming to dynamically pass the current route's ID as a variable to Vue Apollo. Successful Implemen ...

Unique Angular Circular Progress Bar SVG Interface Customization

The circular progress bar I have created was inspired by the angular-circular-progress repository on GitHub. This is my current progress input: https://i.sstatic.net/nDgfO.png I am looking to customize the end of the progress bar with a small CIRCLE and ...

How can one determine if an array in javascript contains anything other than null values?

I am dealing with an array that typically contains: [null, null, null, null, null] However, there are instances where the array may change to something like: ["helloworld", null, null, null, null] Instead of using a for loop, I am curious if it is po ...

The Chrome equivalent of -moz-user-focus

We have a custom model dialog control that we use for all popups on our web pages. When this dialog is initialized, we use jQuery expose to gray out the rest of the page. To prevent selection on the grayed-out area, we apply the following styles to the mas ...

Accept incoming JSON data

Currently, I am utilizing $routeProvider to establish a route as shown below: when('/grab/:param1/:param2', { controller: 'someController', templateUrl: "templates/someTemplate.html", }). Within the someController, I can acce ...

Receiving the error message "Encountered SyntaxError: Unexpected token )" when using a custom directive

Encountering an issue with the customer directive of auto-complete, as I am receiving the error Uncaught SyntaxError: Unexpected token ). This error is displayed in the console of the chrome browser as VM80623:1 Uncaught SyntaxError: Unexpected token ). Cl ...

Tips for making Slider display the next or previous slide when span is clicked

I have implemented a mix of bootstrap 3 and manual coding for my project. While the image thumbnails function correctly when clicked, the span arrows do not navigate to the next or previous images as intended. Below is the code snippet: var maximages ...

Choosing options from an API response in a REACT-JS application

I have a Select Component in my application and I want it to automatically show the selected data once the response is received. import Select from "react-select"; <Select menuPlacement="auto" menuPosition="fixed" ...

Choosing multiple lists in Angular 2 can be achieved through a simple process

I am looking to create a functionality where, upon clicking on multiple lists, the color changes from grey to pink. Clicking again will revert the color back to grey. How can I achieve this using class binding? Below is the code snippet I have tried with ...

Customizing the main icon in the Windows 10 Action Center through a notification from Microsoft Edge

I am facing an issue with setting the top icon of a notification sent from a website in Microsoft Edge. Let's consider this code as an example: Notification.requestPermission(function (permission) { if (permission == "granted") { new ...

Access local files by utilizing iframe

I attempted to load files via an iframe, however, it was unsuccessful. I am attempting to load a file from: C:/Users/Tom/Desktop/Courses/c2.pdf and I tried: <iframe src="file:///C:/Users/Tom/Desktop/Courses/c2.pdf></iframe> Unfortunately, no ...

JavaScript isn't cooperating with a straightforward .click() command

Having some trouble clicking a div using JavaScript in my project. I am able to utilize jQuery, and have tried selecting the element with QuerySelector as well as XPath, followed by utilizing .click() on the element. However, it seems that the div is not b ...