My registration of my custom Entity Doesn't work - java

Hello I have problem with registrating an Entity which i Made.I use Spring.I have made my Model and Everything but i get an error when i try to registrate an Event in my site.
here is an image of the Error:
and Here is an image of all of my folders
I firstly had problems with connections OneToMany and ManyToOne but i searched here and repaired them.But now i don't have errors in the console. Only in the browser. Here is my code in Event entity
package com.example.app.entity;
import javax.persistence.*;
import java.util.List;
#Entity
#Table (name = "events")
public class Event {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
#Column
#ElementCollection(targetClass=String.class)
private List<String> games;
#ManyToMany(fetch=FetchType.EAGER,cascade = {CascadeType.ALL})
#JoinTable(name = "event_users", joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "event_id"))
private List<User> players;
private double latitude;
private double longitude;
private String description;
private String date;
private User owner;
private String gamesToParse;
private String usersToParse;
public String getGamesToParse() {
return gamesToParse;
}
public void setGamesToParse(String gamesToParse) {
this.gamesToParse = gamesToParse;
}
public String getUsersToParse() {
return usersToParse;
}
public void setUsersToParse(String usersToParse) {
this.usersToParse = usersToParse;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public User getOwner(){
return owner;
}
public void setOwner(User owner){
this.owner = owner;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
public double getLatitude(){
return latitude;
}
public void setLatitude(double latitude){
this.latitude = latitude;
}
public double getLongitude(){
return longitude;
}
public void setLongitude( double longitude){
this.longitude = longitude;
}
public String getName(){
return name;
}
public void setName( String name){
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public List<String> getGames() {
return games;
}
public void setGames(List<String> games) {
this.games = games;
}
public void setGames(String gamesData) {
String[] array = gamesData.split(",");
for (String g:array) {
this.games.add(g);
}
}
public List<User> getPlayers() {
return players;
}
public void setPlayers(List<User> players) {
this.players = players;
}
}
and here is my code in RegistrationEvent Model
package com.example.app.model;
import com.example.app.entity.User;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.List;
public class RegistrationEvent {
#Size(min = 5, max = 100, message = "Event name too short")
private String name;
private List<String> games = new ArrayList<>();
private List<User> players = new ArrayList<>();
private double latitude;
private double longitude;
private String description;
private User owner;
private String date;
private String gamesToParse;
private String usersToParse;
public String getGamesToParse() {
return gamesToParse;
}
public void setGamesToParse(String gamesToParse) {
this.gamesToParse = gamesToParse;
}
public String getUsersToParse() {
return usersToParse;
}
public void setUsersToParse(String usersToParse) {
this.usersToParse = usersToParse;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public List<User> getPlayers() {
return players;
}
public void setPlayers(List<User> players) {
this.players = players;
}
public List<String> getGames() {
return games;
}
public void setGames(String gamesData) {
String[] array = gamesData.split(",");
for (String g:array) {
this.games.add(g);
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
i think the mistake is that when i pass arguments in my html something fails so i will show my html too
<body id="eventspeoplebody">
<ul>
<li>Home</li>
<li><a class="active" href="./Events&People.html">Events & People</a></li>
<li>Trade</li>
<li>Chat</li>
<li>Account</li>
<li>About us</li>
<li style="float:right"><a href="#signing">
<img src="./user.png" width="30" height="30" style="vertical-align: middle"> Sign out</a></li>
</ul>
<br>
<p>
<img class="logo" src="./logo.png" width="400" height="175">
<span class="heading"> &nbsp Choose your game & find a team! </span>
</p>
<br>
<div align="center">
<p class="heading1" >Choose where will be your event on the map or enter the coordinates below</p>
</div>
<br>
<br>
<form method="post" th:object="${event}">
<div class="transbox4">
<p align="center" class ="specialText">
<span class="blue"> INFO </span>
</p>
<div align="center">
<div id="info" class ="specialText">
<span class="blue"> Event name*: </span><br>
<input type="text" class="input2" th:field="*{name}"><br>
<span class="blue"> Games at the event*: </span><br>
<input type="text" class="input2" th:field="*{gamesToParse}"><br>
<span class="blue"> Date*: </span><br>
<input type="text" class="input2" th:field="*{date}"><br>
<span class="blue"> Player emails*: </span><br>
<input type="text" class="input2" th:field="*{players}"><br>
<span class="blue"> latitude*: </span><br>
<input type="text" class="input2" th:field="*{latitude}"><br>
<span class="blue"> longitude*: </span><br>
<input type="text" class="input2" th:field="*{longitude}"><br>
<p class="smallInfo" align="center">fields with * must be filled!</p>
</div>
</div>
</div>
<br>
<p align="center"> <button type="submit" class="create button1"><b>Submit the Event</b></button> </p>
</form>
</body>
</html>
here is my controller too
package com.example.app.Controllers;
import com.example.app.Service.EventService;
import com.example.app.model.RegistrationEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
#Controller
public class EventsController {
#Autowired
private EventService eventService;
#GetMapping("/user/eventsAndPeople/registerEvent")
public String getRegisterPage(Model model, RegistrationEvent registrationEvent){
model.addAttribute("event", registrationEvent);
return "events/registerEvent";
}
#PostMapping("/user/eventsAndPeople/registerEvent")
public String registerEvent(#Valid #ModelAttribute RegistrationEvent registrationEvent){
this.eventService.register(registrationEvent);
return "events/registerEvent";
}
#RequestMapping(value = "/user/eventsAndPeople", method = RequestMethod.GET)
public String getEventsAndPeoplePage(){
return "home/eventsAndPeople";
}
}
I use Xampp for local server and HeidiSQL so i can track my database.
I'm very confused what's wrong. Oh and something i forgot here is my EventService Implementation:
import com.example.app.Repository.EventRepository;
import com.example.app.Repository.UserRepository;
import com.example.app.Service.EventService;
import com.example.app.entity.Event;
import com.example.app.model.RegistrationEvent;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
#Service
public class EventServiceImpl implements EventService {
#Autowired
private UserRepository userRepository;
#Autowired
private EventRepository eventRepository;
#Autowired
private ModelMapper modelMapper;
public EventServiceImpl() {
super();
}
#Override
public void register(RegistrationEvent registrationEvent) {
Authentication auth =
SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
Event event = this.modelMapper.map(registrationEvent, Event.class);
event.setGames(registrationEvent.getGamesToParse());
event.setDescription(registrationEvent.getDescription());
event.setLatitude(registrationEvent.getLatitude());
event.setLongitude(registrationEvent.getLongitude());
event.setName(registrationEvent.getName());
event.setPlayers(registrationEvent.getPlayers());
event.setDate(registrationEvent.getDate());
event.setOwner(this.userRepository.findOneByUsername(name));
this.eventRepository.save(event);
}
}

Try declaring your methods like this:
public String getRegisterPage(RegistrationEvent registrationEvent, BindingResult bindingResult, Model model)
{
model.addAttribute("event", registrationEvent);
return "events/registerEvent";
}
public String registerEvent(#Valid #ModelAttribute RegistrationEvent registrationEvent, BindingResult bindingResult, Model model){
this.eventService.register(registrationEvent);
return "events/registerEvent";
}
EDIT:
You are returning "events/registerEvent" on both methods. Is that correct?

Related

how to add image on the page

I want to add a picture to my table. but it does not appear on the page. I don’t get a single error. how can I specify the address of my image field in the index.html ?
the picture is uploaded to the database:
but not visible on page:
index.html
<body>
<div layout:fragment="content" class="py-5">
<div class="container">
<h2 style="text-align: center">Список ваших объявлений</h2>
<div class="col-md-12">
<table class="table">
<thead class="thead-light">
<tr>
<th>ID</th>
<th>Description</th>
<th>Price</th>
<th>Sold</th>
<th>Body</th>
<th>Brand</th>
<th>Engine</th>
<th>Model</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<th:block th:each="order : ${orders}" th:remove="tag">
<tr>
<td th:text="${order.id}"></td>
<td th:text="${order.description}"></td>
<td th:text="${order.price}"></td>
<td th:text="${order.sold}"></td>
<td th:text="${order.body}"></td>
<td th:text="${order.brand}"></td>
<td th:text="${order.engine}"></td>
<td th:text="${order.model}"></td>
<td>
<a href="#" class="thumbnail">
<img th:src="#{/general/{id}/image(id = ${order.getId()})}" th:width="350" th:height="350"/>
</a>
</td>
</tr>
</th:block>
</tbody>
</table>
<p>
<a th:href="#{/general/showFormForAdd}" class="btn btn-outline-info btn-lg my-3">Новое объявление</a>
</p>
</div>
</div>
</div>
</body>
images located in Orders - byte[] image.
code below
#Entity #Table(name = "orders") public class Orders {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "description")
private String description;
#Column(name = "price")
private int price;
#Column(name = "sold")
private boolean sold;
#Column(name = "body")
private String body;
#Column(name = "brand")
private String brand;
#Column(name = "engine")
private String engine;
#Column(name = "model")
private String model;
#Lob
#Column(name = "image")
private byte[] image;
#Column(name = "str")
private String imageStr;
public Orders() {
}
public Orders(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isSold() {
return sold;
}
public void setSold(boolean sold) {
this.sold = sold;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getEngine() {
return engine;
}
public void setEngine(String engine) {
this.engine = engine;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public String getImageStr() {
return imageStr;
}
public void setImageStr(String imageStr) {
this.imageStr = imageStr;
} }
So you can do something like this
<img src="data:image/png;base64,${order.getImage()}">

How can I use two seperate Forms using spring and thymeleaf?

I am trying to pass in every form different objects and to different entities.
It is actually works, I can see the new added values(rows) in my database, but still I keep getting the same Exception by submitting both forms separately.
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'post' available as request attribute
and
rg.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "/addPost" - line 11, col 24)
my Controller
import com.example.blog.domain.Category;
import com.example.blog.domain.Post;
import com.example.blog.service.CategoryService;
import com.example.blog.service.PostService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
#Controller
#RequestMapping("edit")
public class EditController {
private final PostService postService;
private final CategoryService categoryService;
// At the same time, I can use #Autowired
public EditController(PostService postService , CategoryService categoryService) {
this.categoryService = categoryService;
this.postService = postService;
}
//(1)
#GetMapping("/addPost")
public String showAddPost(Model model) {
model.addAttribute("post", new Post());
model.addAttribute("category" , new Category());
return "/addPost";
}
//Mapping is coming from the view page(addPost.html).
//The name of the action must be equal
#PostMapping(value = "/upload")
public String dataPost(#ModelAttribute Post post, #RequestParam(value = "action", required = true) String action){
if (action.equals("AddPost")){
postService.addPost(post);
}
return "/addPost";
}
//default : show all posts
//and shows all categories
#GetMapping
public String showAllPosts(Model model){
model.addAttribute("posts",postService.getAllPosts());
model.addAttribute("categories" , categoryService.getAllCategories());
return "index";
}
#GetMapping("/deletePost/{id}")
public String deletePostById(#PathVariable("id") Long id){
postService.deletePost(id);
return "redirect:/edit";
}
#GetMapping("/editPost/{id}")
public String editPost(#PathVariable("id") Long id,Model model){
Post post = postService.findOnePost(id);
model.addAttribute("post", post);
return "updatePost";
}
#PostMapping("/updatePostAction/{id}")
public String updateEditedPost(#ModelAttribute Post post, #PathVariable Long id){
post.setId(id);
if (post.getId() == null){
throw new NullPointerException("what the hell: " + post.getId());
}
postService.EditPost(post);
return "redirect:/edit";
}
#PostMapping(value = "/addCategory" )
public String addCategory(#ModelAttribute Category category, #RequestParam(value = "action",required = true) String action) {
if (action.equals("AddCategory")) {
categoryService.addCategory(category);
}
return "/addPost";
}
and my html file:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form th:action="#{/edit/upload}" th:object="${post}" method="post" >
Name:<br>
<input type="text" th:field="*{author}">
<br>
Title:<br>
<input type="text" th:field="*{title}">
<br>
Post:<br>
<textarea name="post" id="" cols="30" rows="10" th:field="*{text}"></textarea>
<br><br>
<input type="submit" name="action" value="AddPost">
</form>
<br>
<form th:action="#{/edit/addCategory}" th:object="${category}" method="post" >
New Category: <br>
<input type="text" th:field="*{name}">
<input type="submit" name="action" value="AddCategory" >
</form>
<p th:text="${post.author}"></p>
<p th:text="${post.text}"></p>
</body>
</html>
How can I solve this Exception?
EDIT:
Post class.
#Entity
#Table(name = "posts")
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Date date;
private String author;
private String title;
private String text;
public Post(String author, String title, String text) {
this.author = author;
this.title = title;
this.text = text;
}
public Post(){
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}

Is the controller ok? Error parsing one template meanwhile the others work fine

I'm working on an exercise that simulates a store but when printing on screen the option to add products doesn't work. Print a whitelabel error:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Mar 30 17:09:05 CET 2019
There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/producto.html]")
I tried to improve the references in the model and changed the name to some parameters but the same error kept coming up.
This is the controller.
#Controller
public class ProductController {
#Autowired
ProductService productService;
#GetMapping (value = "/addProduct")
public String addProduct (Model model) {
model.addAttribute("producto", new Product ());
return "producto";
}
#GetMapping (value = "/deleteProduct")
public String deleteProduct (Model model, #RequestParam Integer idProduct) {
productService.deleteProduct(idProduct);
return "redirect:/list-productos";
}
#GetMapping (value = "/updateProduct")
public String updateProduct (Model model, #RequestParam Integer idProduct) {
Product producto = productService.getProductById(idProduct);
model.addAttribute("producto", producto);
return "producto";
}
#PostMapping (value = "/addProduct")
public String addProduct (Model model, String nombre, String descripcion, String marca, float precio) {
productService.addProduct(nombre, descripcion, marca, precio);
return "redirect:/list-productos";
}
#PostMapping (value = "/updateProduct")
public String updateProduct (Model model, Product producto) {
productService.updateProduct(producto);
return "redirect:/list-productos";
}
}
This is the service.
public interface ProductService {
List<Product> getAll();
Product getProductById(Integer idProduct);
void addProduct(String nombre, String descripcion, String marca, float precio);
void addProduct(Product product);
void updateProduct(Product product);
void deleteProduct(Integer idProduct);
}
This is the implementation.
#Service
public class ProductServiceImpl implements ProductService {
#Autowired
ProductRepository productRepository;
#Override
public List<Product> getAll() {
return productRepository.findAll();
}
#Override
public void addProduct(String nombre, String descripcion, String marca, float precio) {
Product producto = new Product(nombre, descripcion, marca, precio);
productRepository.save(producto);
}
#Override
public void addProduct(Product product) {
productRepository.save(product);
}
#Override
public void updateProduct(Product product) {
productRepository.save(product);
}
#Override
public void deleteProduct(Integer idProduct) {
Optional<Product> producto = productRepository.findById(idProduct);
if (producto.isPresent()) {
productRepository.deleteById(idProduct);
}
}
#Override
public Product getProductById(Integer id) {
return productRepository.getOne(id);
}
}
This is the model
#Entity
#Table (name = "product")
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column (name = "idProduct")
private Integer idProduct;
#Column (name = "nombre")
private String nombre;
#Column (name = "descripcion")
private String descripcion;
#Column (name = "marca")
private String marca;
#Column (name = "precio")
private float precio;
#OneToMany(mappedBy = "producto")
private Set<OrderLine> orderLines;
public Product() {
}
public Product(String nombre, String descripcion, String marca, float precio) {
super();
this.nombre = nombre;
this.descripcion = descripcion;
this.marca = marca;
this.precio = precio;
}
public Integer getIdProduct() {
return idProduct;
}
public void setId(Integer idProduct) {
this.idProduct = idProduct;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public float getPrecio() {
return precio;
}
public void setPrecio(float precio) {
this.precio = precio;
}
}
This is the form in HTML.
<form th:action="#{/addProduct}" th:object="${producto}"
method="post">
<div class="form-group">
<label for="nombre" class="control-label">Nombre</label> <input
id="nombre" class="form-control" th:field="*{nombre}" />
</div>
<div class="form-group">
<label for="descripcion" class="control-label">Descripción</label>
<input id="descripcion" class="form-control"
th:field="*{descripcion}" />
</div>
<div class="form-group">
<label for="marca" class="control-label">Marca</label> <input
id="marca" class="form-control" th:field="*{marca}" />
</div>
<div class="form-group">
<label for="precio" class="control-label">Precio</label> <input
id="precio" class="form-control" th:field="*{precio}" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Añadir
producto</button>
</div>
</form>
Yeah controller is bad in updateProduct. Instead of:
model.addAttribute("producto", producto);
Write:
model.addAttribute("producto1", producto);
Because in thymeleaf you referenced it in th:object as producto1 not as producto.

Passing multiple instances of a bean created under c:forEach in JSF

I have a JSF form, in which we need to select list of products(using checkbox). The products are displayed using the c:forEach iteration. I am storing the detail of each selected product in a spearate bean called BuyProduct.java. I want each of this selected bean/product to be passed to the action attribute of form. Or is there any alternate way to implement this?
<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:ui = "http://java.sun.com/jsf/facelets"
xmlns:c = "http://java.sun.com/jsp/jstl/core">
<h:head>
<h:title>Shop</h:title>
<h:outputStylesheet name="/css/products.css"></h:outputStylesheet>
</h:head>
<h:body>
<h:form id="productForm">
<c:forEach items="#{products}" var="prod">
<div id="productDiv">
<div id="nameFacet" name="nameFacet">
<h:selectBooleanCheckbox value="#{buyProduct.code}">
<f:selectItems itemLabel="#{prod.code}" itemValue="#{prod.name}"></f:selectItems>
</h:selectBooleanCheckbox>
<h:outputText id="prodName" value="#{prod.name}"/>
</div>
<div id="priceFacet" name="priceFacet">
<h:outputText id="prodPrice" value="#{prod.price}">
<f:convertNumber type="currency" currencySymbol="₹"></f:convertNumber>
</h:outputText>
</div>
<div id="qtDiv">
<h:inputText id="prodQuantity" value="#{buyProduct.quantity}"></h:inputText>
</div>
<ui:remove><h:graphicImage id="prodImage" value="#{prod.image}"/></ui:remove>
</div>
</c:forEach>
<div id="submit">
<h:commandButton value="Checkout" action="#{checkout.prodCheckout}"/>
</div>
</h:form>
</h:body>
</html>
package com.test.student.beans;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import com.test.student.utilities.SessionUtils;
import com.test.student.utilities.ShoppingDAOImpl;
#ManagedBean(name="accounts")
#SessionScoped
public class Accounts {
private String username;
private String password;
private String role;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String userLogin() {
Map<String,String> requestMap = buildRequestMap();
//String username = requestMap.get("loginForm:username");
//String password = requestMap.get("loginForm:password");
if((username!=null&&username!="") && (password!=""&&password != null)) {
createSession();
return "Home.xhtml?faces-redirect=true";
}
else {
FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Incorrect Username and Passowrd","Please enter correct username and Password"));
return FacesContext.getCurrentInstance().getViewRoot().getViewId();
}
}
private void createSession() {
HttpSession session = SessionUtils.getSession();
session.setAttribute("username",username);
}
public String logout() {
HttpSession session = SessionUtils.getSession();
session.invalidate();
return "Login";
}
private Map<String, String> buildRequestMap() {
ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String,String> requestMap = new HashMap<String,String>();
Map<String,String> params = extContext.getRequestParameterMap();
Set<Entry<String,String>> entries = params.entrySet();
Iterator<Entry<String,String>> iterator = entries.iterator();
while(iterator.hasNext()) {
Entry<String,String> next = iterator.next();
requestMap.put(next.getKey(), next.getValue());
}
return requestMap;
}
public String showItems() {
List<Products> products = getProducts();
HttpSession session = SessionUtils.getSession();
session.setAttribute("products", products);
return "Shop";
}
private List<Products> getProducts() {
ShoppingDAOImpl shopping = new ShoppingDAOImpl();
return shopping.getProducts();
}
}
package com.test.student.beans;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
#ManagedBean(name="buyProduct")
#RequestScoped
public class BuyProduct {
private String code;
private String name;
private String quantity;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
}

Thymeleaf not able to post collections / lists of objects

I'm creating a web-application with spring MVC, hibernate and thymeleaf.
I have a page where I can manage users, on this page you should be able to place and remove users from groups.
I am doing this with 2 multiple select boxes.
I added a jquery script what handles the movement of users from the one select box to the other one.
But when i submit, my Group.users object list is empty and I do not get any exceptions.
Does anyone has some advice?
Thanks in advance.
Edit
I just discovered that all thymeleaf attributes inside the html tag "option", aren't compiled. Except for the th:each attr.
So it's pretty clear the problem is in my thymeleaf file.
Thymeleaf / edit.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<div th:replace="template :: css"></div>
<title>Edit group</title>
</head>
<body>
<script>
$(document).ready(function() {
$(".clickable").click(function() {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected").addClass("unselected");
$('#userGroupContainer').append(this);
$("option:selected").css("background-color", "red");
} else {
$(this).removeClass("unselected").addClass("selected");
$('#userGroupContainerSelected').append(this);
$("option:selected").css("background-color", "green");
}
});
});
</script>
<div id="bodyWrap">
<div th:replace="template :: logo">Logo</div>
<div th:replace="template :: nav">Nav</div>
<div th:replace="template :: messages">Header</div>
<div id="backGround">
<div id="contentWrap">
<form action="#{edit}"
th:action="#{${#httpServletRequest.servletPath}}"
th:object="${group}" th:method="post">
<h1 th:unless="${group.id}">Add group</h1>
<h1 th:if="${group.id}">Edit group</h1>
<hr />
<div th:replace="template :: messages">Header</div>
<div class="newFile">
<input type="hidden" th:field="*{id}" />
<table class="newFile">
<tr>
<th>Name:</th>
<td><input type="text" size="50" th:field="${group.name}" /></td>
</tr>
<tr>
<th>Description:</th>
<td><textarea th:field="${group.description}"></textarea></td>
</tr>
<tr>
<td> </td>
</tr>
</table>
<br /> users <br />
<select multiple="multiple" id="userGroupContainer">
<option th:each="u : ${userNotInGroup}" th:text="${u.displayName}" class="clickable unselected" th:value="${u}" ></option>
</select>
<!-- It's all about the select box under this comment -->
<select multiple="multiple" id="userGroupContainerSelected" th:field="*{users}">
<option th:each="ug, rowStat : ${group.users}" th:text="${ug.displayName}" th:value="${ug}" class="clickable selected">Selected</option>
</select>
<div class="form-actions">
<button th:unless="${group.id}" type="submit">Add</button>
<button th:if="${group.id}" type="submit">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
example of the 2 multiple select boxes:
$(document).ready(function() {
$(".clickable").click(function() {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected").addClass("unselected");
$('#userGroupContainer').append(this);
$("option:selected").css("background-color", "red");
} else {
$(this).removeClass("unselected").addClass("selected");
$('#userGroupContainerSelected').append(this);
$("option:selected").css("background-color", "green");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<select multiple="multiple" id="userGroupContainer">
<option class="clickable unselected" >Example</option>
</select>
<select multiple="multiple" id="userGroupContainerSelected" th:field="*{users}">
<option class="clickable selected">Selected</option>
</select>
Controller:
#RequestMapping(value = "/management/edit/{groupId}", method = RequestMethod.GET)
public String editGroup(ModelMap model, Principal principal, #PathVariable("groupId") Long groupId) {
Group group = groupService.findGroupById(groupId);
User user = new User();
List<User> userNotInGroup = userService.findUsersNotInGroup(group);
model.addAttribute("userNotInGroup", userNotInGroup);
model.addAttribute("group", group);
return "management/groups/edit";
}
#RequestMapping(value = "/management/edit/{groupId}", method = RequestMethod.POST)
public String editGroup(#Valid Group group, BindingResult result, Model model, #PathVariable("groupId") Long groupId) {
model.addAttribute("group", group);
System.out.println("USERS: " + group.getUsers());
groupService.saveGroup(group);
return "redirect:/management/list";
}
Group Entity / object:
#Entity
#Table(name = "GROUPS")
public class Group extends DomainObject {
private static final long serialVersionUID = ;
#Id
#GeneratedValue(generator = "GROUPS_SEQ", strategy = GenerationType.SEQUENCE)
#SequenceGenerator(name = "GROUPS_SEQ", sequenceName = "GROUPS_SEQ")
private Long id;
#Column(name = "NAME")
private String name;
#Column(name = "DESCRIPTION")
private String description;
#JoinTable(name = "USERS_GROUPS")
#ManyToMany(fetch = FetchType.EAGER)
private Collection<User> users;
#JoinTable(name = "GROUPS_ROLES")
#ManyToMany
private Collection<Role> roles;
public Collection<User> getUsers() {
return users;
}
public void setUsers(Collection<User> users) {
this.users = users;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Collection<Role> getRoles() {
return roles;
}
public void setRoles(Collection<Role> roles) {
this.roles = roles;
}
}
User Entity / Object:
#Entity
#Table(name = "USERS")
public class User extends DomainObject implements UserDetails {
private static final long serialVersionUID = ;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#NotNull
private Long ID;
#Column(name = "DISPLAY_NAME")
#NotNull
private String displayName;
#Column(name = "EMAIL_ADDRESS")
#NotNull
private String emailAddress;
#Column(name = "PASSWORD")
private String password;
#Column(name = "USERNAME")
#NotNull
private String username;
#Column(name = "LAST_LOGIN")
private Date lastLogin;
#Column(name = "MODIFIED_DATE")
private Date modifiedDate;
#Column(name = "MODIFIED_BY")
private String modifiedBy;
#Transient
private Collection<? extends GrantedAuthority> authorities;
private boolean admin;
#Nullable
#JoinTable(name = "USERS_GROUPS")
#ManyToMany
private Collection<Group> groups;
public Date getLastLogin() {
return lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
}
public Collection<Group> getGroups() {
return groups;
}
public void setGroups(Collection<Group> groups) {
this.groups = groups;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
#Override
public String getPassword() {
return password;
}
#Override
public String getUsername() {
return username;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {
this.authorities = authorities;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
public boolean isAdmin() {
return admin;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
#Override
public Long getId() {
return ID;
}
#Override
public void setId(Long id) {
this.ID = id;
}
}

Categories