How to Send and Receive GET Requests including Parameters

When faced with the task of retrieving all records from a database based on a specific id, the process involves initiating a request from JavaScript. This request is then captured by a Servlet which accesses a DAO to query the database. Subsequently, the retrieved data will be transmitted back to the front-end. However, I am encountering difficulties with passing these parameters accurately for the correct execution of the database query.

The current issue causing a 500 error stems from the incorrect passing of parameters.

Commencing at the JavaScript stage with the initial request:

let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8080/project1attempt/reimbursement? 
employee_id=' + x._id, true);
xhr.send();

The most challenging aspect lies in receiving the parameters at the Servlet, hence the code snippet provided below remains incomplete (rs denotes Reimbursement Service):

protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {

    resp.setContentType("application/json");
    int id = ;
    List<Reimbursement> reimbursements = rs.findAllReimbursements(id);
    String json = new ObjectMapper().writeValueAsString(reimbursements);
    resp.getWriter().write(json);
}

Here's an example of the query:

public List<Reimbursement> findAllReimbursements(int id) {
    List<Reimbursement> reimbursements = new ArrayList<>();

    try
        (Connection c = manager.getConnection()) {

        String sql = "SELECT reimbursement_id, date, description, amount, 
typing_id, employee_id" +
                "FROM reimbursements" +
                "WHERE reimbursement_id = ?";

        PreparedStatement ps = c.prepareStatement(sql);
        ps.setInt(1, id);
        ResultSet rs = ps.executeQuery();

        Reimbursement r = null;
        while (rs.next()) {
            r = new Reimbursement();
            r.setId(rs.getInt("reimbursement_id"));
            r.setDate(rs.getDate("date"));
            r.setDescription(rs.getString("description"));
            r.setAmount(rs.getDouble("amount"));
            r.setTypingId(rs.getInt("typing_id"));
            r.setEmployeeId(rs.getInt("employee_id"));
            reimbursements.add(r);
        }
        return reimbursements;
    } catch (SQLException e) {
        throw new BlabApplicationDataException("Could not connect to 
Reimbursement Repository" + id);
    }
 }

Answer №1

To retrieve a URL parameter, you can utilize the getParameter method from the HttpServletRequest.

This snippet of code is likely what you need:

String employeeIdStr = request.getParameter('employee_id');
if(employeeIdStr != null) { 
   int employeeId = Integer.parseInt(employeeIdStr);
} 

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

Is it possible to implement a single OrbitControls with two cameras in ThreeJS?

Is there a way to link the OrbitControls of two canvases on the same page? For example, if the user zooms in on one canvas, I want the other canvas to also zoom in simultaneously. How could I achieve this synchronization between multiple canvases? ...

Database failing to insert new data entry

I've been attempting to add a new record to my database but keep encountering issues. Below is the PHP code I'm using for this task: mysql_query("INSERT INTO answers(answer) VALUES('answer')"); if(mysql_affected_rows() ...

Develop an array using a variable's value in JavaScript

I need assistance with creating an array of variable length based on a dynamic value ranging from 1 to 15. The goal is to populate the array differently depending on the specific value of the variable. For instance, if the variable's value is 1, I wo ...

What impact does reselect have on the visual presentation of components?

I'm struggling to grasp how reselect can decrease a component's rendering. Let me illustrate an example without reselect: const getListOfSomething = (state) => ( state.first.list[state.second.activeRecord] ); const mapStateToProps = (state ...

Sorting arrays can yield varying results depending on the browser being used

The variations in output between Chrome 70.0, Chrome 69.0, and Firefox 63.0 for the same code are puzzling. var arr = [1,2,43,1233,5546,33,6,11]; arr.sort(() => -1); //[11, 6, 33, 5546, 1233, 43, 2, 1] arr.sort(() => 1); //[1, 2, 43, 1233, 5546, 33, ...

Tips for resolving CORS error in swagger-ui-express

I'm encountering a "Possible cross-origin (CORS) issue?" error with Spec2 while running this swagger-ui-express application: const express = require('express'); var cors = require('cors'); const app = express(); const swaggerUi = ...

Calculate the total sum of all the figures in a single column

Similar thread: SQL - Summing all values in a column in a table This might seem like a straightforward question, but I've been struggling to find a solution. In my table, there are columns named 'timeId', 'talktime', 'holdti ...

Ways to retrieve class attributes in a child context

When trying to access the class properties (or methods) from another scope, I find myself having to store it in a local variable within the function scope. class MyClass { constructor(API) { this.API = API; this.property = 'value& ...

Utilizing Asynchronous Values in a Different JavaScript Function

Currently delving into the world of destructuring arrays in Javascript, I find myself faced with the challenge of accessing these variables in other functions. I attempted to retrieve the array by calling a function and then using console.log(thermostatAr ...

Flowing seamlessly from one element to the next

I experimented with some jQuery code for a multi-step form, but I'm facing some glitches in the transitions. When I navigate back and forth between steps 1 and 2, everything seems fine. However, when I try to go from step 1 to step 3 and then reverse ...

three.js LambertMeshMaterial

Hello everyone: I've noticed that my models using MeshLambertMaterial are consuming approximately 1.6GB of memory, exceeding the capabilities of a 32-bit Chrome browser. Switching to Basic Material drops the memory consumption to around 456mb, but the ...

What is the best way to continuously swap out images inside a div every second, except when the mouse hovers over

I recently posted a question on Stack Overflow about displaying an image in a div when a specific link is hovered over, and thanks to the help of user adeneo, I was able to find a solution (jsFiddle): HTML Markup: <div id="imgs"> <img src="h ...

Avoid displaying passwords in source code

Currently, I am working on developing a password manager web application similar to LastPass. One issue that has come to my attention is the visibility of variables containing decrypted passwords in the source code after retrieving them from a database u ...

Transforming a collection of Javascript objects into a pure Javascript array

After JSON.stringify-ing my JavaScript object, the output looks like this: [ { "item_id": null, "parent_id": "none", "depth": 0, "left": "1", "right": 4 }, { "item_id": "1", "parent_id": ...

Whenever I execute the code, my if statement seems to interpret the conditions as true regardless of the actual values

let num = (Math.floor(Math.random() * 6 + 1)) console.log(num) if (num === 6) console.log('Wow, you hit the jackpot with a rarity of 1/6!') The above code snippet generates a random number between 1 and 6, then prints "that was a 1/6 chance" if ...

Determine the value in a column by counting the occurrences of another column in a SELECT statement using

Here is a set of data that needs to be analyzed: EVENT_ID MENU_HINT EVENT_NAME SELECTION_ID EVENT_DT WIN_LOSE BSP 144705336 AUS / KemG (AUS) 16th Jun R3 1000m 2yo 19276642 16-Jun-18 0 46.91005891 144705 ...

Tips for calculating the frequency of individual user IDs based on specified conditions in a SQL database

I have a dataset stored in MS SQL that tracks the participation status of individual IDs in a marketing campaign. For each month, there is a column indicating whether each consumer ID is a part of the marketing campaign (is_in_programme), and if so, whethe ...

How can you extract all values from an ArrayObject using the flatMap method in lodash?

Looking at the Array Object provided, I need to filter the data and group it by a specific key. Here is the Array Object: var data = [{ 'value': [{ 'id': '1', ' ...

Tips for managing unfinished transactions through Stripe

I have successfully set up a checkout session with Stripe and included a cancel_url as per the documentation. However, I am facing an issue where the cancel_url is only triggered when the user clicks the back button provided by Stripe. What I want to achie ...

JQuery table sorter is unable to effectively sort tables with date range strings

I am facing an issue with sorting a column in my table that contains text with varying dates. The text format is as follows: Requested Statement 7/1/2014 - 9/16/2014 When using tablesorter, the sorting does not work properly for this column. You can see ...