Transferring data from a jsp button click to a servlet

Hey there! I'm fairly new to jsp and servlets and I'm trying to figure out how to pass a value to a servlet upon clicking a button. Below is the code snippet that I have been working on. web.xml

<servlet>
<servlet-name>Login</servlet-name>
    <servlet-class>org.wso2.carbon.identity.application.authentication.endpoint.oauth2.OAuth2Login</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

test.jsp

       function ok() {
        $.ajax({
            url: "/login",
            data: 'test=' +'test',
            type: "GET",
            async: false,
            success: function (data) {

            }
        });
    }

Below is the HTML code in test.jsp

<button id="ok" class="btn btn-primary btn-large" onclick="ok()">OK</button>

The servlet

public class OAuth2Login extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
        IOException {
       System.out.print("========do get fires===========");
    }

}

However, even though my test.jsp is loading and invoking the doget() of the servlet, it does not do so upon clicking the button. I only want the servlet to be invoked upon the button click, not during the page load. Can anyone help me solve this issue? Apologies for any ignorance on my part. :)

Answer №1

Instead of using /test.jsp in web.xml, you can replace it with your servlet name like

<servlet-mapping>
    <servlet-name>Login</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

Afterwards, on the button click within test.jsp, you can invoke an ajax function to call the get method of the servlet

function ok() {
        $.ajax({
            url: "/login",
            data: 'test=' +'test',
            type: "GET",
            async: false,
            success: function (data) {

            }
        });
    }

Answer №2

Please provide the URL for your servlet mapping in the designated attribute:

function fetchUserData() {
         var path = "<%=request.getContextPath()%>";

        $.ajax({
            url: path+"/profile";
            data: {"username":"johndoe", "email": "johndoe@gmail.com"}
            type: "POST",
            async: true,
            success: function (response) {

            }
        });
}

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

Troubles arise when compiling TypeScript to JavaScript

I have been experimenting with TypeScript, specifically for working with classes. However, I am facing an issue after compiling my TS file into JS. Below is the TypeScript code for my class (PartenaireTSModel.ts): export namespace Partenaires { export ...

Is there a way to verify if a zip file has been modified?

I am facing an issue with a .sh script that cyclically saves files to a zip file. The problem arises when another Java program attempts to read these files while the .sh script is in the process of writing files to the zip. Is there a way in Java to determ ...

Displaying the product quantity counter in the shopping cart immediately after adding the item

My website has a shopping cart quantity counter that doesn't update immediately when a product is added. Instead, it requires a page reload or navigation to another page for the change to be reflected. I would like the quantity counter to show the pro ...

How can I insert a JsonArray into a JsonObject using Gson?

Imagine I am working on creating a unique Json structure: { "rows": [ { "date_str": "2016-07-01", "sleep_7_or_more_hours": true, "activity_minutes": "0", "water_5_or_more_cups": true, "fruit_veg_4_or_more_servings": tru ...

What is the reason for function expressions being hoisted when called within Express JS middleware?

It's common knowledge that function declarations are hoisted, allowing them to be called from anywhere in your script. However, this is not the case for function expressions. For instance: test(); const test = () => { console.log(1+3); } ...

A class adorned with Lombok annotations that is unchangeable and utilizes

What is the best approach for creating a class that is: Immutable Can be serialized/deserialized using Jackson Human-readable with minimal boilerplate code I had hoped to use something like the following: @Data(onConstructor = @__(@JsonCreator)) and t ...

What could be the reason for my inability to reach function attributes?

Struggling with accessing properties in a function that involves callback functions. const example = ( callback: (...args: unknown[]) => unknown ): void => ({ name: callback.name // <- errors // ... }) Encountering issues in typescript d ...

What is the best way to sequentially read various sections of a file in vue.js?

I am currently working on a browser tool that analyzes a large file and provides statistics based on its content. The tool randomly selects k parts of the file for processing, treating each part individually. As each part is processed, an object is update ...

Can you create a dropdown menu using information from one JSON file and have the selected option come from another source?

Recently, I came across this JavaScript code that is supposed to create a dropdown list of statuses: $.getJSON('/statuses', { ajax: 'true' }, function (data) { var html; var len = data.length; html + ...

JPlayer experiencing technical difficulties on Internet Explorer and Opera browsers

Hey there! I'm facing an issue with my website . I've uploaded some ogg and m4a files for streaming, and while it works perfectly on Firefox, Safari, and Chrome, it's not functioning properly on IE. When I try to play a song, it seems to loa ...

Utilize typeahead bootstrap to automatically activate when an item is selected or highlighted from the dropdown menu, retrieving the selected value

When utilizing typeahead bootstrap, my goal is to trigger an action when an item is selected or focused from the menu, allowing me to assign a specific value connected to the selected item. To fully grasp my intention, please refer to the comments within ...

Transmitting an array within the POST request payload

My goal is to send an array to my Node/MongoDB server using an AJAX POST request, along with other variables in the body. Check out the client side JS code below: function setupForm(){ $("#add").submit(function(event) { event.preventDefault() ...

"Upgrade your website visuals by dynamically changing image sources using jQuery and adding a touch of flair with smooth loading

I am currently working on a page where I have an image that changes its source using JavaScript. However, I would like to enhance this by adding a beautiful sliding effect when the image changes. My goal is to create a seamless transition so that when a ...

Display an "add to cart" button and a discount image when hovering over

Currently, I am in the process of developing an Online Shopping website using PHP. To enhance the design of my website, I have implemented bootstrap. One specific query I have is how to display an 'add to cart' button and a discount image when a ...

Verify that all images have been loaded via AJAX before displaying them on the page

After thinking my project was complete, I encountered a problem when pushing the code live. While it worked perfectly on my local server, the images now take half a second to load properly causing a page thumbnail to pop up over a loading image. https://i ...

Guide on using jQuery Ajax to send form data to another cs file in ASP.Net

How can I create a form to submit data to another CS file in order to update the database. Below is the form and corresponding code. <form id="form1" runat="server" action="./update.aspx" class="col-md-10"> <asp:Table ID="GridView1" class= ...

Learn how to insert a <TableRow> in a for loop using Object.keys

<TableBody> {(() => { var result = []; let key = Object.keys(genericResultList)[1]; var list = genericResultList[key]; for (var i = 0; i < list.length; i++) { ***\<!-- Add in the \<T ...

Utilize AngularJS to load pages through a single state

Is there a way to develop a method that can dynamically load the controller and template for each page as needed, upon changing routes? I am looking to enhance the state url option by including 2 parameters, with the second one being optional. This would a ...

Guidelines for setting the Id and value for a Hidden field

I am working with a gridview that has a few rows and columns, each containing ListBox Controls. Markup: <asp:GridView ID="gvDataEntry" runat="server" AutoGenerateColumns="False" <Columns> <ItemTemplate> <asp:ListBox ID="lst ...

What advantages does JWT have over Firebase that make it the preferred choice?

In our authentication systems, we have the option to verify a user through Firebase or by their stored email in the database. Despite having these methods of verification, why do we incorporate JWT (json web token) into our processes? What distinct advan ...