Developing J2EE servlets with Angular for HTTP POST requests

I've exhausted my search on Google and tried numerous PHP workarounds to no avail. My issue lies in attempting to send POST parameters to a j2ee servlet, as the parameters are not being received at the servlet. Strangely though, I can successfully receive data when sending parameters via URL attachment (GET).

Below is the Angular 4 code snippet:

   import { Component } from '@angular/core';
   import { IonicPage, NavController, NavParams } from 'ionic-angular';
   import { Http, Headers, RequestOptions } from '@http/client';
   import 'rxjs/Rx';
   @IonicPage()
   @Component({
  selector: 'page-login',
  templateUrl: 'login.html',
 })
export class LoginPage {
 userName: string;
password: string;

constructor(public navCtrl: NavController, public navParams: NavParams, 
public http: Http) {
 }

login() {

var headers = new Headers({ 'Content-Type': 'application/json' });

let options = new RequestOptions({ headers: headers });
let devicecode = '1-001-001-009-1';

let postParams = {
  loginid: this.userName,
  password: this.password,
  devicecode: devicecode
}

this.http.post("http://localhost:8092/OCWebService/LoginOSO", postParams
  , options)
  .subscribe(data => {
    console.log(data);
    alert(data);
  }, error => {
    console.log(error);// Error getting the data
  });


    }

   }

And here's the corresponding Servlet Code:

  protected void processRequest(HttpServletRequest request, 
  HttpServletResponse response)
        throws ServletException, IOException {
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
    response.setContentType("text/html;charset=UTF-8");    

        BufferedReader bf = request.getReader();
        String userName = request.getParameter("loginid");
        String password = request.getParameter("password");
        String deviceCode = request.getParameter("devicecode");
      }

Please note that I'm relatively new to working with Ionic 2.

Answer №1

When it comes to retrieving data, keep in mind that request.getParameter() is designed for handling

application/x-www-form-urlencoded
or query string parameters. In the scenario where you are dealing with JSON data instead, adjustments need to be made.

To address this issue, you have the option to either switch to sending data in the application/x-www-form-urlencoded format or manually extract and parse the JSON from the request input stream. This process can be achieved by utilizing a library such as Jackson. Here's an example:

 InputStream in = request.getInputStream();
 MyPojo pojo = new ObjectMapper().readValue(in, MyPojo.class);

The use of ObjectMapper signifies the incorporation of a Jackson class.

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

Error: It is not permitted to have multiple instances of the CORS header 'Access-Control-Allow-Origin', nor is it allowed to have the header missing

Having trouble with CORS headers when making an HTTP request from my Angular 7 app (hosted on http://localhost:4200) to my Spring-Boot app (hosted on https://localhost:8924) using Firefox. The Spring-Boot app has a CORS filter that is applied to the reque ...

Retrieve upcoming route details within canDeactivate guard in the updated Angular2 router

Is there a way to retrieve the upcoming route information within the "canDeactivate" guard of Angular 2's new router? ...

Which is faster in Java: retrieving ResultSet data by string or by int?

When moving through a Resultset using the conventional method while (rs.next()){ ... } Is it faster to retrieve column data (e.g long) by using rs.getLong(String columnLabel) or rs.getLong(int columnIndex) It's assumed that columnLabel is more a ...

Experiencing difficulty in accessing the database information. Encountering a runtime error while trying to retrieve the data. Below is an example snippet from my servlet DBController

HTTP request to retrieve data from the database using servlet: DBController.java java.sql.Statement statement = conn.createStatement(); ResultSet rs=statement.executeQuery("select * from students"); while(rs.next()) ...

Java guide on obtaining CSV files using Firefox Profile

Query - I have configured a Firefox profile, but still receive prompts to choose download location for CSV files. Any suggestions? System.setProperty("webdriver.gecko.driver", "..\\C_Automation\\Files\\geckodriver64_15.0.exe" ...

Learn the steps for implementing i18n-x in Angular 2 to localize constant property values

I am currently working on localizing my Angular2 application using the i18n-x form from here. It has been successful for attributes like so: <p-dialog i18n-header header="User Details"></p-dialog> The result is: <trans-unit id="fe871da89f ...

I'm torn between whether to calculate on the client side for more requests or on the server side for fewer requests. What should I do?

Consider this scenario: I am developing a shopping cart application where I need to store information such as idClient, createdAt, total, and products in each purchase. In addition, I need to apply discounts on the products for each purchase. This is how ...

What are the steps for incorporating the AAD B2C functionality into an Angular2 application with TypeScript?

I recently built a web application using Angular2 and TypeScript, but now one of my clients wants to integrate Azure B2C for customer login instead of OAuth. I followed a simple example on how to implement Azure B2C in a .NET Web app through the link provi ...

Testing Angular Components with setInterval FunctionTrying out unit tests in Angular

I'm struggling to figure out how to write unit tests for setInterval in my .component.ts file. Here is the function I have: startTimer() { this.showResend = false; this.otpError = false; this.time = 60; this.interval = setInterval(() => { this.ti ...

What is the recommended way to include @types/module in a TypeScript project?

Once I've added a module like @types/express using npm, how can I correctly reference it in typescript? I've tried the following methods: /// <reference path="../node_modules/@types/express/index.d.ts" /> but I still get an error sayin ...

The class is experiencing an undefined method error while attempting to extend a Java class using Selenium

I am just starting out with selenium and java and struggling to create a program due to various issues. Below is the code snippet for the Parent Class. Error encountered in the Login Method. Received an error stating "Void is an valid type" along with ...

"Here's a comprehensive guide on how to connect dynamic data with angular-tree-grid components

ERROR TypeError: Cannot read property 'map' of undefined Can anyone help with binding dynamic data? I'm currently using angular-tree-grid but struggling to bind dynamic data. <html> <db-angular-tree-grid (expand)= ...

Dynamic encoding/decoding operations

Utilizing Spring MVC and Jackson, I manage the API for an application. Here's my challenge - we need to serialize the Person class in two different ways: @Entity Order{ String id; String name; String address; List<Items> items; ...

JSON representation of the directory structure

Is there a way to generate a Json representation of a local directory? When I specify a folder, I would like to view all its subfolders and files in a json tree structure. Important: I am not looking for a simple list of file paths. Thank you! ...

Exploring Tailwind's flexibility with custom color schemes

I'm attempting to generate unique hex colors for my React/TypeScript application with Tailwind. Why isn't the background color updating based on the color variable value? Check out my code snippet below: import React, { useState } from &apo ...

"Using Angular's NgFor directive to efficiently organize and collapse data within

I am currently working on displaying API data in a table using ngFor, and I am facing an issue with hiding/showing a specific row of details outside the ngFor loop. Since this line is not within the ngFor loop, I am unable to bind the data accordingly. Can ...

Exploring nested objects within an instance

I'm facing an issue with accessing a variable object within my main object. I am able to access 'start', 'end', and 'category' without any problem, but I am unsure how to access the variable Object in my Angular web app d ...

Struggling to find a solution for directing to the featured homes page without the content overlapping with my navbar and search component. Any assistance would be greatly

Looking for assistance with routing to the featured homes page without the content overlapping my navbar and search component. I simply want it to direct to a new URL without importing the components unless specifically needed. Check out this link I suspe ...

A guide on incorporating a JavaScript plugin using Vue.use() into a TypeScript project equipped with typings

Currently, I am facing an issue while attempting to integrate Semantic-UI-Vue into my Vue project. Upon trying to execute Vue.use(SuiVue), the following error message is displayed: Argument of type 'typeof import("semantic-ui-vue")' is not ass ...

What could be causing the ion-item click to malfunction in Ionic 4 on iOS devices?

ion-item clickable event is not working on iOS but it works fine on Android. I have been searching for a solution and have wasted a lot of time on it. Can someone please help me with this issue? <ion-content> <div> <ion-sear ...