Executing both Java and JavaScript code in the same form using JSP

Currently facing an issue where my form includes inputs for username and password, a captcha (<div>), and a submit button. Upon clicking the submit button, I want it to first check if the captcha is empty. If not, then proceed to call the Java code that authenticates the user.

This is how my jsp form looks:

<html>
  <head>
    <!-- additional scripts / google api js go here -->
    <script type="text/javascript">
      function validate(form) {
        var v = grecaptcha.getResponse();
        if(v.length === 0) {
           document.getElementById('captcha').innerHTML="Login failed: Empty captcha";
           return false;
        } else { 
           return true; 
        }
      }
    </script>
  </head>
  <body>
    <form action="login" method="post" onsubmit="return validate(this);">
       <input type="text" id="email" value="${fn:escapeXml(param.email)}" required>
       <input type="text" id="password" value="${fn:escapeXml(param.password)}" required>
       <div class="g-recaptcha" data-sitekey="xxx"></div>
       <input class="submit_button" type="submit" name="submit" value="Submit" />
       <span class="error"${error.invalid}</span>
       <div id="captcha" class="captchaError"></div>
    </form>
  </body>
</html>

And this is my login servlet responsible for user verification:

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private LoginDAO loginDAO;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        request.getRequestDispatcher("login.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        Map<String, String> error = new HashMap<String,String>();
        request.setAttribute("error",error);

        String email = request.getParameter("email");
        String password = request.getParameter("password");

        // Verify reCaptcha
        String gRecaptchaResponse = request.getParameter("captcha");
        boolean verify = VerifyRecaptcha.verify(gRecaptchaResponse);
        if(!verify) {
            error.put("captcha","You seem to be a robot. Try using the captcha again.");
        }
        if(error.isEmpty()) {
            loginDAO = new LoginDAO();
            try {
                List<Customer> customer = new ArrayList<Customer>();
                customer = loginDAO.validate(email,password);
                if(customer.isEmpty()) {
                    error.put("invalid","Invalid email or password");
                }
                if(error.isEmpty()) { // no errors, proceed
                    HttpSession session = request.getSession(true);
                    Customer user = customer.get(0);
                    session.setAttribute("user",user);
                    response.sendRedirect("main");
                    return;
                }
                request.getRequestDispatcher("login").forward(request,response);
            } catch(SQLException e) {
                throw new ServletException("Could not authenticate login",e);
            }
            loginDAO.closeLoginDAO();
        }
    }
}

The 'loginDAO' just verifies the username and password against a database.

Suddenly encountering issues, even though everything was functioning correctly last night. The only change made was moving the java files into subdirectories. The 'web.xml' file was updated as well to ensure nothing was wrong.

I suspect the 'onsubmit=' part of the 'form' is interfering with the Java class. Any guidance on the correct approach for form validation using JavaScript and Java? Unfortunately, some level of JavaScript is necessary for the reCaptcha to prevent submission with an empty captcha.

Answer №1

When implementing a jsp file, be sure to define

var v = grecaptcha.getResponse();
. Forgetting to define grecaptcha can lead to errors in your script.

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

Unlocking JSON data with identical keys using JavaScriptLearn how to access JSON data with

I need help converting my JSON training data that includes classes and sentences into a different format. [ { class: 'Reservation', sentence: 'make reservation' }, { class: 'Reservation', sentence: 'do reservation&a ...

Is there a way to implement jwt.verify() from jsonwebtoken in a React application?

Every time I attempt to use the jwt.verify() or jwt.decode() function in my React project, it keeps throwing a multitude of errors. The errors that I encounter are: ERROR in ./node_modules/jwa/index.js 5:13-30 Module not found: Error: Can't resolve ...

What is the significance of the error message "Uncaught (in promise) Object"?

I am facing an error in my code and need help to correct and debug it. I would like the code execution to halt when an issue arises. Here is my code snippet: export function postRequestOtpCode(phone: string, token: string): CancellableAxiosPromise { ax ...

Retrieving the input[text] value in TypeScript before trimming any special characters

One of the tasks I am working on involves a form where users can input text that may contain special characters such as \n, \t, and so on. My objective is to replace these special characters and then update the value of the input field accordingl ...

Turn off the feature of map scrolling on OpenStreetMaps

Is there a way to prevent mouse interactions and scrolling in an open maps iframe? I have already tried adding the attribute scrollwheel="false" to no avail. Are there any CSS methods to achieve this? <iframe id= "mapsource" scrollwheel="false" src="ht ...

When used simultaneously, two jQuery functions fail to operate as expected

Currently in the process of coding my portfolio, I encountered an issue with incorporating two JavaScript/jquery codes together. Firstly, for the first section to be a full-page scroll using fullpage.js "plugin," and secondly, changing the navbar to be tra ...

At what point does the cleanup function in UseEffect activate the clearInterval() function?

In the process of creating a timer for a Tenzie game, there is an onClick function that changes the state of isTimerActive from false to true when a user clicks a button. The initial value of tenzie state is also set to false, but once the user completes t ...

The server has denied access to the resource due to a HTTP 403 Forbidden error in the AJAX request

I have exhausted all resources online in an attempt to resolve an error I am encountering with my AJAX request. Even after trying XMLHttpRequest() request, the problem remains unsolved. Below is the code for my Ajax Request: $.ajax({ type: "POST", url: " ...

What would be the best way to set up .replace(/./g, '_') to exclude spaces from being replaced?

After completing my first jQuery project, a simple hangman game featuring one-word book titles in the word bank, I am eager to enhance it to accommodate multi-word book titles. However, I am unable to find the necessary information to modify my code. Curr ...

"Select2 dropdown search bar vanishing act: The hunt for results comes up empty

Currently, I am dealing with a scenario involving two modals, each containing a select2 search dropdown. An issue has arisen where selecting modal one filters the dropdown data effectively. However, upon selecting modal two, although the data is filtered i ...

Issue arises when implementing Ajax with a straightforward conditional statement

After spending hours on a seemingly small and trivial problem, I am feeling frustrated. I have been toiling away, trying different methods, rearranging variables, and experimenting with various approaches to solve it. The issue lies within the generateSpe ...

Using file types in Vue 3: a beginner's guide

In order to use file-type to determine not only the extension but also ensure the headers are correct I would need to use one of the methods listed on their GitHub page. In version 19.0.0 it says fileFromFileType doesn't have such an export and in 16. ...

Use ajax to dynamically update the contents of a textbox

As a newbie programmer, I recently created my own JavaScript update function for my program. However, the code is not updating as expected. Can someone please help me troubleshoot and get it working properly? What I want to achieve is that when I change t ...

Angular 2's Conditional Validation: A Comprehensive Guide

Angular 2 offers straightforward validation, which is a great feature. However, the challenge lies in making a required field optional based on another field's selection. Below are the validation rules: this.contractsFilter = this.fb.group({ selec ...

Encountering an error when trying to use this.setState

I'm currently working on developing a simple react application that consists of a component. In this component, I am attempting to adjust the state when a link is clicked. However, I'm encountering an issue where the setState function is not bein ...

State changes are not being properly reflected in the function within Next.Js

I am currently working on a functional component that displays an array of products. The products are received as props and the component utilizes the useEffect and useState hooks to manage its state. One of the functionalities I am trying to implement is ...

In the realm of JavaScript, the GET request exclusively functions in Internet Explorer

This particular request is specific to Internet Explorer. I've spent the last two days attempting various solutions to make it work, but unfortunately, I have not been successful. Any advice would be greatly appreciated. Pure JavaScript: var xm ...

Arranging a javascript object by organizing an array as a value

Looking to organize a JavaScript Object structured as key:pair, where the pair consists of an array with 2 timestamp values. The goal is to arrange the elements so that those with the smallest numbers (earliest times) are shown first. For instance, consid ...

Failed to load Gulpfile.js in the Task Runner Explorer of Visual Studio 2019 version 16.6.2

Displayed below is the result in the output error window. Failed to execute "D:\TortSVN\Oil Diversity\Main Web App\LatsetOildiversity\Gulpfile.js"... cmd.exe /c gulp --tasks-simple fs.js:27 const { Math, Object } = primordials; ...

How to adjust the timezone settings in PHPMyAdmin on a shared server platform

I'm having trouble changing my timezone to India on my shared server database. I've tried everything but can't seem to get it to work. My website is built using PHP Codeigniter The contact us page on my site saves all inquiry details to my ...