Passing parameters with AngularJS can return as Resteasy @FormParam being null

Struggling to integrate AngularJS on the front end with Resteasy as my Rest API. The issue I'm encountering is that my @FormParam values are always null when sending parameters using AngularJS.

Below is a snippet of my JavaScript code:

$scope.addPerson = function(newFirstName, newLastName) {
            $http({
                method: 'POST',
                url: "rest/persons/savePerson",
                data: {firstName: 'newFirstName', lastName: 'newLastName'},
                headers: {'Content-Type': 'application/json'}
            })
            .success(function(data) {
                alert("DATA  : " + data);
            }).error(function(data, status, headers, config) {
                alert("Could not save new person");
            });
        };

And this is the relevant server-side code:

@POST
@Path("/savePerson")
@Produces("application/json")
@Secured({ "ROLE_USER" })
public PersonBean savePerson(@FormParam("firstName") String firstName,
        @FormParam("lastName") String lastName) {
    if (firstName== null || lastName== null) {
        return null;
    }
    PersonBean person = personDao.savePerson(firstName,
            lastName);
    return person ;
}

Any assistance would be greatly appreciated.

Answer №1

Remember, when posting data from Angular, ensure that the fields are in JSON format and not form encoded.

headers: {'Content-Type': 'application/json'}

It's important to note that changing the header alone won't suffice. The values must be form encoded. Check out this helpful guide on how to properly post form data from Angular:

Alternatively, you can stick with using JSON and let your framework handle mapping the fields to a Bean for you automatically.

If you're using Resteasy, the implementation should be straightforward like so...

@POST
@Path("/savePerson")
@Consumes("application/json")
@Produces("application/json")
@Secured({ "ROLE_USER" })
public PersonBean savePerson(SavePersonBean savePersonBean) {
    PersonBean person = personDao.savePerson(savePersonBean.getFirstName(),
            savePersonBean.getLastName());
    return person;
}

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 is the process of mapping an array of object IDs in order to retrieve the corresponding objects associated with each ID

I currently have a specific collection that stores IDs referencing objects in a separate schema. If I'm working with an array containing these IDs, what is the best way to iterate through and retrieve the corresponding object? Although I've mad ...

Strategies for sending checkbox data to MySQL via AJAX and jQuery

Looking for assistance on passing values of multiple checkboxes to MySQL using arrays with AJAX (jQuery). I've written two separate code snippets, is there someone who can help me merge them? $(document).ready(function(){ var selected = []; $(&apo ...

Trigger a re-render in React using setState(null) and forceUpdate()

When using react 16, setState(null) no longer triggers an update according to the official documentation: The new behavior for calling setState with null is that it does not trigger an update. This gives you the control in the updater function to decide ...

Struggling to set up server-sent events and event sources in JHipster

I am currently working on building an application using JHipster 3.5.0 with spring-boot and angular. I want to implement server-sent events to send updates from the backend to the UI, but I am facing issues getting it to work. Below is the code snippet of ...

Navigate to a particular date with react-big-calendar

I know this might sound like a silly question, but I am new to working with React. Currently, the React-big-calendar allows users to navigate to specific dates when selected from the Month view. What I want is for the same functionality to apply when a use ...

Fade In Effect in Angular 2 Using SwitchCase

Hi everyone, I'm facing an issue with making my switch cases fade in after one is called. Here's what I have so far. When the correct switch case is entered in the input field, I want the current one to fade out and the new one to fade in. How ...

Switch the 360-degree images by clicking a button using Panolen.js

As a beginner in the world of html, css, and javascript, I am trying to create a webpage that displays 360 panorama images. My goal is to have the image change when a button is clicked - for example, clicking on button 1 will display image1, while clicking ...

Conceal a secret input element's value upon clicking a submit button (using PHP and jQuery)

Greetings, I'm facing an issue and need your assistance: Here's the scenario - I have a form that gathers First Name, Last Name, and City from the user. Upon clicking submit, the provided information is then showcased within a table as follows: ...

Tips for restricting users from inputting spaces into a form field using ReactJS

Within my application, I have developed a specialized component named QueryForm that serves the purpose of enabling search capabilities. The code snippet being outputted by this component is as follows: ...

Interact with Dialogflow using fulfillment to retrieve responses by opening an HTTP URL

Despite my efforts, I have yet to find a satisfactory solution. I am in the process of creating an agent on Dialogflow. This agent will be embedded on a webpage, not as part of Facebook Messenger or Google Assistant. The purpose of this agent is to guide ...

Animating Jquery to smoothly change opacity until it reaches 100% visibility

The script I have does several things, but the main issue lies in the last line where the opacity of the class doesn't seem to reach 100%.... $('.fa-briefcase').parent().on('click', function () { $("#colorscreen").remove(); ...

Invoking a C# function inside a cshtml file

Having trouble calling a function in my CSHTML page. In the script of my CSHTML page : <script type="text/javascript" > //var sLoggedInUser = <%# GetSession_LoggedInIdUser() %>; $(document).ready(function () { ale ...

Issue with implementing MUI Style Tag in conjunction with styled-components and Typescript

I have created a custom SelectType component using Styled Components, which looks like this: import Select from '@mui/material/Select'; export const SelectType = styled(Select)` width:100%; border:2px solid #eaeaef; border-radius:8px ...

What is the best way to structure Vue.js components for optimal organization?

Imagine having an index page called index.vue consisting of various components like this: index.vue <template> <div> <component-1 /> <section class="section-1"> <div class="container section-container"> <com ...

How can one transfer information from a client to a server and complete a form using JavaScript?

Can the information be transferred from a client to the server using just JS, then fill out a form on the server, and finally redirect the client to view a pre-filled form? I am considering utilizing AJAX to send a JSON object, but unsure if it will be s ...

The null evaluation consistently yields a negative outcome

import org.json.JSONObject; String jsonData = "{\"someKey\": " + "null" + "}"; JSONObject jsonObject = new JSONObject(jsonData); Object key = jsonObject.get("someKey"); if (null == key) { ...

Code Wizard

I am currently working on a project to develop an HTML editor. How it Needs to Function Elements Inside: Text Area - Used for typing HTML as text Iframe - Displays the typed HTML as real [renders string HTML to UI] Various Buttons Functionality: When ...

Receive dual responses in a single express post

I have a question regarding making multiple requests in one post in Express and receiving multiple responses on the client side (specifically Angular). When I try to make two res.send(body) calls, I encounter an error stating: Error: Can't set headers ...

Activating Dynamic Functionality through JavaScript Input

I am currently working on a form in Apex 4.1 where I have an address lookup field that utilizes JavaScript to connect to an address database and populate separate fields with the address details (address1, address2, town, postcode). On the same page, I ha ...

Differences in Behavior when using $http and Restangular for POST Requests

Currently, I am using a basic ASP.NET Web API 2 service. As someone new to Angular, I decided to transition from utilizing $http to Restangular. Although my GET request seems to be functioning properly, there are issues with my POST request. This is how t ...