Tips for sending a form using Angular 1.5.8 and Java Servlet via POST method

After reading various tutorials and online documentation, I'm still struggling to figure out how to pass parameters from a JSP form. Below is the JavaScript script I am using:

var app = angular.module('myApp', []);
app.controller('FormController', FormController);

//add dependencies
FormController.$inject = ['$scope', '$http'];

function FormController($scope, $http) {
    $scope.blob = {};
    $scope.submitForm = function() {
        $http({
            method : 'POST',
            url : '/javaAngularJS',
            data : $scope.blob,
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            }
        });
    };
}

This is the form I have created:

<div class="site-body" ng-app="myApp">
    <form ng-controller="FormController" ng-submit="submitForm()">
    <p>Blob Key: <input type='input' name='blob-key' ng-model="blob.key"></p>
    <p>Ancestor: <input type='text' name='ancestor' ng-model="blob.ancestor"></p>
<input type="submit" class="btn btn-primary" value="Submit">
</div>

Although I have successfully used Angular and AJAX calls for other tasks, I am currently stuck on this issue. Does anyone know how I can correctly retrieve the form parameters in my Servlet? For example, I would like to print the parameters using System.out.println.

Answer №1

Utilize the httpParamSerializerJQLike service to effectively serialize your data.

( converting from {key: "asd", ancestor: "asd"} to ancestor=asd&key=asd )

FormController.$inject = ['$scope', '$http', '$httpParamSerializerJQLike'];

function FormController($scope, $http, $httpParamSerializerJQLike) {
  $scope.blob = {};
  $scope.submitForm = function() {
    $http({
       method : 'POST',
       url : 'javaAngularJS', // use relative
       data: $httpParamSerializerJQLike($scope.blob),
       headers: {
         'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
       }
     });
   };
}

This allows you to retrieve parameters like:

String key = request.getParameter("key");
String ancestor = request.getParameter("ancestor");

If you require parsing requests in JSON format, consider using libraries such as Jackson or Gson to convert JSON inputs into Java objects and vice versa.

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

Assign the appropriate label to the HTML checkbox based on the value obtained from the function

I have managed to successfully initiate the HTML service and display the checkbox itself. However, I am facing a challenge in displaying text next to the checkbox as a label. My goal is to have this label text be the return value of a function in the .gs f ...

Maintain Bullet and Arrow Size with JSSOR Scaling Feature

I am currently utilizing the jssor image slider with jquery and overall, it is functioning well. However, I have encountered an issue when attempting to resize the slider. My goal is to dynamically resize the slider whenever the window width changes. The ...

Hierarchy-based dynamic breadcrumbs incorporating different sections of the webpage

Currently in the process of developing a dynamic breadcrumb plugin with either jQuery or Javascript, however I am struggling to implement functionality that allows it to change dynamically as the page is scrolled. The goal is to have a fixed header elemen ...

Handling the ng-if condition based on a model that dynamically gets updated through an asynchronous

In my controller, I have implemented a method to update a model asynchronously using $http. To check whether the model is defined or not, I am using a flag. function myController(ModelService){ var vm = this; vm.myModel = ModelService.data; ...

Incorporate a pause into a JavaScript function

Consider the following function: $(document.body).ready(function() { var o = $(".hidden"); $(".about_us").click(function() { o.hasClass("visible") ? o.removeClass("visible") : o.addClass("visible"); }); }); I am looking to add a delay to this f ...

Failing to catch the return value from a stored procedure in ASP Classic

Apologies for the lengthy post, but I wanted to provide all the necessary details. I am facing an issue with a JavaScript function that uses ajax to call some asp code, which then executes a stored procedure to check if a record already exists. Depending ...

The JQuery CSS function is unable to alter the height of the element

I am working with a grid that contains various elements, each with the class item. When I click on one of these elements, I toggle the class expand to resize the element. <body> <div class="grid"> <a href="#"> < ...

Storing Vue.js components as objects in a database: A step-by-step guide

Is there a way to serialize Vue.js components and store them in a database? For example, I am looking to save components like the HelloWorld component typically found in a fresh Vue installation. Any suggestions on a serialization process or package that ...

Issue with Angular Material Table: Dragged rows do not drop in the correct position when scrolling

I'm encountering issues with using Angular Material Table along with Drag and Drop CDK and scrolling. While dragging a row and then scrolling, the row does not drop where intended. Additionally, the animation does not follow the scroll correctly. I ...

Include a search button within the search box of the Custom Search Engine

Can anyone help me with adding a search button to my HTML code? I've tried implementing it, but when I try to search something on a website like YouTube, the results show up without displaying my search query. How can I fix this issue and what changes ...

Transforming JSON objects, retrieve an empty value in place of undefined

Can someone please offer some advice on the following: I am retrieving JSON data using this code snippet: $.getJSON(jsonPath, function(returnedData){ ... }); The JSON object returned will have a structure similar to this: ... "skin": { "elapsedTextCo ...

The Viadeo Social Toolbox seems to be encountering technical difficulties at the moment

I attempted to utilize a Viadeo Social Toolbox, specifically the Viadeo Share Button, but it seems to be malfunctioning in certain browsers? I came across some outdated viadeo share URLs like this: http://www.viadeo.com/shareit/share/?url=${url}&title ...

Modify the ngb-timepicker formatting to output a string instead of an object

I am currently working on modifying ngb-timepicker so that it returns a string instead of an object. Right now, it is returning the following format: { "hour": 13, "minute": 30 } However, I want it to return in this format: "13:30" This is the HTM ...

Creating a "briefing" iframe at the top of a webpage

I'm looking for a way to allow users to embed my iframe at a specific size, like 100x100, and then have it resize dynamically to fit the page size when they click on it. I want this functionality to work regardless of how the HTML embedding the iframe ...

Tips for presenting HTML source code with appropriate tag coloring, style, and indentation similar to that found in editors

I need to display the source code of an HTML file that is rendered in an iframe. The source code should be shown with proper tag colors and indentations similar to editors like Sublime Text. https://i.stack.imgur.com/IbHr0.png I managed to extract the sour ...

Error: The fetch request was unsuccessful [NextJS API]

I keep encountering an error - TypeError: fetch failed after waiting for 300 seconds while requesting an optimization server that requires a response time longer than 300 seconds. The request is being sent from the provided API in NextJS. Is there a way ...

Having trouble with playing the appended HTML5 Video?

Having trouble getting a video player to display after clicking a button. This is the code I use to add the video player in index.html: $("#videoContainer").append( "<video id=\"video-player\" width=\"100%\" height ...

AngularJS: Modifying values in one div updates data in all other divs

The webpage appears as shown below: https://i.sstatic.net/IxcnK.png HTML <li class="list-group-item" ng-repeat="eachData in lstRepositoryData"> <div class="ember-view"> <div class="github-connection overflow-hidden shadow-oute ...

Exploring the concept of 'JavaScript with Scope' within the MongoDB environment

Within the link provided at https://docs.mongodb.com/manual/reference/bson-types/, it discusses JavaScript with Scope as a potential data type found in documents. I have some inquiries: (1) Could you explain what exactly JavaScript with scope entails? ( ...

Using a dynamic HTML interface, select from a vast array of over 50,000 values by leveraging the power

I am working on a project that includes a multiselect option with over 50,000 records. We are using AJAX to fetch data from the server based on user searches, which works fine. However, when a user tries to select all records by clicking the "check all" ...