Using a boolean checkbox with Spring MVC and implementing ajax

On my HTML page, I have a boolean checkbox that looks like this:

<input type="checkbox" id="pnrCheckbox" name="includesPnr" value="true"/>
<!-- This field is generated by Spring as a workaround for something -->
<input type="hidden" name="_includesPnr" value="on"/>

When I use Ajax to send a JSON string to my controller, the network traffic in my browser displays this form data:

_includesPnr: on

Upon deserializing the JSON back to my Java model in the controller using Jackson, I encounter an issue mapping the _includesPnr property due to the underscore. Even manually mapping the property like this:

@JsonProperty(value="_includesPnr")
private Boolean includesPnr;

fails because 'on' is not a valid boolean value.

How can I ensure that the property is sent with the correct name and values of true/false instead of on/off?

Answer №1

Consider using the @JsonProperty annotation by following this guide: JSON field mapping for Java model

To convert "on" to "true", implement a custom deserializer like so:

In your scenario:

@JsonProperty("_includesPnr")
@JsonDeserialize(using = CustomBooleanDeserializer.class)
private Boolean includesPnr;

Refer to the CustomBooleanDeserializer class below (source: )

public class CustomBooleanDeserializer extends JsonDeserializer<Boolean> {

   @Override
   public Boolean deserialize(JsonParser jsonParser,
        DeserializationContext deserializationContext) throws
    IOException, JsonProcessingException {
       return ("on".equals(jsonParser.getText())) ? true : false;
   }
}

(Please note that the code is untested)

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

Employing specific delimiters with hogan-express while managing the {{{ yield }}} statement

I've hit a roadblock trying to solve this issue. My goal is to incorporate hogan.js (via hogan-express) into a new expressjs application while also utilizing hogan.js on the front-end with Backbone, lodash, and other tools. The layout I am using cons ...

What could be causing my .env file to be undefined and why is it failing to function properly?

I am encountering an issue with the final 10 lines of code when working with a .env file. I have successfully added my .env file with the MESSAGE_STYLE=uppercase. However, upon starting the local server using npm start, the message "hello json" is display ...

The React application is experiencing difficulty in rendering SVG images exclusively on Windows operating systems

My react app runs smoothly on OSX, but encounters issues on Windows due to SVG files: Module parse failed: Unexpected token (2:0) You may need an appropriate loader to handle this file type. <svg xmlns="http://www.w3.org/2000/svg" viewBox="..."> I ...

Ways to transfer a state from the child component to the app component

I have 2 different components that contain sub-components within them. In one of these components, I'm trying to figure out how to transfer the click event from the sub-component to another component so that it can render an entirely new component for ...

Issue with jQuery: Android browser receiving XML instead of JSON from HTTP POST request

When attempting to make an HTTP POST request using jQuery in older Android browsers, I encounter a specific issue. The response received is: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <application xmlns="http://wadl.dev.java.net/20 ...

Logging DOM elements with Electron's webview preload feature

Within my Electron program, I am utilizing a webview in my index.html file. The webview is equipped with a preloader, and my goal is to manipulate the DOM of the webview specifically, not just the index.html file. In my preloader code snippet below, the c ...

Turn off scrolling for the body content without removing the scrollbar visibility

Whenever I click a thumbnail, a div overlay box appears on top: .view-overlay { display:none; position:fixed; top:0; left:0; right:0; bottom:0; overflow-y:scroll; background-color:rgba(0,0,0,0.7); z-index:999; } Some browsers with non-f ...

Add fresh inline designs to a React high-order component creation

Applying a common HOC pattern like this can be quite effective. However, there are instances where you may not want a component to be wrapped, but rather just extended. This is the challenge I am facing here. Wrapper HOC const flexboxContainerStyles = { ...

CSS magic: Text animation letter by letter

I have a <div> with text. <div> to be revealed on the page one character at a time:</p> <div>, the animation should stop and display the full text instantly.</p> In summary, I aim to replicate an effect commonly seen in Jap ...

wordpress widget that triggers a function when a click event occurs on jquery

I'm facing an issue where this function works perfectly in my header, but seems to have no effect when used in a widget $("#myID").click(function(){ var name = $("#name").val(); var phone = $("#phone").val(); console.log(name +" "+ phone) ...

Squashing the `require()` method in nwJS using emberJS

I am facing an issue with my nwjs application that connects to a web address hosting an ember application. I need to access the node context within the ember application to determine the user's operating system for updating purposes. I attempted to do ...

When an exception is caught, the async method in the controller gets called repeatedly

I am currently facing an issue with exceptions not being properly handled in my ajax call. Whenever my asynchronous controller method gets called multiple times, the ajax request is sent only once. However, I do not receive any response as indicated by th ...

Illumination scope for directional lights in three.js

In the world of three.js, calculating shadows for directional lights involves setting a range based on a bounding box that extends from the light source. This means that if I want to limit how far shadows are rendered, I need to adjust the bounding box geo ...

Tips for displaying dynamic content based on conditions in React

I am currently working on adjusting the boilerplate repository in order to render different pages based on whether a user is logged in or not. The current setup always displays the same page but includes additional content if there is an authenticated user ...

Creating a material texture with file api in three.js is a straightforward process

I have a vision to create a cutting-edge model browser that allows users to handpick models and textures themselves. In order to achieve this, I am utilizing the File API for smooth file handling. My approach involves using two separate file inputs for rec ...

Receiving an array via a jQuery AJAX request is not functioning as expected

Here is the code snippet I am working with: var data = $(this).sortable('serialize'); $.ajax({ data: {order: data, actionFor: 'main_articles'}, type: 'POST', url: &a ...

Ways to retrieve the content of a text box within a cell

Here is the code snippet I am currently working with: <tr val='question'> <td> <input style='width: 500px' type='text' placeholder='Q.Enter your question here for radio button? '> </ ...

Incorporating a TypeScript module into a JavaScript module within a React application

I'm encountering an issue with my React app that was created using create-react-app. I recently added a Typescript module to the project, which is necessary for functionality reasons. Although it will remain in Typescript, I made sure to install all t ...

Tips for clearing Nightwatch session storage efficiently

To ensure the pop-up functionality was working properly, I had to reset the browser's session storage. By doing this, the pop-up will reappear. Is there a way to clear the page's Session Storage in Nightwatch? ...

I noticed that when using Next.js with the `revalidate: 1` option on a static page, it is triggering two full F5 refresh actions instead of just one. I was hoping for

Currently, I have set up a blog post edit page in my Next.js project. The post pages are utilizing the Incremental Static Regeneration feature with a revalidation time of 1 second for testing purposes. In the future, I plan to increase this to a revalidat ...