How to clear the error message when we click reset button in thymeleaf - spring-boot

I created a web page displays users information and register a new user. If we try to enter existing user it is showing the error message. when I refresh the page the error is still exist. How to clear the error message when we refresh or when we click reset button.I am using spring Boot Here is my code.
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User Registration </title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
th:href="#{/webjars/bootstrap/3.3.6/css/bootstrap.min.css}"
rel="stylesheet" media="screen" />
</head>
<body>
<div class="container">
<div class="page-header" id="banner">
<div class="row">
<div class="col-lg-8 col-md-7 col-sm-6">
<h1>Users</h1>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>UserId</th>
<th>USerName</th>
</tr>
</thead>
<tbody border="0">
<tr th:each="user :${users>
<td th:text="${user.userId}"></td>
<td th:text="${user.userName}" > </td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-md-7 col-sm-6">
<h1>Register USer</h1>
<form th:action="#{/registerUser}" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="col-lg-3 control-label">Enter UserId</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="userId" value=""/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Enter UserName</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="userName" value=""/>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 col-lg-offset-3">
<button type="submit" class="btn btn-primary" name="button">registerUSer</button>
<button type="reset" class="btn">Reset</button>
</div>
</div>
<div th:if="*{errorMessage != null}" class="alert alert-danger" th:text="*{errorMessage}">
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Here is my controller:
#RequestMapping(value = "/registerUser", method = RequestMethod.POST)
public String registrationForNewUSer(#RequestParam Long userId, #RequestParam String userName, Model model)
throws Exception {
//checking whether user already exist
UserModel userInfo = userInfo.findOne(userId);
if (userInfo != null) {
String str = "user already exist" + userId;
model.addAttribute("errorMessage", str);
return usersList(model);
} else {
//
return "redirect:/registerUser/" + userId + "/" + userName;
}
}
#RequestMapping(value = "/usersList", method = RequestMethod.GET)
public String usersList(Model model) {
model.addAttribute("users", userInfo.findAll());
return "usersview";
}
#RequestMapping("/registerUser/{userId}/{userName}")
public ResponseEntity<Object> authentication{
// it does authenticationprocess and add user user in database and redirect to usersview.
}

Related

How to load data into modal window?

How to edit a database entry in a modal window? I am doing the following but getting an error. Please help me to edit in modal window.
Controller
#Controller
#RequestMapping("/classifier")
public class ClassifierController {
private final LuServices luServices;
private final ModelMapper modelMapper;
#Autowired
public ClassifierController(LuServices luServices, ModelMapper modelMapper) {
this.luServices = luServices;
this.modelMapper = modelMapper;
}
#GetMapping()
public String showClassifierPage(Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
PersonDetails personDetails = (PersonDetails) authentication.getPrincipal();
model.addAttribute("personDetails", personDetails);
model.addAttribute("luDTO", luServices.findByTagWith0());
model.addAttribute("newLuDTO", new LuDTO());
return "lu/index";
}
#PostMapping()
public String createLuWith0(#ModelAttribute("newLuDTO") #Valid LuDTO luDTO, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
StringBuilder errorMessage = new StringBuilder();
List<FieldError> errors = bindingResult.getFieldErrors();
for (FieldError error : errors) {
errorMessage.append(error.getField()).append(error.getDefaultMessage()).append(";");
}
return "lu/index";
} else {
luServices.addNewLu(convertToLu(luDTO));
return "redirect:/classifier";
}
}
#GetMapping("/chageLuWith0")
public String test(#RequestParam("id") int id, Model model) {
model.addAttribute("editedLuDTO", luServices.findById(id));
return "lu/index";
}
#PostMapping("/chageLuWith0")
public String changeLuWith0(#RequestParam("id") int id, #ModelAttribute("editedLuDTO") #Valid LuDTO luDTO) {
luServices.update(id, convertToLu(luDTO));
return "redirect:/classifier";
}
private Lu convertToLu(LuDTO luDTO) {
return modelMapper.map(luDTO, Lu.class);
}
private LuDTO convertToLuDTO(Lu lu) {
return modelMapper.map(lu, LuDTO.class);
}
}
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:form="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width"/>
<link rel="stylesheet" th:href="#{/styles/css/style.css}"/>
<link rel="stylesheet" th:href="#{/styles/css/bootstrap.min.css}"/>
<link rel="stylesheet" th:href="#{/styles/css/awesome/all.css}"/>
<script th:src="#{/js/jquery.min.js}" type="text/javascript"></script>
<script th:src="#{/js/bootstrap.min.js}" type="text/javascript"></script>
<script th:src="#{/js/bootstrap.bundle.min.js}" type="text/javascript"></script>
<title>Main page</title>
</head>
<body>
<div class="page_wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-3">
<div class="row">
<div class="item_configure_menu">
<button type="button" class="btn btn-outline-success" data-bs-toggle="modal" data-bs-target="#addNewLuWith0">
<i class="fa-solid fa-file-medical"></i>
</button>
</div>
<div class="lu_block">
<table>
<tr th:each="luDTO : ${luDTO}">
<td>[[*{luDTO.text}]]
<button type="button" class="btn btn-outline-warning" data-bs-toggle="modal" th:attr="data-bs-target='#editNewLuWith0' + *{luDTO.id}">
<i class="fa-solid fa-pen"></i>
</button>
<div class="modal fade" th:id="*{'editNewLuWith0' + {luDTO.id}}" tabindex="-1" aria-labelledby="editNewLuWith0Label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="editNewLuWith0Label">Add item</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form method="POST" action="#{/chageLuWith0}" th:object="${editedLuDTO}">
<input type="text" th:field="*{tag}" id="tag" value="" placeholder="tag"/>
<div class="error_block" style="color: red" th:if="${#fields.hasErrors('tag')}"
th:errors="*{tag}">tag errors
</div>
<input type="text" th:field="*{shorttext}" id="shorttext" placeholder="shorttext"/>
<div class="error_block" style="color: red" th:if="${#fields.hasErrors('shorttext')}"
th:errors="*{shorttext}">shorttext errors
</div>
<input type="text" th:field="*{text}" id="text" placeholder="text"/>
<div class="error_block" style="color: red" th:if="${#fields.hasErrors('text')}"
th:errors="*{text}">text errors
</div>
<input type="text" th:field="*{lcode}" id="lcode" placeholder="lcode"/>
<div class="error_block" style="color: red" th:if="${#fields.hasErrors('lcode')}"
th:errors="*{lcode}">lcode errors
</div>
<input type="text" th:field="*{code}" id="code" value="" placeholder="code"/>
<div class="error_block" style="color: red" th:if="${#fields.hasErrors('code')}"
th:errors="*{code}">code errors
</div>
<input type="text" th:field="*{bgndat}" id="bgndat" placeholder="bgndat"/>
<div class="error_block" style="color: red" th:if="${#fields.hasErrors('bgndat')}"
th:errors="*{bgndat}">bgndat errors
</div>
<input type="text" th:field="*{enddate}" id="enddate" placeholder="enddate"/>
<div class="error_block" style="color: red" th:if="${#fields.hasErrors('enddate')}"
th:errors="*{enddate}">enddate errors
</div>
<input type="submit" value="Add"/>
</form>
</div>
</div>
</div>
</div>
</td>
<td>[[*{luDTO.getTag()}]]</td>
</tr>
</table>
</div>
</div>
</div>
<div class="col-9">
test info
</div>
</div>
</div>
<div class="modal fade" id="addNewLuWith0" tabindex="-1" aria-labelledby="addNewLuWith0Label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addNewLuWith0Label">Add item</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form th:method="POST" th:action="#{/classifier}" th:object="${newLuDTO}">
<input type="text" th:field="*{tag}" id="tag" value="" placeholder="tag"/>
<div class="error_block" style="color: red" th:if="${#fields.hasErrors('tag')}"
th:errors="*{tag}">tag errors
</div>
<input type="text" th:field="*{shorttext}" id="shorttext" placeholder="shorttext"/>
<div class="error_block" style="color: red" th:if="${#fields.hasErrors('shorttext')}"
th:errors="*{shorttext}">shorttext errors
</div>
<input type="text" th:field="*{text}" id="text" placeholder="text"/>
<div class="error_block" style="color: red" th:if="${#fields.hasErrors('text')}"
th:errors="*{text}">text errors
</div>
<input type="text" th:field="*{lcode}" id="lcode" placeholder="lcode"/>
<div class="error_block" style="color: red" th:if="${#fields.hasErrors('lcode')}"
th:errors="*{lcode}">lcode errors
</div>
<input type="text" th:field="*{code}" id="code" value="" placeholder="code"/>
<div class="error_block" style="color: red" th:if="${#fields.hasErrors('code')}"
th:errors="*{code}">code errors
</div>
<input type="text" th:field="*{bgndat}" id="bgndat" placeholder="bgndat"/>
<div class="error_block" style="color: red" th:if="${#fields.hasErrors('bgndat')}"
th:errors="*{bgndat}">bgndat errors
</div>
<input type="text" th:field="*{enddate}" id="enddate" placeholder="enddate"/>
<div class="error_block" style="color: red" th:if="${#fields.hasErrors('enddate')}"
th:errors="*{enddate}">enddate errors
</div>
<input type="submit" value="Add"/>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
I get an error:
java.lang.IllegalStateException: Neither BindingResult nor plain
target object for bean name 'editedLuDTO' available as request
attribute

pass object from HTML template back to the controller

I have the following HTML block. I want to pass the object "jobDTO" back to the contoller "/deleteJob" method. Whatever I do I am getting null object.
<th:block th:if="${jobDTO != null}" th:each="jobDTO: ${allJobDTOs.get(jobGroup)}">
<div id="accordion2" style="margin-bottom: 3px;">
<div class="card" id="headingOne">
<div class="card-header" style="padding: 0">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" th:attr="data-target='#accordion2_'+${jobDTO.identity.name}"
aria-expanded="true" aria-controls="collapseChild" >
<p class="font-weight-bold custom-p identity-black" > Job Identity </p>
<p class="custom-p" style="padding-left: 52px;" th:text="${jobDTO.identity.group} +' , ' + ${jobDTO.identity.name}"></p>
</button>
</h5>
</div>
<div th:id="'accordion2_'+${jobDTO.identity.name}" class="collapse" aria-labelledby="headingOne" data-parent="#accordion2">
<div class="card-body">
<dl class="row">
<dt class="col-lg-3">Trigger List</dt>
<dd class="col-sm-9">
<th:block th:each="trigger: ${jobDTO.triggers}">
<p><b>nextFireTime</b> <span th:text="${trigger.nextFireTime}"> </span></p>
<hr>
</th:block>
</dd>
</dl>
<!-- important part.. how to pass the jobDTO object back to the controller -->
<form id="form2" action="#" th:action="#{/deleteJob}" th:object="${jobDTO}" th:method="post">
<input type="text" th:value="*{identity.name}" th:field="*{identity.name}" hidden/>
<button type="submit" value="Submit" class="btn btn-danger btn-sm" >Delete Job</button>
</form>
</div>
</div>
</div>
</div>
</th:block>
my controller relevant parts are:
#GetMapping(value = "/deleteJob")
public String deleteJobPage(Model model) {
model.addAttribute("jobDTO", new ScheduleJobDTO());
//Returns the Home page with the prepared model attributes
return "Home";
}
// =================
#PostMapping("/deleteJob")
public String deleteJob(#ModelAttribute final ScheduleJobDTO jobDTOReturn, BindingResult bindingResult, Model model) {
// I want to receive the jobDTO object here
schedulerService.deleteJobFromGroup(jobDTOReturn.getIdentity().getGroup(),
jobDTOReturn.getIdentity().getName());
return "redirect:/";
}
what I am missing here?
I think there is an error in your input tag, try this :
<input type="text" th:value="${jobDTO.identity.name}" th:field="*{identity.name}" hidden/>

Repopulate Textbox in PartialView When Page Fails Validation

I have a View that besides being bound to a model, has 3 partial views (a people picker) of a reuseable component. I perform a validation to check for duplicates of the data in the model at submit. If the record is a dup, it redirects back to the page, where the model can repopulate the model fields. However, I'd like the People Picker values to be retained as well, but since it is not part of the model, I don't know how to do that.
This is the controller
public ActionResult Create(IFormCollection collection)
{
try
{
Dept_COEModel Dept = new DeptModel();
Dept.DeptName = collection["DeptName"];
Dept.DeptAcronym = collection["DeptAcronym"];
Dept.DeptCeNtId = collection["UserIdHidden_20"];
Dept.DeptCeUserName = collection["UserNameHidden_20"];
Dept.DeptCeEmail = collection["UserEmailHidden_20"];
Dept.delegate1PocNtId = collection["UserIdHidden_30"];
Dept.delegate1PocName = collection["UserNameHidden_30"];
Dept.delegate1PocEmail = collection["UserEmailHidden_30"];
Dept.delegate2PocNtId = collection["UserIdHidden_40"];
Dept.delegate2PocName = collection["UserNameHidden_40"];
Dept.delegate2PocEmail = collection["UserEmailHidden_40"];
int result = _adoSqlService.CheckDept(collection["DeptName"]);
if (result == 0)
{
_adoSqlService.InsertDept(dept);
return RedirectToAction(nameof(Index));
}
else
{
ModelState.AddModelError("DeptName", "This Department already exists");
ViewData["UserResultTextbox_20"] = Dept.DeptCeUserName;
return View(Dept);
}
}
catch
{
return View(Dept);
}
}
Here is the View
#model EDAD.Models.LOB_COEModel
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>LOB_COE</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
#*<div class="form-group">
<label asp-for="lobCoeId" class="control-label"></label>
<input asp-for="lobCoeId" class="form-control" />
<span asp-validation-for="lobCoeId" class="text-danger"></span>
</div>*#
<div class="form-group">
<label asp-for="lobCoeName" class="control-label"></label>
<input asp-for="lobCoeName" class="form-control" />
<span asp-validation-for="lobCoeName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="lobCoeAcronym" class="control-label"></label>
<input asp-for="lobCoeAcronym" class="form-control" />
<span asp-validation-for="lobCoeAcronym" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Select Chief Engineer</label>
<div class="form-group form-field-div">
<table>
<tr style="white-space:nowrap;">
<td>
#Html.Action("PeoplePicker", "PeoplePicker", new EDAD.Models.PeoplePickerViewModel { PickerId = 20 })
</td>
<td></td>
</tr>
</table>
</div>
#*<span asp-validation-for="lobCoeCeNtId" class="text-danger"></span>*#
</div>
<div class="form-group">
<label class="control-label">Select Delegate 1</label>
<div class="form-group form-field-div">
<table>
<tr style="white-space:nowrap;">
<td>
#Html.Action("PeoplePicker", "PeoplePicker", new EDAD.Models.PeoplePickerViewModel { PickerId = 30 })
</td>
<td></td>
</tr>
</table>
</div>
#*<span asp-validation-for="lobCoeCeNtId" class="text-danger"></span>*#
</div>
<div class="form-group">
<label class="control-label">Select Delegate 2</label>
<div class="form-group form-field-div">
<table>
<tr style="white-space:nowrap;">
<td>
#Html.Action("PeoplePicker", "PeoplePicker", new EDAD.Models.PeoplePickerViewModel { PickerId = 40 })
</td>
<td></td>
</tr>
</table>
</div>
#*<span asp-validation-for="lobCoeCeNtId" class="text-danger"></span>*#
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Here is the cshmtl for the People Picker (note that this is reusable so I don't want to modify any code in this)
#model ABC.Models.PeoplePickerViewModel
<script src="~/lib/jquery/jquery.js"></script>
<script src="~/js/site.js"></script>
<script>
$(function () {
setUpGlyphicons(#Model.PickerId, '#Url.Action("SearchForUsers", "PeoplePicker")');
});
</script>
<div class="people-picker">
#Html.TextBox("UserResultTextbox_" + Model.PickerId, Model.User.userName, new { #onkeypress = "userSearchKeyPress(event);", #class = "form-control input-smaller", style = "display: inline", placeholder = "Last Name, First Name", autocomplete = "off" })
#Html.Hidden("UserIdHidden_" + Model.PickerId, Model.User.NTId)
#Html.Hidden("StoredUserNameHidden_" + Model.PickerId, Model.User.userName)
#Html.Hidden("UserNameHidden_" + Model.PickerId, Model.User.userName)
#Html.Hidden("UserEmailHidden_" + Model.PickerId, Model.User.userEmail)
<span id="UserEditButton_#Model.PickerId" class="fa fa-pencil icon-inline"></span>
<span id="UserCancelButton_#Model.PickerId" class="fas fa-ban hide icon-inline"></span>
<span id="UserSearchButton_#Model.PickerId" class="fa fa-search hide icon-inline"></span>
#*<span id="InjectButtonPlaceholder_#Model.PickerId" class="hide"></span>*#
<img id="PeoplePickerLoading_#Model.PickerId" class="hide" alt="Loading..." src="~/Images/loading.gif" /><br />
<span id="PeoplePickerError_#Model.PickerId" class="error-label">*</span>
<div id="UserSearchContent_#Model.PickerId" class="list-group user-results"
onmouseout="$('.disable-scroll-container').removeClass('disable-scroll');"
onmouseover="$('.disable-scroll-container').addClass('disable-scroll');">
</div>
</div>
How can I update the fields that start with the word "User" when the view fails validation
I'm going to close this question. I discovered that the issue lies in a different direction and I'm going to post a new question.

Fill a table in JSP with list provided from spring controller

I'm trying to fill a table in a jsp with a List I put in the model from a Spring controller but the table is not being filled. This is the page:
<%# page import="cl.onvision.dte.be.utils.*" %>
<%
String order = request.getParameter("o");
String search = request.getParameter("s");
String strTitulo = "Gestor usuarios";
%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<title>Administrador / Inicio</title>
</head>
<body>
<!-- Header layer -->
<div class="container">
<div class="row" style="background-color: rgb(255,130,0); padding: 10px">
<div class="col-sm-3"><img src="/img/index/slogan150.png" /></div>
<div class="col-sm-4"></div>
<div class="col-sm-5 text-right text-white">
<!--a href="/login/salir">Salir</a-->
<%#include file="/views/include/bannerSesion.jsp"%>
</div>
</div>
</div>
<!-- Menu layer -->
<div class="container">
<ul class="nav nav-tabs nav-justified">
<li class="nav-item"><a class="nav-link" href="/admin/inicio">Inicio</a></li>
<li class="nav-item"><a class="nav-link" href="/admin/usuarios">Gestion Usuarios</a></li>
<li class="nav-item"><a class="nav-link" href="/admin/contrib">Gestion Contribuyentes</a></li>
<li class="nav-item"><a class="nav-link" href="/admin/alertas">Alertas</a></li>
<li class="nav-item"><a class="nav-link active" href="/admin/ciudades">Ciudades</a></li>
</ul>
</div>
<br />
<!-- Search & button upper-layer -->
<div class="container">
<div class="row">
<div class="col-sm-6">
<b>Búsqueda:</b>
<input type="text" class="input-sm" style="height:25px" id="s" value="<%= (search==null)? "": search %>"
maxlength="20" size="20" autofocus />
<input type="hidden" id="o" value="<%= (order==null)? "": order %>" />
</div>
<div class="col-sm-6 text-right">
<button data-toggle="modal" data-target="#modaladd" class="btn btn-sm btn-success">
<i class="material-icons" style="font-size:22px">person_add</i>
</button>
</div>
</div>
</div>
<div style="height:10px"></div>
<!-- Data list -->
<div class="container">
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered table-condensed table-sm">
<thead>
<tr>
<th style="text-align:center">#</th>
<th style="text-align:center">Nombre usuario</th>
<th style="text-align:center">Region</th>
<th style="text-align:center">Acciones</th>
</tr>
</thead>
<tbody>
<c:forEach var="ciudad" items="${ciudades}">
<tr>
<td style="text-align:center"><c:out value="${ciudad.id}"/></td>
<td style="text-align:center"><c:out value="${ciudad.nombre}"/></td>
<td style="text-align:center"><c:out value="${ciudad.region}"/></td>
<td class="pl-5">
<a href="/admin/usuario/eliminar/${ciudad.id}/">
<button class="btn btn-sm btn-primary"><i class="material-icons"
style="font-size:16px">remove_circle</i></button>
</a>
<a href="javascript:leerDatos(${ciudad.id});">
<button class="btn btn-sm btn-warning"><i class="material-icons"
style="font-size:16px">border_color</i></button>
</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
<a href="#" id="axls" style="display:none;" donwload>a</a>
<!-- Modal 'add user' form-->
<div class="modal" id="modaladd">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header bg-info text-white">
<h2 class="modal-title">Agregar nuevo usuario</h2>
</div>
<!-- Modal body -->
<form method="post" action="/admin/usuario/agregar">
<div class="modal-body">
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="nom">Nombre de usuario:</label></div>
<div class="col-sm-8">
<input type="text" class="form-control input-sm" name="nomusu" id="nom" maxlength="40"
required />
</div>
</div>
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="run">RUN:</label></div>
<div class="col-sm-8">
<input type="text" class="form-control input-sm" name="runusu" id="run" maxlength="40"
required />
</div>
</div>
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="cla">Nueva clave:</label></div>
<div class="col-sm-8">
<input type="password" class="form-control input-sm" name="cla1usu" id="cla"
maxlength="20" required />
</div>
</div>
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="cla2">Repita la clave:</label></div>
<div class="col-sm-8">
<input type="password" class="form-control input-sm" name="cla2usu" id="cla2"
maxlength="20" required />
</div>
</div>
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="com">Comentarios:</label></div>
<div class="col-sm-8">
<textarea class="form-control input-sm" name="comentusu" id="com" rows="3"
cols="80"></textarea>
</div>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Agregar nuevo usuario" />
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancelar</button>
</div>
</form>
</div>
</div>
</div>
<!-- Modal 'update user' form-->
<div class="modal" id="modalupdate">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header bg-info text-white">
<h2 class="modal-title">Modificar usuario</h2>
</div>
<!-- Modal body -->
<form method="post" action="/admin/usuario/modificar">
<div class="modal-body">
<input type="hidden" name="uid" id="uid" value="" />
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="unom">Nombre de usuario:</label></div>
<div class="col-sm-8">
<input type="text" class="form-control input-sm" name="unomusu" id="unom" maxlength="40"
readonly />
</div>
</div>
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="urun">RUN:</label></div>
<div class="col-sm-8">
<input type="text" class="form-control input-sm" name="urunusu" id="urun" maxlength="40"
readonly />
</div>
</div>
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="ucom">Comentarios:</label></div>
<div class="col-sm-8">
<textarea class="form-control input-sm" name="ucomentusu" id="ucom" rows="3"
cols="80"></textarea>
</div>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Modificar datos" />
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancelar</button>
</div>
</form>
</div>
</div>
</div>
</body>
<script>
function ordenarDatos(campo) {
url = 'gestionUsuarios.jsp?o=' + campo + '&s=' + $('#s').val();
document.location.href = url;
return null;
}
/*function descargarXls()
{
url1 = '${pageContext.request.contextPath}/ExtraerXlsUsuarios.do';
$.ajax( {url: url1,
success: function(result)
{
//$('#axls').attr('href', "../" + result);
location.href = "../" + result; //$('#axls').attr('href');
} });
}*/
$('#s').keypress(function (event) {
if (event.which == 13) {
document.location.href = 'gestionUsuarios.jsp?o=' + $('#o').val() + '&s=' + $('#s').val();
return null;
}
}
);
function leerDatos(id) {
$.post("/admin/usuario/ver/" + id + "/", function (obj) {
obj = JSON.parse(obj);
$('#uid').val(obj.id);
$('#unom').val(obj.nom);
$('#urun').val(obj.run);
$('#ucom').val(obj.com);
$('#modalupdate').modal('show');
obj = null;
});
}
/*$().ready( function()
{
v = $('#s').val();
$('#s').val('');
$('#s').val(v);
});*/
</script>
</html>
I'm putting the list into the model right, as you can see in the chrome developer tools:
I can't see the problem here, I need help trying to figure out why the table is not being filled.
Try including the <%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> athe top of your code. Also, make sure your object name ciudades is spelled as it is in your controller.
Well my problem was thwo things:
I'm using tomcat as webapp which doesn't bring JSTL embeddeb. So I had to add the dependency in the pom.xml.The version is important if you want to use EL's.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
I had to add the taglib on top of the JSP to access the <c:> tags. Thanks to #Morteza Bandi for the heads up.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

How to fill List<string> field in Thymeleaf + Spring

here is my form
<!--destinationList List-->
<div class="form-group">
<div class="col-sm-3">
<label for="Destination">Destination</label>
</div>
<div class="col-sm-9">
<input type="text" class="form-control" th:field="*{destinationList[0]}" />
<input type="text" class="form-control" th:field="*{destinationList[1]}" />
<input type="text" class="form-control" th:field="*{destinationList[2]}" />
<input type="text" class="form-control" th:field="*{destinationList[3]}" />
</div>
</div>
<div class="form-group">
<div class="col-sm-9">
<button type="submit" class="btn btn-primary btn-block">Calculate</button>
</div>
</div>
</form>
And I'm going to fill following model
public class PriceSearchDTO {
private List<String> destinationList;
public List<String> getDestinationList() {
return destinationList;
}
public void setDestinationList(List<String> destinationList) {
this.destinationList = destinationList;
}
}
I can do this. But I hard coded number of input fields in the list as above in the view. I need to genarate them dynamically and make the number of element in the list is airbitary.
Try this:
<div class="col-sm-9">
<input type="text" class="form-control" th:each="destination : ${destinationList}" th:field="*{destination}" />
</div>
You are using Iteration in Thymeleaf. In fact, there is a quite complete set of objects that are considered iterable by a th:each attribute.
Like this :
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Good Thymes Virtual Grocery</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all"
href="../../../css/gtvg.css" th:href="#{/css/gtvg.css}" />
</head>
<body>
<h1>Product list</h1>
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>IN STOCK</th>
</tr>
<tr th:each="destination: ${destinations}">
<td th:text="${destination}">Onions</td>
</tr>
</table>
<p>
Return to home
</p>
</body>
</html>
And Controller in Spring framework.
#RequestMapping(value = "/")
public ModelAndView showView(ModelAndView mav) {
List<String> destinations = new ArrayList<String>();
destinations.add("elementA");
destinations.add("elementB");
destinations.add("elementC");
mav.addObject("destinations", destinations);
mav.setViewName("/viewName");
return mav;
}

Resources