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

Transform PDF files into PNG format directly in your web browser

I am currently utilizing Vue.js and attempting to convert a PDF file to PNG or another image format directly within the browser. My current setup involves reading the PDF from a URL using PDF.js along with the Vue.js component pdfvuer. let instance = this ...

Use jQuery to easily update the background of an iFrame

I have implemented this code to store the background image selected from a dropdown menu labeled rds. This function also sets a cookie so that the chosen background persists even after the page is reloaded. The issue lies in the line containing $('da ...

Modifying the appearance and behavior of an element dynamically as the page is being loaded using AngularJS

Struggling with a challenge for two days now, I have attempted to implement a panel-box using bootstrap and AngularJS. Within the confines of a controller, my code looks like this: <div id="menu2a"> <div class="panel list-group"> <div ...

Sequelize.Model not being recognized for imported model

I am encountering an issue while trying to implement a sequelize N:M relation through another table. The error message I keep receiving is as follows: throw new Error(${this.name}.belongsToMany called with something that's not a subclass of Sequelize ...

Checkbox not appearing in datagrid when using Material-UI

There are some key code snippets related to the datagrid below const apiRef = React.useRef(null); const [gotApiRef, setGotApiRef] = useState(false); const [gotApiRef2, setGotApiRef2] = useState(false); console.log("apiRef.current: ", apiR ...

Struggling to get a shader up and running on three.js using shaderfrom

Trying to add this shader to my project: This is the fragment shader code: <script id="fragmentShader" type="x-shader/x-fragment"> #ifdef GL_ES precision highp float; precision highp int; #endif uniform vec2 u_resolutio ...

Can const variables be reassigned in JavaScript programming?

Can you reassign a const variable in JavaScript? In C++, we can cast variables to and from const. Is there something similar in JavaScript? My question is const a = 1; unconst(a); a = "xyz"; a === "xyz" // true I'm not referring to object prope ...

Numerous data retrieval commands within the componentWillMount lifecycle method

Initially, I utilized the componentWillMount() method to populate the articles property successfully by iterating over the values to display various images/text. However, I am now encountering an issue as I also need to use componentWillMount to populate ...

Having issues with an Angular reactive form that includes a custom form-level validator and the 'blur' updateOn option?

Having issues combining the following: angular reactive form custom validator at form level (cross-field validator) usage of the 'updateOn' option set to 'blur' A demonstration of the problem can be found in this simple stackblitz: h ...

Showing exclusively JavaScript data in a select element

I am struggling with getting a select tag to display only JavaScript values. Here is the code snippet: <select id="pname"> <option>som data</option> </select> After running a JavaScript function, I want to update the select ta ...

I'm looking for a way to set up a PropType that accepts a boolean value, but also allows for

Currently, my code includes a Modal component with a prop called disableEscapeKeyDown. The PropType defines it as boolean | null, but when trying to use it in the ModalWindow function, I receive an error stating Type 'boolean | null' is not assig ...

Error in NodeJs: ReferenceError - the variable I created is not defined

Encountering an issue while attempting to use a module in my router file. I have successfully required it, but now I am seeing the following error message: ReferenceError: USERS is not defined at c:\work\nodejs\router\main.js:32 ...

Having trouble connecting to a PHP file on a web server using AJAX?

So, I'm attempting to access a PHP file on a webserver (1freehosting.com) from my localhost machine (wamp) using AJAX code embedded in an HTML file. I've tried various iterations without success as shown below: xmlhttp.open("GET","bcbustransit.u ...

Retrieve information from subcategories in the Realtime Database using Firebase

Trying to access message inputs from ALL users has been a challenge. While it can be done for a specific user, the goal is to do so for all users by specifying in the code. Each UID is unique, adding complexity to the process. The Realtime Database struct ...

I am facing an issue where Bootstrap button classes are duplicating when I inspect the code. How can I resolve this

Can anyone help me with an issue I am facing with a Bootstrap button? Despite using only the btn btn-default classes, when inspecting it in Chrome, multiple classes are being displayed on the button. I'm unable to figure out why this is happening and ...

Continuously iterate through collection as it expands over time

As I cycle through an array, I'm performing additional actions that could potentially prolong the loop if new elements are added to the array during iteration. (I understand it's not recommended to modify the object being iterated over, but pleas ...

Discovering the way to retrieve background height following a window resize using jQuery

Is there a way to obtain the background height once the window has been resized? div { background-image: url(/images/somebackground.jpg); background-size: 100% 90%; background-repeat: no-repeat; width: 70%; background-size: contain; ...

When jQuery's `foo.html("<span>bar</span>")` doesn't alter `foo[0]`, what implications does it have?

While using jQuery in Firebug, the following actions are taken one by one: foo = $('<div>foo</div>') foo[0] // => <div> foo.html('<span>bar</span>') foo.html() // => "<span>bar</span> ...

How to center items within a Toolbar using React's material-ui

I need help with implementing a toolbar on a page that contains three ToolbarGroup components: <Toolbar> <ToolbarGroup firstChild={true} float="left"> {prevButton} </ToolbarGro ...

Utilizing Google App Engine for seamless deployment, integrating Ajax for dynamic interactions, and

Using the google App Engine, I am looking to implement javascript (or Ajax) for POSTing a form and updating the target div. The form includes multiple fields and files for transfer. The javascript function I am using is extracted from the "Javascript: The ...