Fill a table in JSP with list provided from spring controller - spring-boot

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" %>

Related

Spring Security Binding Result always false

so.. I have a registration page and there are a lot of validations in there but my binding result is always false. After a few tries I found the problem but I don't know the solution. When I pass a parameter in the /processRegistrationForm method it doesn't work but when I delete the #RequestParam it works. Why the passed parameter is influencing the binding result and how can I resolve this?
registration-form.html
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Register New User Form</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Reference Bootstrap files -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
.error {color:red}
</style>
</head>
<body>
<div>
<div id="loginbox" style="margin-top: 50px;"
class="mainbox col-md-3 col-md-offset-2 col-sm-6 col-sm-offset-2">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="panel-title">Register New User</div>
</div>
<div style="padding-top: 30px" class="panel-body">
<!-- Registration Form -->
<form th:action="#{/processRegistrationForm(flag=${flag})}"
th:object="${crmUser}" method="POST"
class="form-horizontal">
<!-- Place for messages: error, alert etc ... -->
<div class="form-group">
<div class="col-xs-15">
<div>
<!-- Check for registration error -->
<div th:if="${registrationError}" class="alert alert-danger col-xs-offset-1 col-xs-10">
<span th:text="${registrationError}"></span>
</div>
</div>
</div>
</div>
<!-- User name -->
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" th:field="*{userName}" placeholder="username (*)" class="form-control" />
</div>
<div th:if="${#fields.hasErrors('userName')}"
style="margin-bottom: 25px" class="text-danger">
<ul>
<li th:each="err : ${#fields.errors('userName')}" th:text="'User name ' + ${err}" />
</ul>
</div>
<!-- Password -->
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input type="password" th:field="*{password}" placeholder="password (*)" class="form-control" th:errorclass="fieldError" />
</div>
<div th:if="${#fields.hasErrors('password')}"
style="margin-bottom: 25px" class="text-danger">
<ul>
<li th:each="err : ${#fields.errors('password')}" th:text="'Password ' + ${err}" />
</ul>
</div>
<!-- Confirm Password -->
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input type="password" th:field="*{matchingPassword}" placeholder="confirm password (*)" class="form-control" th:errorclass="fieldError" />
</div>
<div th:if="${#fields.hasErrors('matchingPassword')}"
style="margin-bottom: 25px" class="text-danger">
<ul>
<li th:each="err : ${#fields.errors('matchingPassword')}" th:text="'Password ' + ${err}" />
</ul>
</div>
<!-- First name -->
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" th:field="*{firstName}" placeholder="first name (*)" class="form-control" th:errorclass="fieldError" />
</div>
<div th:if="${#fields.hasErrors('firstName')}"
style="margin-bottom: 25px" class="text-danger">
<ul>
<li th:each="err : ${#fields.errors('firstName')}" th:text="'First name ' + ${err}" />
</ul>
</div>
<!-- Last name -->
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" th:field="*{lastName}" placeholder="last name (*)" class="form-control" th:errorclass="fieldError" />
</div>
<div th:if="${#fields.hasErrors('lastName')}"
style="margin-bottom: 25px" class="text-danger">
<ul>
<li th:each="err : ${#fields.errors('lastName')}" th:text="'Last name ' + ${err}" />
</ul>
</div>
<!-- Email -->
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" th:field="*{email}" placeholder="email (*)" class="form-control" th:errorclass="fieldError" />
</div>
<div th:if="${#fields.hasErrors('email')}"
style="margin-bottom: 25px" class="text-danger">
<ul>
<li th:each="err : ${#fields.errors('email')}" th:text="'Email ' + ${err}" />
</ul>
</div>
<!-- Register Button -->
<div style="margin-top: 10px" class="form-group">
<div class="col-sm-6 controls">
<button type="submit" class="btn btn-primary">Register</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
controller:
#PostMapping("/processRegistrationForm")
public String processRegistrationForm(
#Valid #ModelAttribute("crmUser") CrmUser theCrmUser,#RequestParam(name="flag") Integer flag,
Model theModel,BindingResult theBindingResult) {
String userName = theCrmUser.getUserName();
// form validation
if (theBindingResult.hasErrors()){
return "registration-form";
}
// check the database if user already exists
User existing = userService.findByUserName(userName);
if (existing != null){
theModel.addAttribute("crmUser", new CrmUser());
theModel.addAttribute("registrationError", "User name already exists.");
return "registration-form";
}
// create user account
userService.save(theCrmUser);
if(flag==0)
return "redirect:/user";
else return "redirect:/list";
}
The problems are here:
/register-form:
<!-- Registration Form -->
<form th:action="#{/processRegistrationForm(flag=${flag})}"
th:object="${crmUser}" method="POST"
class="form-horizontal">
/processRegisterForm:
PostMapping("/processRegistrationForm")
public String processRegistrationForm(
#Valid #ModelAttribute("crmUser") CrmUser theCrmUser,#RequestParam(value = "flag",required = false) Integer flag,
BindingResult theBindingResult,
Model theModel) {...

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

Dynamic Form Fields on Table using thymeleaf and Spring Boot

I am trying to create rows dynamically in a table using thymeleaf and spring boot.
I've looked at following urls but couldn't make it working for me.
http://forum.thymeleaf.org/I-have-problem-in-binding-the-list-of-objects-contained-inside-a-object-on-the-form-using-thymeleaf-td3525038.html#a3526497
http://stingh711.github.io/dynamic-form-with-springmvc-and-thymeleaf.html
when I click on the addCourse button, its not even going to StudentController.
please can someone help?
Student.html
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="layout">
<head>
<title>Students</title>
</head>
<body>
<div layout:fragment="content">
<form th:object="${student}" th:action="#{/student/create}" action="#" method="post">
<div class="row">
<div class="col-md-offset-3 col-md-6">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Add New Student</h3>
</div>
<div class="panel-body">
<input type="text" th:field="*{studentId}" class="form-control" placeholder="Student Id" />
<div style="clear: both; display: block; height: 10px;"></div>
<input type="text" th:field="*{firstName}" class="form-control" placeholder="First Name" />
<div style="clear: both; display: block; height: 10px;"></div>
<input type="text" th:field="*{lastName}" class="form-control" placeholder="Last Name" />
<div style="clear: both; display: block; height: 10px;"></div>
<input type="text" th:field="*{city}" class="form-control" placeholder="City" />
<div style="clear: both; display: block; height: 10px;"></div>
<input type="submit" class="btn btn-success pull-right"
value="Save">
</div>
</div>
</div>
</div>
<!-- start of detail section -->
<div class="row" style="margin-bottom: 50px;">
<div class="col-md-offset-2 col-md-8">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Student Courses</h3>
</div>
<div class="panel-body">
<table class="table table-bordered table-striped table-hover">
<thead>
<tr class="btn-success">
<th>Course</th>
<th>End Date</th>
</tr>
</thead>
<tbody>
<tr th:each="studentCourse, rowStat : *{studentCourses}">
<td></td>
<td><input type="text" class="form-control" th:field="*{studentCourses[__${rowStat.index}__].courseId}" placeholder="Course" /></td>
<td><input type="text" class="form-control" th:field="*{studentCourses[__${rowStat.index}__].endDate}" placeholder="End Date"/>
<span class="col-sm-1 row-delete-button">
<button class="btn btn-default" th:value="*{studentCourses[__${rowStat.index}__].studentCourseId}" name="removeStudentCourse">
<i class="glyphicon glyphicon-trash icon-white"></i>
</button>
</span>
</tr>
</tbody>
</table>
<button class="btn btn-success btn-add" type="submit" name="addCourse">
<i class="glyphicon glyphicon-plus gs"></i> <b> Add</b>
</button>
</div>
</div>
</div>
<!-- end of detail -->
</form>
</div>
</body>
</html>
StudentController
#RequestMapping(value="/Student", params = {"addCourse"})
public String addCourse(Student student, BindingResult result) {
System.out.println("add new course");
student.getCourseList().add(new StudentCourse());
return "Student";
}
js.html (locatated # templates/fragments)
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<script th:src="#{/webjars/jquery/2.1.4/jquery.min.js}"></script>
style.html (locatated # templates/fragments)
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<link rel="stylesheet" th:href="#{/webjars/bootstrap/3.3.4/css/bootstrap.min.css}" />

loading popup jsp page on view jsp without page refresh using jQuery-ajax

I've two jsp pages 1.view.jsp,2.popup.jsp (it is a popup page).the popup.jsp will be loaded when I click the 'add icon' on my view.jsp. Just I want to know how to load values on my 'view.jsp' (without refreshing the page) when 'submit' button is clicked on my 'popup.jsp' using Ajax.
view.jsp
<body>
<div class="st-content">
<jsp:include page="/WEB-INF/jsp/settings/adminmenu.jsp" />
<div class="width1">
<div class="mgmt-menu-bar font-new">
<div class="margin-left10 margin-top line-height1 ">
<a href="executeIndustry">
<div class="menunew cursor red">
<i class="icon-list icon-grey1"></i> Industry</div>
</a>
<a href="viewDepartment">
<div class="menunew cursor" ><i class="icon-list icon-grey1"></i> Department</div>
</a>
<a href="addViewDesignation">
<div class="menunew cursor" ><i class="icon-list icon-grey1"></i> Designation</div>
</a>
</div>
</div>
<div class="mgmt-content-right">
<div class="width2 margin-left10">
<div class="content-table-full">
<div class="content-h bold margin-left margin-top">Industry
<div class="top-right-icon2 cursor" data-toggle="tooltip" title="Add Industry" onclick="TINY.box.show({iframe:'addPageIndustry.action',boxid:'frameless',width:456,height:200, fixed:false,maskid:'bluemask',maskopacity:40})" >
<i class="icon-plus icon-grey1"></i>
</div>
</div>
<s:form action="executeIndustry" name="paginationForm" id="paginationForm">
<s:hidden name="industryId" id="industryId"/>
<s:if test="%{success!=null}" >
<div id="error" style="color:#048350;margin-top: 10px" >
<s:property value="success"/>
<br/>
</div>
</s:if>
<s:if test="%{error!=null}" >
<div id="error" style="color: #FF0000;margin-top: 10px">
<s:property value="error"/>
<br/>
</div>
</s:if>
<table width="100%" cellpadding="0" cellspacing="0" class="margin-bottom margin-top table-display">
<tr class="row-header">
<td >
Industry </td>
<td width="450">Created Date</td>
<td width="200">Action</td>
</tr>
<s:if test="%{industrylist!= null && industrylist.size > 0}">
<s:iterator value="industrylist">
<tr class="row1">
<td > <s:property value="industryName"/></td>
<td> <s:date name="createdDate" format="dd/MM/yyyy hh:mm:ss a"/></td>
<td>
<i class="icon-edit icon-grey1 cursor" title="Edit" data-toggle="tooltip" onclick="TINY.box.show({iframe:'editIndustry.action?editid=<s:property value="industryId"/>',boxid:'frameless',width:456,height:200, fixed:false,maskid:'bluemask',maskopacity:40})"></i>
<i title="Delete" data-toggle="tooltip" onclick="deletethis('<s:property value="industryId"/>')" class="icon-minus-sign icon-grey1 cursor"></i>
</td>
</tr>
</s:iterator>
</s:if>
<s:else>
<tr class="row1">
<td colspan="4" align="center">No industries were found</td>
</tr>
</s:else>
<s:hidden name="deleteid" id="deleteid"></s:hidden>
</table>
<div class="width2">
<s:if test="%{industrylist.size()>0}">
<%# include file="/WEB-INF/jsp/pagenation/pagination.jsp" %>
</s:if>
</div>
</s:form>
</div>
</div>
</div>
</div>
</div>
<jsp:include page="/common/commonfooter.jsp" />
<script type="text/javascript" src="shared/scripts/js/pagination.js"></script>
</div>
popup.jsp
<body>
<div class="pop-box">
<s:if test="%{edit!=1}" >
<s:form action="addIndustry" method="post" id="FormOne" name="FormOne" target="_top" cssClass="validate">
<span style="margin-left:10px;" class="heading-st2">Add Industry</span>
<div class="popup-style">
<div class="row-form">
<span class="red">*</span>Industry
</div>
<div class="row-form ">
<s:textfield name="industryName" id="industryName" cssClass="input-xlarge required-field" oncopy="return false" onpaste="return false" oncut="return false" onkeypress="return isNumberKey(event)" maxlength="60" />
</div>
<div class="row-form">
<button type="submit" class="btn btn-success ">Submit <i class="icon-ok icon-white"></i></button>
<span class="help-inline"></span>
</div>
</div>
</s:form>
</s:if>
<s:else>
<s:form action="updateIndustry" method="post" id="FormOne" name="FormOne" target="_top" cssClass="validate">
<s:hidden name="industryId"/>
<span style="margin-left:10px;" class="heading-st2">Edit Industry</span>
<div class="popup-style">
<div class="row-form">
<span class="red">*</span>Industry
</div>
<div class="row-form ">
<s:textfield name="industryName" id="industryName" cssClass="input-xlarge required-field" oncopy="return false" onpaste="return false" oncut="return false" onkeypress="return isNumberKey(event)" maxlength="60" />
</div>
<div class="row-form">
<button type="submit" class="btn btn-success ">Submit <i class="icon-ok icon-white"></i></button>
<span class="help-inline">
</span>
</div>
</div>
</s:form>
</s:else>
</div>
$(document).ready(function(){
var frm = $('#myform');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert("submitted");
},
error:function(data){
alert("error");
}
});
window.scrollTo(0,0);
ev.preventDefault();
});
The above jquery ajax helps you to accompany your action submittion without refreshing...

smarty template getting blank after entering js validation

pinterest js
<script type="text/javascript">
(function(d){
var f = d.getElementsByTagName('SCRIPT')[0], p = d.createElement('SCRIPT');
p.type = 'text/javascript';
p.async = true;
p.src = '//assets.pinterest.com/js/pinit.js';
f.parentNode.insertBefore(p, f);
}(document));
</script>
css files
<link rel='stylesheet' href='css/fab-sales.css' media='all' type='text/css' />
<link rel='stylesheet' href='css/basic.css' media='all' type='text/css' />
codes
{if isset($products)}
<!-- Products list -->
<ul id="product_list" class="clear">
{foreach from=$products item=product name=products}
{assign var=foo value=$product.link}
<li class="ajax_block_product {if $smarty.foreach.products.first}first_item{elseif $smarty.foreach.products.last}last_item{/if} {if $smarty.foreach.products.index % 2}alternate_item{else}item{/if} clearfix">
<div class="left_block">
{if isset($comparator_max_item) && $comparator_max_item}
<p class="compare">
<input type="checkbox" class="comparator" id="comparator_item_{$product.id_product}" value="comparator_item_{$product.id_product}" {if isset($compareProducts) && in_array($product.id_product, $compareProducts)}checked="checked"{/if} />
<label for="comparator_item_{$product.id_product}">{l s='Select to compare'}</label>
</p>
{/if}
</div>
<div class="center_block">
<div align="center" id="prodList">
<div class="product">
<div class="prodImgBlock filler" style="cursor:pointer"><a href="{$foo|escape:'htmlall':'UTF-8'}" class="product_img_link" title="{$product.name|escape:'htmlall':'UTF-8'}"><img src="{$link->getImageLink($product.link_rewrite, $product.id_image, 'home_default')}" alt="{$product.legend|escape:'htmlall':'UTF-8'}" {if isset($homeSize)} width="{$homeSize.width}" height="{$homeSize.height}"{/if} />{if isset($product.new) && $product.new == 1}<span class="new">{l s='New'}</span>{/if}
</a></div>
<div class="newSocialCt">
<div class="newSocialToolBar"> <span style="left: 10px;" class="newSocialTool faveIt"> <span style="position: relative;top: 4px;display: none;" class="loader"> <img src="img/tmp/ajax-loader-white.gif"> </span></span> <span class="loaderCt newSocialTool"></span> <span class="newSocialTool pinItTool" style="float:left; margin-left:-10px; margin-right:5px;"> <img src="//assets.pinterest.com/images/pidgets/pin_it_button.png" /> </span> <span class="newSocialTool" style="float:left; width:85px; margin-left:15px;">
<div id='basic-modal'> <a href='#' class='basic'><img alt="Share" src="img/tmp/tellafriend.png" border="0" /></a> </div>
</span> <span class="newSocialTool" style="float:none; margin-right:20px;">
<div class="fb-like" data-href="$foo" data-send="false" data-layout="button_count" data-width="450" data-show-faces="true"></div>
</span> </div>
</div> </div>
</div>
<div class="productCt">
<div class="productDet" id="0"><h4>{$product.name|escape:'htmlall':'UTF-8'|truncate:35:'...'}</h4>
<p class="product_desc"><a href="{$product.link|escape:'htmlall':'UTF-8'}" title="{$product.description_short|strip_tags:'UTF-8'|truncate:360:'...'}" >{$product.description_short|strip_tags:'UTF-8'|truncate:130:'...'}</a></p>
</div>
</div></div>
<div id="push" class="clear"></div>
<div id="basic-modal-content">
<div id="tellFriendBox">
<div class="popUpHd">
<h2>Tell A Friend!</h2>
</div>
<div class="error" id="tf"></div>
<form class="" id="" method="post" action="" enctype="multipart/form-data">
<div class="eachRow">
<div>Your Name
<label style="color:#FF0000">*</label>
:</div>
<div class='field'>
<input type='text' id="name" class="required email" name="name" size='33'/>
</div>
</div>
<div class="eachRow">
<div>Friends Email Address
<label style="color:#FF0000">*</label>
:</div>
<div class='field'>
<input type='text' id="email_id" class="required email" name="email" size='33'/>
</div>
</div>
<div class="eachRow">
<div>Matter:</div>
<div class='field'>
<textarea rows='4' cols='25' id="matter" class="required" name="matter" ></textarea>
</div>
</div>
<div class="eachRow">
<div class='field'>
<input class="button" type='submit' name="tellafriend" onclick="return TellFriend(); " value="Send Mail"/>
</div>
</div>
</form>
</div>
</div>
<div style='display:none'> <img src='img/tmp/x.png' alt='' /> </div>
***after putting following javascript code for validation smarty template getting blank
<script type="text/javascript">
function TellFriend()
{
var em = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(document.getElementById("name").value == "")
{
document.getElementById("tf").innerHTML= "* Marks Fields are Mandatory ";
document.getElementById("name").focus();
return false;
}
if(document.getElementById("email_id").value == "")
{
document.getElementById("tf").innerHTML= "* Marks Fields are Mandatory ";
document.getElementById("email_id").focus();
return false;
}
if (document.getElementById("email_id").value.search(em) == -1)
{
document.getElementById("tf").innerHTML= "Invalid Email "+"</span>";
document.getElementById("email_id").focus();
return false;
}
}
</script>
need help..and after putting $foo as URL in pinterest..pinterest count button disappering..
You should enclose the javascript in {literal}{/literal} tags
There is the great article for undestand debug process: http://blog.belvg.com/showing-php-and-sql-errors-and-debugging-a-blank-white-page-in-prestashop.html

Resources