Tuesday, December 10, 2013

How add multiple objects into the database using single form in spring mvc


Form to add multiple rows:


<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
       <form:form action="save" modelAttribute="categorylist">
                    
              <input name="categories[0].id" value="101">
              <input name="categories[0].name" value="Laptop Music">
              <input name="categories[0].description" value="Dell XPS Steerios">
                     <br>
              <input name="categories[1].id" value="102">
              <input name="categories[1].name" value="Laptop">
              <input name="categories[1].description" value="Dell XPS Laptop">
                     <br>
              <input name="categories[2].id" value="103">
              <input name="categories[2].name" value="Laptop cum Mobile">
              <input name="categories[2].description" value="Dell XPS Laptop Mobile">
                     <br>
                     <input type="submit" value="Save" />
       </form:form>
</body>
</html>

Controller Code:

@RequestMapping("/save")
public String storeCategory(@ModelAttribute CategoryList categorylist){
                           System.out.println(categorylist);
                           System.out.println(categorylist.getCategories().size());
                           for(Category c:categorylist.getCategories())
                                  System.out.println(c);
                           return "your jsp";
}

Category:

public class Category {
    
           private int id;
           private String name;
           private String description;
                               
//getters and setters
}



public class CategoryList {
           private List<Category> categories=new ArrayList<>();

           public List<Category> getCategories() {
                return categories;
           }

           public void setCategories(List<Category> categories) {
                this.categories = categories;
           }

}

Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"...