Retrieve data from multiple inputs with the same name in a Spring MVC form

I have a JSP page with input fields that can be dynamically added or removed. I need to map these input fields to the @ModelAttributes in Spring MVC, but I'm unsure of how to do this.

I want to submit a form that includes:

<form enctype="multipart/form-data">
    <!-- code omitted -->

    <div>
        <input type="text" name="content">
        <input type="file" name="file">
    </div>
    <div>
        <input type="text" name="content">
        <input type="file" name="file">
    </div>
    <div>
        <input type="text" name="content">
        <input type="file" name="file">
    </div>
</form>

These fields should be mapped to the Java class (@ModelAttribute) below:

package com.example.myapp.web.command;

import java.util.Arrays;
import java.util.List;


public class AddRecipeCommand {

    private String mainImageUrl;
    private String foodName;
    private String kcal;
    private String ingredients;
    private String foodDescription;

    // How do I map this field?
    private List<RecipeStep> recipeSteps;

    private String videoUrl;


    public String getMainImageUrl() {
        return mainImageUrl;
    }
    public void setMainImageUrl(String mainImageUrl) {
        this.mainImageUrl = mainImageUrl;
    }
    public String getFoodName() {
        return foodName;
    }
    public void setFoodName(String foodName) {
        this.foodName = foodName;
    }
    public String getKcal() {
        return kcal;
    }
    public void setKcal(String kcal) {
        this.kcal = kcal;
    }
    public String getIngredients() {
        return ingredients;
    }
    public void setIngredients(String ingredients) {
        this.ingredients = ingredients;
    }
    public String getFoodDescription() {
        return foodDescription;
    }
    public void setFoodDescription(String foodDescription) {
        this.foodDescription = foodDescription;
    }
    public List<RecipeStep> getRecipeSteps() {
        return recipeSteps;
    }
    public void setRecipeSteps(List<RecipeStep> recipeSteps) {
        this.recipeSteps = recipeSteps;
    }
    public String getVideoUrl() {
        return videoUrl;
    }
    public void setVideoUrl(String videoUrl) {
        this.videoUrl = videoUrl;
    }
    @Override
    public String toString() {
        return "AddRecipeCommand [mainImageUrl=" + mainImageUrl + ", foodName="
                + foodName + ", kcal=" + kcal + ", ingredients=" + ingredients
                + ", foodDescription=" + foodDescription + ", recipeSteps="
                + recipeSteps + ", videoUrl=" + videoUrl + "]";
    }
}

The command class includes a property called RecipeStep, which is not a primitive type:

package com.example.myapp.web.command;

import org.springframework.web.multipart.MultipartFile;

public class RecipeStep {
    private String content;
    private MultipartFile image;

    public RecipeStep() {}

    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public MultipartFile getImage() {
        return image;
    }
    public void setImage(MultipartFile image) {
        this.image = image;
    }

    @Override
    public String toString() {
        return "RecipeStep [content=" + content + ", image=" + image + "]";
    }


}

My question is, how do I map the input fields from the form to the Java class above? Is it possible by changing the name of the input fields? If so, how can I do that?

Answer №1

public class MultipleUploadForm {
 
    private List<MultipartFile> uploadedFiles;
 
        public List<MultipartFile> getUploadedFiles() {
            return uploadedFiles;
        }
 
        public void setUploadedFiles(List<MultipartFile> uploadedFiles) {
            this.uploadedFiles = uploadedFiles;
        } 
 
}

public @ResponseBody String handleFileUpload(@ModelAttribute("multipleUploadForm") MultipleUploadForm multipleUploadForm){

}

Add the @ModelAttribute annotation in the controller

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

Hiding horizontal lines in a table without affecting vertical lines (Material-ui) - a step-by-step guide

Is there a way to hide the horizontal lines and timeslots in the table below without affecting the vertical lines? I attempted to use the visibility property on the td elements, but it hides both sets of lines. Any suggestions on how to resolve this is ...

What is the best way to retrieve the value of a JavaScript variable and display it within an HTML label tag

In my JavaScript code, I'm attempting to retrieve location coordinates using the onchange event and then display those coordinates in a label. I've tried alerting the coordinates successfully, but I'm struggling to update the label using doc ...

How can I create a reusable function in Java Selenium WebDriver that can be called multiple times?

@Test(priority = 0) public void platformAdminLogin() { // logging in as a platform admin using correct credentials try { driver.findElement(By.id("emailId")).sendKeys("example@example.com"); driver.findElement(By.id("password")).sen ...

Bootstrap Modal closing problem

While working on a bootstrap modal, I encountered an issue where the modal contains two buttons - one for printing the content and another for closing the modal. Here is the code snippet for the modal in my aspx page: <div class="modal fade" id="myMod ...

Utilizing BeautifulSoup to Extract Links

Currently, I am extracting cricket schedules from a specific website using Python's Beatiful Soup library. The webpage I am scraping corresponds to the following URL: www.ecb.c0.uk/stats/fixtures-results?m=1&y=2016 This particular link displays ...

When working with angular.js and angular-sanitize.js, the src attribute is removed from JSON HTML data

I'm new to Angular and I'm really enjoying learning how to work with it. Currently, I have a simple JSON file that contains text structured like this: "gettingstarted":{ "title":"Getting Started", "content":"<img ng-src='i ...

The div element is failing to adjust its height correctly to match its parent container

I'm struggling to make the red border that wraps around the text extend all the way to the bottom of its parent div. Setting the height to 100% isn't achieving the desired effect, as it needs to match the height of the image. Tip: Try resizing y ...

Utilizing Selenium WebDriver to Locate Elements Using Relative XPath Based on Their Text Content

I am currently utilizing Selenium webdriver in conjunction with Java. My main challenge lies in identifying elements within dynamic dropdown lists, as accessing them by exact id/name/xpath is proving to be difficult. I have resorted to locating these elem ...

Spinning a CSS object around an axis

Trying to add a unique touch to my image rotation with CSS. While familiar with rotating around x, y, and z axis, I want to achieve a diagonal rotation this time. Wondering if there's a way to tweak the y axis for a more slanted effect on my image? ...

Plugin for jQuery Validation: Verify if input is NOT an email address

I am currently updating a small Zend e-commerce website and we have been experiencing issues with robot inputs filling in email addresses in every field. To prevent this, I am looking to implement form validation that checks if the field does not contain a ...

Tips for accessing JSON data nested within another JSON object

Above is the JSON data I have: { "RestResponse" : { "messages" : [ "More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm", "Total [249] records found." ], "result" : [ { "name" : "Afghanistan", "alpha2_ ...

Switching views in AngularJS by using a controller to control the content displayed in the

My JavaScript web app utilizes AngularJS to simplify tasks, but I've encountered an issue. I'm trying to change views from an ng-controller using $location.path, but for some reason, the view isn't updating even though the path in the $loca ...

I am experiencing difficulties updating my website

Is there a way to automatically refresh my webpage in PHP whenever I press the enter key? ...

What is causing the fluctuation in the width?

I am struggling to understand this portion of CSS code. When I resize the page, one button sometimes overlaps with the edit box. While debugging in Firebug, I noticed that the width is displayed as 0 for a container. Adding some width brings the button bac ...

How can the seating arrangement be optimized for a seating chart and what is the most effective way to transition away from a traditional table structure?

Currently, I am attempting to create a dynamic seating chart on a webpage within an asp.net-mvc site using data retrieved from a database. Initially, I used a table to organize the grid layout of rows and columns, which resembled this structure: The datab ...

Tips for refreshing the <img> tag using a user image

I am currently designing a bootstrap webpage and trying to implement a feature where the user can input an image, which will then be displayed in a preview modal along with some text provided by the user. The modal is functioning correctly. Here is the co ...

Can you help me identify the reason behind a page displaying a temporary horizontal scrollbar?

While browsing the following page in Google Chrome: A horizontal scrollbar appears briefly during page load. It seems that something hidden below the fold is causing this issue, but I haven't been able to identify the exact cause. EDIT:- Watch a v ...

Creating a unified border style for both <p> and <ul> tags in HTML5

Is there a way to have both paragraphs and unordered lists contained within the same border? I initially thought I could achieve this by placing the list inside the paragraph tag, but that does not seem to work. Below is a snippet of my external style sh ...

Why is it that vanilla HTML/JS (including React) opts for camelCase in its styling conventions, while CSS does not follow the same pattern

Each type of technology for styling has its own set of conventions when it comes to naming properties, with camelCase and hyphenated-style being the two main options. When applying styles directly to an HTML DOM Node using JavaScript, the syntax would be ...

Managing elements within another element in Angular

I am currently exploring the use of Component Based Architecture (CBA) within Angular. Here is the situation I am dealing with: I have implemented three components each with unique selectors. Now, in a 4th component, I am attempting to import these compon ...