Receive a notification for failed login attempts using Spring Boot and JavaScript

Seeking assistance with determining the success of a login using a SpringBoot Controller. Encountering an issue where unsuccessful logins result in a page displaying HTML -> false, indicating that JavaScript may not be running properly (e.g., failure: function()...etc). Attempted utilizing async: false without any changes.

The Auth class within the controller package is as follows. Even tried mapping the doLogin method with @ResponseBody, but it only displays a response on a new page encoded in JSON format. If @ResponseBody tag is removed, an error occurs stating that Boolean is unsupported as a response.

@Controller
@CrossOrigin("http://localhost:4200")
public class Auth {
    
    @GetMapping("/login")
    public String login(){
        return "loginPage.html";
    }
    
    @PostMapping("/login")
    public Boolean doLogin(HttpServletRequest httpRequest, HttpServletResponse httpResponse, @RequestParam String nickname, @RequestParam String password){
        System.out.println(nickname);
        System.out.println(password);

        User user = DBManager.getInstance().getUserDao().findByPrimaryKey(nickname);
        if(user != null) {
            httpRequest.getSession().setAttribute("User", user);
            try {
                httpResponse.sendRedirect("http://localhost:4200/");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }

    @GetMapping("/register")
    public String register() {
        return "registerPage.html";
    }

    @PostMapping("/register")
    public void doRegister(@RequestParam String nickname){
        System.out.println(nickname );
    }
}

This is my JavaScript code linked to the Login Button.

window.onload = function(){
  const button = document.getElementById("submitButton");
  const nickname = document.getElementById('nicknameInput');
  const password = document.getElementById('passwordInput');

  button.addEventListener("click", function(event){
    $.ajax({
      method: 'POST',
      url: 'http://localhost:8080/doLogin',
      data: {'nickname': nickname.nodeValue, 'password': password.nodeValue},
      success: function(response){
        alert(response);
      },
    });
    event.preventDefault();
  });
}

Attempting to:

- Upon successful login, redirect to Angular homepage possibly through JavaScript

- In case of failed login, display an alert/label indicating an error

Your advice and input are highly appreciated.

Answer №1

After spending a few hours, I managed to find a solution, although the exact root of the problem still eludes me. My approach involved organizing the Controllers into distinct classes in java - one tagged with @Controller, and the other with @RestController.

@RestController
public class Auth {

    @PostMapping("/doLogin")
    @ResponseBody
    public String doLogin(HttpServletResponse response,@RequestParam String nickname, @RequestParam String password){
        System.out.println(nickname);
        System.out.println(password);

        User user = DBManager.getInstance().getUserDao().findByPrimaryKey(nickname);
        if(user != null){
            if(user.getPassword().equals(password)){
                return "Logged In";
            }else{
                return "Password is incorrect";
            }
        }else{
            return "Can't find user" + nickname;
        }
    }
}

The second class serves solely as a route for directing to the appropriate HTML page.

@Controller
@CrossOrigin("http://localhost:4200")
public class PagesController {

    @GetMapping ("/login")
    public String login(){
        return "loginPage.html";
    }


    @GetMapping ("/register")
    public String register() {
        return "registerPage.html";
    }

}

Below is my JavaScript call using jQuery v3:

<script type="text/javascript">
    $(document).ready(function () {
      let name = document.querySelector("#nicknameInput");
      let pass = document.querySelector("#passwordInput");
        $('#submitButton').click(function () {
          if(name.value !== undefined && pass.value !== undefined) {
            $.post('/doLogin',   // url
                    {nickname: name.value,
                    password: pass.value}, // data to be submit
                    function (data, status, jqXHR) {// success callback
                      $('p').append('status: ' + status + ', data: ' + data);
                    });
          }
        });
    });
  </script>

I hope this explanation proves helpful to someone encountering a similar issue.

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

Identifying the moment when the body scroll reaches the top or bottom of an element

I have been experimenting with javascript and jquery to determine when the window scroll reaches the top of a specific element. Although I have been trying different methods, I have yet to see any successful outcomes: fiddle: https://jsfiddle.net/jzhang17 ...

The Expressjs router prioritizes resolving before retrieving data from Firestore

UPDATE: Upon further investigation, I discovered that by adding "async" to the function signature, the output now displays in the intended order. However, I am still encountering an error regarding setting headers after they have already been sent, even th ...

I'm having trouble getting my object to display using ng-repeat in Angular. Can anyone help me understand what I'm missing?

My goal was to add an object to an array upon clicking an event, which I successfully achieved. However, the objects are not displaying in the ng-repeat as ordered. Can you help me figure out what's missing? angular.module('app', []); an ...

When making xmlhttp requests, IE9 will prioritize loading from the cache rather than from the server when the data is available

During my local development process, I've been utilizing this AJAX code: function getChart(num,ld,margin,idr) { idr = typeof(idr) != 'undefined' ? idr : 0; $(ld).style.display="inline-block"; if (window.XMLHttpRequest) { ...

What are the possibilities of utilizing a variable that is stated within composition to enable dynamic rendering?

I'm working on a Vue.js v3 project using the composition API. I have defined a variable in my setup like this: setup() { const showInvoiceItemForm = true; return { showInvoiceItemForm }; }, Now, I want to show a form when a button is click ...

A 'select all' checkbox in a PHP 'foreach loop' with JavaScript

I am in search of a solution to implement JavaScript in the given code block. My goal is to have the checkbox with id = alles automatically check all the checkboxes that are generated within the while loop. <form id="andere" name="andere" action="<? ...

Navigating through a Single Page Application (SPA) can be achieved without

Can the CSS (Level 4) @document rule handle URLs that have the # symbol or include query parameters? For those who are not familiar with this topic Currently, only Firefox supports this feature with the @-moz-document prefix. If other browsers start supp ...

OutOfBoundsError. Definitely not where we want to be

I'm facing an issue with a method structured like this: var someColletion = _someService.GetSomeCollection(someParam); var taskCollection = new Task<double>[someCollection.Count]; for (int i = 0; i < taskCollection.Length; i++) { // pe ...

Tips for preparing HTML content with Jquery's "ON" method?

My jQuery Accordion is functioning properly, but I'm encountering issues when trying to load the accordion content dynamically from a database or JSON onto the page. The problem arises because the DOM doesn't have information about the newly inje ...

Having trouble with axios not transferring data to Express server in React (File upload)?

Hey there! I've encountered an issue with my React client and Express Server. When attempting to send data from the React client to the Express Server, it's not reaching its destination despite trying two different approaches. First Approach: U ...

Modifying specific attributes of an object within the $scope: A step-by-step guide

When working with Angular, if you have code in the view that looks like this: <span ng-model="foo.bar1"></span> <span ng-model="foo.bar2"></span> <span ng-model="foo.bar3"></span> Due to how Angular maps objects, you c ...

Is my Magento journey on the correct course?

I am wanting to include or require a file in DATA.php within magento. Below is the code snippet I have: public function formatPrice($price) { require_once(Mage::getBaseDir('app').'\design\frontend\neighborhood ...

The D3js visualization is failing to display properly for the user, with the D3 source code residing on the server

I have encountered an issue after transferring my D3js chart generation system from a development server with no problems to a live Windows 2008 r2 server. On the live server, only the background SVG element is displayed and none of the other elements like ...

Trouble confirming the password field with regular expressions in angular.js

I'm trying to validate my password field with specific special characters requirements. The field must contain at least one number, upper case letter, lower case letter, and an underscore, all of which are mandatory. I have attempted to achieve this u ...

display and conceal a division by clicking a hyperlink

How can I make a hidden div become visible when clicking on a specific link without using jQuery? Javascript function show() { var a = document.getElementsByTagName("a"); if (a.id == "link1") { document.getElementByID("content1").style.v ...

Needing to utilize the provide() function individually for every service in RC4

In Beta, my bootstrapping code was running smoothly as shown below: bootstrap(App, [ provide(Http, { useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, helperService: HelperService, authProvider: AuthProvider) => new CustomHt ...

JavaScript Function to Redirect Page After a Delay of X Seconds

I'm trying to implement a redirect to a specific URL after displaying an error message for 5 seconds. Initially, I used JavaScript like this: document.ready(window.setTimeout(location.href = "https://www.google.co.in",5000)); However, the redirectio ...

Having trouble with Npx and npm commands not running in the VSCode terminal?

I am currently facing an issue while attempting to set up a react app in vscode using the command npx create-react-app my-app. It seems like the command is not working properly. Can anyone provide guidance on what steps I should take next? Despite watchin ...

What is the best way to separate a comma-delimited string in JS without including JSON data?

I have a string that looks like this: ABC, CDE, [{"ab":"1","cv":"23"},{"ab":"1","cv":"2%3A1639251967619%2C%22v%22%3A1%7D"}] My goal is to split it into an array of length 3, w ...

A comprehensive guide on harnessing the power of server-sent events in express.js

After incorporating the express.js framework, I configured my REST server. Now, I am interested in integrating server-sent events (sse) into this server. However, upon implementing the sse package from npmjs.com, an error occurs. It seems that the error is ...