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

"Exploring the capabilities of Node WebKit in conjunction with Serial

Currently, I am in the process of building an application using Node WebKit and require access to the SerialPort on my Windows 8 PC. To install third-party modules with C/C++ addons, I followed the instructions outlined in this guide: https://github.com/n ...

AngularJS JSON data computation

As I delve into learning angularjs (not 2), one of the challenges I face is calculating the total amount for a customer order. The data I'm working with is structured as follows: var clients = [ { id: 1, jo ...

Utilizing JavaScript along with ASP.NET web user controls

My web user control generates specific HTML code on the client side. I am trying to reference a particular RadioButton control using JavaScript. The issue is that the RadioButton ID is dynamically generated by ASP.NET, for example, I assign the ID as 1_R ...

Obtaining Compiled HTML Output Using AngularJS

I'm running into an issue with obtaining the compiled html of a page in AngularJS. Below is the code snippet that demonstrates this problem: JavaScript: <script src="http://code.angularjs.org/1.2.0rc1/angular.min.js"></script> &l ...

Would using a Maven Multi-Module project be beneficial for streamlining automated testing with tools like Selenium, Appium, and Karate?

After setting up a Java Maven project for web automated tests using Selenium, the next step is to dive into mobile automated testing with Appium. Instead of starting from scratch with a new project, I am considering converting my Maven project into a Mave ...

Initiate an AJAX request to validate and verify

Is it possible to use Ajax to first check for results, ask for confirmation if any result is found, and then proceed with an action? $(".btn-delete").click(function(){ var url = "index.php?route=catalog/product/delete&user_token={{user_token}}"; var i ...

Refresh the PHP MySQL table view based on selection changes in the dropdown menu

Hello there! I currently have a table displayed on my page thanks to the following code: $result = mysql_query("Select * from porders, porders_detail, parts where porders.order_no = porders_detail.order_no and porders_detail.om_part_no = parts.om_part_no" ...

What could be causing my jQuery AJAX to trigger on all buttons, not just the submit button?

I am new to using AJAX form submission and I have encountered an issue. The submit function is triggered when clicking any button within the form, not just the submit button as intended. I plan to eventually connect the clear button to a form clearing acti ...

Arrange the array based on the order of the enumeration rather than its values

Looking to create an Array of objects with enum properties. export enum MyEnum { FIXTERM1W = 'FIXTERM_1W', FIXTERM2W = 'FIXTERM_2W', FIXTERM1M = 'FIXTERM_1M', FIXTERM2M = 'FIXTERM_2M', FIXTERM3M = 'FIX ...

Creating input fields in Vue 3: Best practices

I am looking to create an input field that automatically removes entered characters if they do not match a specific pattern. Here is the template: <input type="text" :value="val" @input="input" /> And here is the ...

Verify if a checkbox is selected upon loading the page

Hey there, I have a jQuery change function set up to turn an input text box grey and read-only when a user selects a checkbox. However, I'm interested in adding a check on page load to see if the checkbox is already selected. Any suggestions for enhan ...

Ways to manage absent embedded expressions in template literals

I'm curious about the most effective way to handle expressions in a template literal. The following code functions correctly var val1 = "Hello" var val2 = "world" var template = `${val1} ${val2}!` console.log(template) However, suppose for some rea ...

Storing information in a file with jQuery

Currently, I am in the process of creating a website with jquery that allows me to easily edit images. I have implemented some interactive buttons for users to input information (such as "0" or "1") via their browsers. However, my main challenge lies in s ...

Tips for concealing a collapsible navbar menu upon clicking elsewhere (Bootstrap 5)

I am trying to create a collapsible navbar menu: <div class="collapse navbar-collapse" id="navbarCollapsible"> .. menu items .. </div> My goal is to hide the menu whenever a user clicks outside of it (not just when click ...

The user interface design transforms as a PDF file is being generated through html2pdf

I am experiencing an unusual problem while using html2pdf to convert an HTML page to a PDF file and download it. The conversion process is successful and the PDF file is downloaded without any issues. However, when I click on a button to generate the file, ...

Automatically navigate to a specific element as the user scrolls down the page

I am attempting to achieve a similar effect as seen on the App Builder Website. When the user reaches the header with the background image/video and scrolls down, the website smoothly transitions to the next div/section. If the user scrolls back up and ret ...

Notify the user with a message that our support is limited to Chrome, Firefox, and Edge browsers when utilizing Angular

How can I display a message stating that we only support Chrome, Safari, Firefox, and Edge browsers conditionally for users accessing our site from other browsers like Opera using Angular 10? Does anyone have a code snippet to help me achieve this? I atte ...

Navigating a Frame and Clicking a Link with Puppeteer: A Step-by-Step Guide

I am facing an issue with clicking on an anchor link within a page that is supposed to open a new tab for exporting a PDF. The problem arises because this link is located inside a frame within a frameset structure as shown below: https://i.stack.imgur.com ...

React Native encounters issues with removing the reference to the callback attribute upon unmounting

Utilizing a component that I place in an array (of various sizes) and controlling individual components through refs, while adding refs to an object to keep track of each separately. constructor(props){ super(props); this.stamps = []; this.get ...

An issue with ASP.Net 2.0: Invalid postback or callback argument when using the browser back button

My webpage has a simple initialization process where it binds data to a GridView. This GridView has sorting and paging functionalities enabled, and is contained within an UpdatePanel. However, I am encountering an error when the user performs the followin ...