Spring-form multiple forms with same model atribute name properties - spring

Hello I am trying to to use spring-form.tld + spring MVC but I can't figure out how to solve this problem. Let's say I have two classes:
public class Person {
private String name;
public String getname() {...}
public void setname(String name) {...}
}
public class City {
private String name;
public String getname() {...}
public void setname(String name) {...}
}
In both of them is property with same name - "name".
Now I got a jsp with two forms:
...
<form:form name="person" modelAttribute="person">
<form:label path="name">Person</form:label>
<form:input path="name" />
<input type="submit" value="send"/>
</form:form>
<form:form name="city" modelAttribute="city" method="post">
<form:label path="name">City</form:label>
<form:input path="name" />
<input type="submit" value="send"/>
</form:form>
...
and controller which serves my requests:
...
#RequestMapping(method = { RequestMethod.POST })
public ModelAndView handle(#ModelAttribute City city,
#ModelAttribute Person person) {
ModelAndView mav = new ModelAndView("test.jsp");
mav.addObject("city", city);
mav.addObject("person", person);
return mav;
}
...
Problem is that if I post person form the attribute name is inserted into person object but also into city. This example is nonsense but it illustrates my problem. I would like to somehow "bind" the person form with person object.
Thanks for any advice!

Related

check if Team exists in the database or the input field is empty

It is necessary to check if the input fields for Team are empty, and whether there is such a Team in the repository.
If the field is not empty and there is no such Team, then you can create a new Team. If the field is empty or Team already exists, then give an error
AdminController
#Controller
public class AdminController {
#RequestMapping(value = "/admin/team", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public String addTeam(Model model, #ModelAttribute("teamForm") #Validated TeamForm teamForm,
BindingResult result, final RedirectAttributes redirectAttributes) {
System.out.println("addTeam invoked");
if (result.hasErrors()) {
return "/admin";
}
Team newTeam = new Team();
newTeam.setName(teamForm.getName());
newTeam.setUrl(teamForm.getUrl());
teamRepository.save(newTeam);
return "teamList";
}
#RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminPage(Model model) {
model.addAttribute("teamForm",new TeamForm());
model.addAttribute("eventForm",new EventForm());
model.addAttribute("usersForm",new UsersForm());
return "admin";
}
admin.html
<form th:action="#{/admin/team}"
th:object="${teamForm}" method="POST">
Team name:
<input type="text" th:field="*{name}" />
<p th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Incorrect Name</p>
<br/>
Url :
<input type="text" th:field="*{url}" />
<br/>
<input type="submit" value="Create Team" />
</form>

Thymeleaf form - how to pass a value for model attribute from one controller method to another one

I'm struggling with adding products into product table for a specific user, whiich is logged via log method. The issue is that the attribue userLogin loses his value and is not equal to the user who logged into. So the actual value for attribute userLogin in addProduct method is null, hence there is an exception.
#RequestMapping("/home")
public String home(Model model) {
model.addAttribute("customer", new Customer());
model.addAttribute("userLogin", new Customer());
return "register";
}
#PostMapping("/save")
public String save(#ModelAttribute(value = "customer") #Valid Customer customer, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
throw new NotValidInputException();
}
if (customerService.checkIfCustomerIsInDb(customer)) {
throw new CustomerAlreadyExists();
}
customerService.saveCustomerIntoDb(customer);
return "saved";
}
#ExceptionHandler(NotValidInputException.class)
public String notValidInputExceptionHandler() {
return "databaseError";
}
#ExceptionHandler(CustomerAlreadyExists.class)
public String customerAlreadyInDbHandler() {
return "customerError";
}
#RequestMapping("/log")
public String login(Model model, #ModelAttribute(name = "userLogin") Customer customerFromLoginForm) {
if (Objects.isNull(customerService.getUserByLoggingDetails(customerFromLoginForm))) {
return "userNotFound";
}
model.addAttribute("product", new Product());
return "logged";
}
#PostMapping(value = "/addProduct")
public String addProduct(#ModelAttribute("userLogin") Customer customerFromLoginForm, #ModelAttribute(value = "product") Product product) {
// customer is null
customerFromLoginForm = customerService.findCustomerById(customerFromLoginForm.getId());
product.setCustomer(customerFromLoginForm);
customerFromLoginForm.setProducts(Arrays.asList(product));
productService.addProduct(product);
return "logged";
}
The form in logged. html
<form th:method="post" th:action="#{addProduct}" th:object="${product}">
<input type ="text" th:field="*{name}" placeholder="Name" /><br />
<input type ="text" th:field="*{category}" placeholder="Category" /><br />
<input type="number" th:field="*{price}" placeholder="Price" /><br />
<input style="text-align: center" type="submit" value="Add Product" /> </form>
Not sure what I'm missing here
See this answer: Not able to pass model Attribute passed from controller to thymeleaf html back to another controller .
In general, I would use a hidden input for it, e.g:
<input type ="hidden" th:name="userLogin" th:value="${userLogin}" />
Then your controller method should get it. Let me know if this helps.

Field is always null in Spring Boot Postmapping method

I want to bind my HTML table with all fields to Java code in Spring Boot.
Therefore, I have annotated my method with Postmapping, too.
I was already able to show all the fields in Thymeleaf and I was also able to set the checkBox value ( true / false ) accordingly.
This is my Thymeleaf HTML code:
<form action="#" th:action="#{/mitarbeiterverwaltung}" th:object="${users}" method="post">
<fieldset>
<table border="1" align="center">
<thead>
<tr>
<!-- <th:text = "#{mitarbeiterverwaltung.active}>Active ( Tick ) / Passive</th>-->
<th>Active ( Tick ) / Passive</th>
<th>ID</th>
<th>Username</th>
<th>Anzeigename</th>
<th>Dienstnummer</th>
</tr>
</thead>
<tbody>
<tr th:each="user, itemStat : *{users}">
<td><input th:field="*{users[__${itemStat.index}__].isActive}"
th:checked="${user.isActive}"
class="checkBox"
type="checkBox"
name="checkBox"
/></td>
<td><input th:field="*{users[__${itemStat.index}__].id}"
readonly/></td>
<td><input th:field="*{users[__${itemStat.index}__].username}"
readonly/></td>
<td><input class="anzeigename"
type="text"
name="anzeigename"
th:field="*{users[__${itemStat.index}__].anzeigename}"
th:id="${itemStat.index}"
readonly/></td>
<td><input class="dienstnummer"
type="text"
name="dienstnummer"
th:field="*{users[__${itemStat.index}__].dienstnummer}"
th:id="${itemStat.index}"
readonly/></td>
</tr>
</tbody>
</table>
<br />
<div style="text-align:center;">
<input type="submit" id="submitButton" th:value="Speichern"/>
</div>
</fieldset>
And this is my Java code, where the field isActive of UserCreationDto is always null.
#PostMapping
public String updateActivePassiveUser(#ModelAttribute UserCreationDto userTableSettings,
#RequestParam("checkBox") String checkBoxName, BindingResult result, Model model, Errors errors) {
logger.info("Method {} called in {}", new Object() {}.getClass().getEnclosingMethod().getName(), this.getClass().getName());
if (errors.hasErrors()) {
logger.error("Error in {}", new Object() {}.getClass().getEnclosingMethod().getName());
return "error";
}
List<Benutzer> users = userManagementServiceImpl.getAllUsers();
userManagementServiceImpl.updateActivePassiveUser(1, 0);
return "redirect:/mitarbeiterverwaltung?success";
}
Here is a picture of the field in Java code where the method is annotated with #PostMapping
And so does my #RequestMapping look like:
This is my #RequestMapping method:
#RequestMapping
public String showUserManagement(Model model) {
logger.info("Method {} called in {}", new Object() {}.getClass().getEnclosingMethod().getName(), this.getClass().getName());
List<Benutzer> users = userManagementServiceImpl.getAllUsers();
userForm = userManagementServiceImpl.saveUserForm(users);
model.addAttribute("users", userForm);
return "mitarbeiterverwaltung";
}
My UserCreationDto where all the fields get added to a list:
public class UserCreationDto {
private List<User> users = new ArrayList<>();
public void addUser(User user) {
this.users.add(user);
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
And my simple POJO class with all the fields
#Data
public class User {
//#SafeHtml prevents XSS ( Cross-Site Scripting )
#SafeHtml
private String username;
private String password;
private String anzeigename;
private String dienstnummer;
private long id;
private Boolean isActive;
}
The other fields like anzeigename, dienstnummer, id, and username are filled within my Java code, however, isactive is always null.
Maybe, someone can tell me what I am doing wrong here.
Thank you very much in advance.
I think you have to many options set. You don't need th:checked:
<input th:field="*{users[__${itemStat.index}__].isActive}"
class="checkBox"
type="checkBox"
name="checkBox" />
I found another way now, but it is not really nice.
#PostMapping
public String updateActivePassiveUser(#Valid #ModelAttribute("userForm") UserCreationDto userTableSettings,
#RequestParam List<String> searchValues, BindingResult result, Model model, Errors errors) {
The field searchValues contains all the checkBoxes that are ticked.
This is my view:
<td><input type="checkbox"
name="searchValues"
th:value="${user.id}"
th:checked="${user.isActive}"
/>
Now, the only problem that I am having is how to update my column that is of type Boolean in Postgresql?
For accomplishing this task I call this:
userRepo.updateActivePassiveUser(new Boolean("False"), id);
#Modifying
#Query(value = "UPDATE benutzer SET active = :active WHERE id = :id", nativeQuery = true)
#Transactional
void updateActivePassiveUser(#Param("active") Boolean active, #Param("id") long id);
However, the value in my database never changes.
Maybe, someone could give me a last hint, please!

get selected value in controller - jsp/spring

I am trying to pass value from in jsp to POST controller.
i have the controller get:
#RequestMapping(value = "/matches/{pageNumber}/", method = RequestMethod.GET)
public String games( #PathVariable Integer pageNumber, Model model ) {
....
//build map for dropdown compatitions
HashMap<Integer, String> leaguesMap = new HashMap<Integer, String>();
leaguesMap.put(1, "Top Leagues");
leaguesMap.put(2, "All");
for (Competition competition : competitions) {
if(!leaguesMap.containsKey(competition.getApiId())){
leaguesMap.put(competition.getApiId(), competition.getName());
}
}
model.addAttribute("leaguesMap", leaguesMap);
.....
return "upcomingMatches";
}
And then in jsp:
<form:form modelAttribute="leaguesMap" action="drop" class="dropdown-leagues" method="POST">
<form:select path="${leaguesMap.value}" id="league-selection" onchange="this.form.submit()" class="form-control select-filter select2-hidden-accessible" aria-hidden="true">
<form:options items="${leaguesMap}" />
</form:select>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form:form>
I am trying to get the selected value in POST controller:
#RequestMapping(value = "/matches/{pageNumber}/drop", method = RequestMethod.POST)
public String games( #ModelAttribute("leaguesMap") String leaguesMap, #PathVariable Integer pageNumber, BindingResult result) {
String fff = leaguesMap;
System.out.println("asadasdadsa"+fff);
return "redirect:/matches/{pageNumber}/";
}
But getting always null.
If you can give me direction how to proceed , it will be great.
Thanks!
Create a model class League.class
public class League {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Change your get controller:
#RequestMapping(value = "/matches/{pageNumber}/", method = RequestMethod.GET)
public String games( #PathVariable Integer pageNumber, Model model ) {
....
//build map for dropdown compatitions
HashMap<Integer, String> leaguesMap = new HashMap<Integer, String>();
leaguesMap.put(1, "Top Leagues");
leaguesMap.put(2, "All");
for (Competition competition : competitions) {
if(!leaguesMap.containsKey(competition.getApiId())){
leaguesMap.put(competition.getApiId(), competition.getName());
}
}
model.addAttribute("leaguesMap", leaguesMap);
model.addAttribute("league", new League());
.....
return "upcomingMatches";
}
Change your jsp:
<form:form modelAttribute="league" action="drop" class="dropdown-leagues" method="POST">
<form:select path="id" id="league-selection" onchange="this.form.submit()" class="form-control select-filter select2-hidden-accessible" aria-hidden="true">
<form:options items="${leaguesMap}" />
</form:select>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form:form>
And finally your post controller:
#RequestMapping(value = "/matches/{pageNumber}/drop", method = RequestMethod.POST)
public String games( #ModelAttribute("league") League league, #PathVariable Integer pageNumber, BindingResult result) {
System.out.println("asadasdadsa" + league.getId());
return "redirect:/matches/{pageNumber}/";
}

Spring form binding return null with many-2-one relationship

Here is the problem, when I try to submit form, user entity returns null.
Form is
<form:form class="g-form" modelAttribute="objView" id="userAssignmentForm">
<form:hidden path="id" value="${objView.id}"/>
${objView.user.id}
<div class="g-form-group required">
<label for="user">User</label>
<form:hidden id="user" path="user" value="${objView.user}"/>
<input type="text" value="${objView.user.userName}" readonly="true"/>
<input type="button" class="import-input" onclick="gImport.showImportUserForm()"/>
</div>
Controller is
#RequestMapping(value = "/create", method = RequestMethod.POST)
public #ResponseBody
String create(
#ModelAttribute("objView") UserAssignmentView objView, BindingResult result,
SessionStatus status,
HttpServletRequest request) throws UnsupportedEncodingException {
UserAssignment obj = new UserAssignment();
obj.setUser(objView.getUser());
userAssignmentService.create(obj);
return "ok";
}
Model is below contains a view entity. What am I missing?
public class UserAssignmentView extends UserAssignment {
public UserAssignmentView() {
}
public UserAssignmentView(UserAssignment obj) {
setId(obj.getId());
setStatus(obj.getStatus());
setUser(obj.getUser());
}
}
And this is form view part of controller
#RequestMapping(value = "/form", method = RequestMethod.POST)
public ModelAndView form(HttpServletRequest request) {
UserAssignment obj = new UserAssignment();
Account account = AccountRegistry.getByHttpSession(request.getSession());
ModelAndView modelAndView = new ModelAndView("forms/userAssignmentForm");
modelAndView.addObject("objView", UserAssignmentWrapper.wrap(obj));
return modelAndView;
}
I could not solve since 3 days, how can I set user to userassignment?

Resources