What is the best approach for handling @RequestParam in a JSP file?

Hello there! I have a query regarding the usage of @RequestParam in @RestController. My question is about extracting @RequestParam from the client side. Below is an example of server code using @RestController:

@ResponseBody
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<ProjectBean>> getAllBeans(@RequestParam(name = "head") Integer headId) {
    Integer head = securityService.getLoggedAccountId();
    List<ProjectBean> projects = (List<ProjectBean>) projectService.getByHead(head);
    return new ResponseEntity<List<ProjectBean>>(projects, HttpStatus.OK);
}

And here is the JSP/JavaScript code:

function loadProjects() {
    $.ajax({
        url : 'rest/projects',
        method : 'GET',
        headers : {
            'Content-Type' : 'application/json',
        },
        success: function(data){
            $.each(data, function(index, project) {
                addProject(project);
            });
        }
    });
}

This function fetches all projects, but does not filter them by the exact headId.

Let's take a look at the entity structure:

@Entity
@Table(name = "projects")

public class Project {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "project_name", nullable = false, length = 255)
    private String projectName;

    @Column(name="head")
    private Integer head; //need to get projects with this value

    @Column(name = "description")
    private String description;

    @Column(name = "photo")
    private String photo;

    @Column(name = "status", nullable = false, length = 200)
    private String status;
}

Answer №1

Personally, I believe that following @NayoR's suggestion is the way to go. However, in order to provide a concrete answer to your question, you must incorporate a query string into your JavaScript code. Here is an example:

function loadProjects() {
    $.ajax({
        url : 'rest/projects?head=' + headId,
        method : 'GET',
        headers : {
            'Content-Type' : 'application/json',
        },
        success: function(data){
            $.each(data, function(index, project) {
                addProject(project);
            });
        }
    });
}

Answer №2

To define a route in your application, you can utilize the @RequestMapping annotation:

@RequestMapping(method = RequestMethod.GET, path = "api/projects/{id}")

Alternatively, you can also use the @GetMapping annotation:

@GetMapping(path = "api/projects/{id}")

Remember to access the parameter using @PathVariable("id") instead of @RequestParam(name = "id").

When working with JavaScript, be sure to include the ID in the URL:

function fetchProjects(id) {
    $.ajax({
        url : 'api/projects/' + id,
        method : 'GET',
        headers : {
            'Content-Type' : 'application/json',
        },
        success: function(response){
            $.each(response, function(index, project) {
                displayProject(project);
            });
        }
    });
}

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

What is the best way to handle waiting for a request and user input simultaneously?

Imagine a scenario where a component loads and initiates an asynchronous request. This component also includes a submit button that, when clicked by the user, triggers a function that depends on the result of the initial request. How can I ensure that this ...

Utilizing variable index to access nested objects

When my Ajax request returns a response, the data takes the form of an object shown below: How can I access the value? Keep in mind that idVariable is a variable. data.test1.idVariable.test2.value The result of the code above is: undefined. ...

How shouldjs makes value verification effortless for unordered arrays

In my express.js application, I'm currently using supertest and should.js as my preferred testing framework. However, I've encountered some difficulties when it comes to testing for specific values within an unordered array. After referring to t ...

Using Angular, implementing conditional statements within a for loop

I am currently working on a project where I have an array being looped inside a tag, using the target="_blank" attribute. The issue is that one of the elements in the array should not have this target="_blank" attribute. What would be the best course of ...

Not including the Spring annotation @ResponseBody can result in a 404 error

When I do not include @ResponseBody in my service, it results in a 404 error even though the service is successfully called. In the logs, I see this exception being thrown: .10:00:38.716 [http-nio-8082-exec-10] WARN o.s.web.servlet.PageNotFound - No ma ...

Tips for customizing the color of Menu in material-ui v5

I've been searching for solutions to change the background color of the Menu, but the methods I found are outdated. The use of @mui/styles and makeStyles is now deprecated, as stated in mui.com/styles/basics/#hook-api. I attempted to change the backgr ...

Pause until an email is received in Selenium

I am working on a code snippet to check for emails after a form submission. Sometimes, there is a delay in receiving the email. I have implemented a thread.sleep for 20 seconds before calling the email method, but it seems insufficient. Is there any way ...

Comprehending the significance of *this* within class structures

I've got this code snippet below. class Node { constructor(value, parent, possibleChildren = []) { this.value = value; this.parent = parent; this.children = [] this.setChildren(possibleChildren); } setChildren(possibleChil ...

Create a JavaScript function without attaching it to the global window object

Can someone please help me with defining a function and using it inside Jquery within the $(document).ready block? function addLeadingZero(number) { return (number < 10 ? '0' : '') + number } I'm not confident that I ha ...

Deleting validation messages from my MVC controls

I set up some validation in my Model by adding the following code: [Required] [StringLength(60, MinimumLength = 4)] [Display(Name = "Users code")] public string UserCode { get; set; } When c ...

Guide on removing material-ui from your project and updating to the newest version of MUI

I need to update my React app's material-ui package to the latest version. Can someone provide instructions on how to uninstall the old version and install the new MUI? UPDATED: In my package.json file, the current dependencies are listed as: ...

Could using 'require' in node.js lead to a memory leak issue?

I have been working on a program that experiences continuous heap growth. The program is quite simple - it repeatedly tries to load an external file (SyntaxError) using require. However, this external module fails to load due to a syntax error present in i ...

``The Dynamic Checkbox Selection Process using Ajax, Jquery, and PHP

I'm a bit confused about the next steps... <input id="" type="checkbox" name="" onClick="" /> <td> <h4>PDF Document</h4> <p> Do you have your own menu or flyer? You can add it to your App </p> ...

What are the proper methods for accurately testing vuex state and mutations?

Can someone guide me on how to properly test mutations and state? I have a modal window component that is rendered when the showModal property in the state is true. There is an event triggering a mutation that changes this property. How can I verify that a ...

Tips for loading a webpage directly to the center instead of the top position

Is there a way to make the page open at a specific div halfway down the page instead of starting from the top? Here is an example: <div id="d1"> <div id="d2"> <div id="d3"> <div id="d4"> <div id="d5"> <div id="d6"> Do ...

Grouping an array of arrays of objects

I am trying to group an array of objects based on the value of the first item below: const data = [{"value":"value1","metric":1},{"value":"value1","metric":2},{"value":"value3","metric":0},{"value":"value2","metric":4},{"value":"value3","metric":1},{"va ...

Exploring Recursive Types in TypeScript

I'm looking to define a type that can hold either a string or an object containing a string or another object... To achieve this, I came up with the following type definition: type TranslationObject = { [key: string]: string | TranslationObject }; H ...

Injecting multiple instances of an abstract service in Angular can be achieved using the following techniques

I am fairly new to Angular and currently trying to make sense of the code written by a more experienced developer. Please excuse me if I'm not adhering to the standard communication practices and vocabulary. There is an abstract class called abstract ...

Display a fancy slideshow that transitions to five new images when the last one is reached

Here is a screenshot of my issue: https://i.stack.imgur.com/duhzn.png Incorporating Bootstrap 3 and FancyBox, I am facing an issue with displaying images in rows. When I reach the last image, clicking on the right arrow should result in sliding to anothe ...

Utilizing Material-UI List components within a Card component triggers all onClick events when the main expand function is activated

Need help with Material-UI, Meteor, and React I am trying to nest a drop down list with onTouchTap (or onClick) functions inside of a card component. While everything renders fine initially, I face an issue where all the onTouchTap events in the list tri ...