Receive parameters from Thymleaf page - java

I have tried to send a parameter from this thymleaf page
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Email</th>
<th>Send Invoice</th>
</tr>
</thead>
<tbody>
<tr class="table-row" th:each="p : ${POList}">
<td th:text="${p.email}"></td>
<td>
<form style='float:left; padding:5px; height:0px' th:object="${p}" th:method="post" th:action="#{/dashboard/makeAndSendInvoice/{email}(email=${p.email})}">
<button class="btn btn-default btn-xs" type="submit">Send Invoice</button>
</form>
</td>
</tr>
</tbody>
and then I tried to receive the parameter (email) using this code
#RequestMapping(method=POST, path="/makeAndSendInvoice/{email}")
public void makeAndSendInvoice(#PathVariable("email") String email) throws Exception {
System.out.println("Invoice is sent to..................."+email);
}
The problem is when the value of p.email is something like myemail#gmail.com
what I receive in the method makeAndSendInvoice is only myemail#gmail
and it does not send me the .com part
How can I fix it?

(email=${p.email}) means , you are passing a query parameter.
So, how can you be able to catch the query param value using path variable?
We can use #RequestParam to catch the queryparam value in Spring
Try the below java code :
#RequestMapping(method=POST, path="/makeAndSendInvoice/{email}")
public void makeAndSendInvoice(#RequestParam("email") String email) throws Exception {
System.out.println("Invoice is sent to..................."+email);
}

The period in ".com" will need to be encoded to be used in the url to prevent it being parsed as the suffix

Your HTML:
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Email</th>
<th>Send Invoice</th>
</tr>
</thead>
<tbody>
<tr class="table-row" th:each="p : ${POList}">
<td th:text="${p.email}"></td>
<td>
<form method="post" th:action="#{/dashboard/makeAndSendInvoice/__${p.email}__} ">
<button class="btn btn-default btn-xs" type="submit">Send Invoice</button>
</form>
</td>
</tr>
</tbody>
Your controller
#RequestMapping(value = "/dashboard")
#Controller
public class testController {
...
#RequestMapping(value = "/makeAndSendInvoice/{email}", method = RequestMethod.POST)
public ModelAndView makeAndSendInvoice(#PathVariable String email, ModelAndView mav) {
return mav; // <- Break point, debug !!
}
}

Related

How to read MomgoDB data from HTML page using Sprinboot

This is my controller class read data method. I cant read spring data from requesting. when I do it from postman it works fine but cant read using html page.
#RequestMapping("/index")
public String ItemList(Model model) {
model.addAttribute("itemList", repository.findAll());
return "index";
}
Like this I try to read data using my index.html page
<h2>Medicine List</h2>
<form action="/index" method="POST">
<table>
<thead>
<tr>
<th>ID</th>
<th>MedicineName</th>
<th>Description</th>
<th>Quantity</th>
<th>Price</th>
<th>ExDate</th>
</tr>
</thead>
<tbody>
<tr th:each="item:${itemList}">
<td th:text="${item.id}"></td>
<td th:text="${item.MedicineName}"></td>
<td th:text="${item.Description}"></td>
<td th:text="${item.Quantity}"></td>
<td th:text="${item.Price}"></td>
<td th:text="${item.ExDate}"></td>
<td><form action="/delete/item:${itemList}" method="Delete"><input type="submit" value="Delete" /></form></td>
</tr>
</tbody>
</table>
</form>

How to refresh page content after POST request without location.reload()

Goal
After a POST request, I want to update a list. For example, if a user is added, so user list must be refresh.
So I do the post request, then I do a get request to update the content.
There is a way to do it without reload the page?
Thanks for your answer!
Ajax calls
function rafraichirContenu(url, type) {
$.ajax({
url: url,
type: type
}).done(function (response) {
$(document).html(response)
});
}
postRequest().done(function(response) {
rafraichirContenu('/emprunts/encours', 'GET');
...
});
Get Mapping
#GetMapping(value = "/encours")
public ModelAndView findAllEnCours() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("emprunts", empruntResource.getEmpruntsByStatutEquals(StatutEmprunt.EN_COURS));
modelAndView.setViewName("webapp/pages/emprunts");
return modelAndView;
}
HTML
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionEmprunts">
<div class="card-body">
<table class="table">
<thead>
<tr>
<th scope="col">Usager</th>
<th scope="col">Exemplaire</th>
<th scope="col">Date de rendu</th>
<th scope="col">Statut</th>
</tr>
</thead>
<tbody>
<th:block th:each="emprunt : ${emprunts}">
<tr>
<!--/*#thymesVar id="emprunt" type="bibliotheque.model.Emprunt"*/-->
<td th:text="${emprunt.getUsager().getMail()}"></td>
<td th:text="${emprunt.getExemplaire().getOeuvre().getTitre()}"></td>
<td th:text="${emprunt.getDaterendu()}"></td>
<td th:text="${emprunt.getStatut()}"></td>
</tr>
</th:block>
</tbody>
</table>
</div>
</div>
Console error
jquery.min.js:2 Uncaught TypeError: Cannot read property 'createDocumentFragment' of null

Showing error message on JSP using BindingResult

I am new to Spring.
I am trying to show error messages on jsp for the wrong user and password by using BindingResult. But the error messages are not showing.
Please suggest me what I is wrong in the below code.
JSP
<script type="text/javascript">
function loginUser() {
$('#loginForm').submit();
}
</script>
</head>
<body>
<form:form action="login.test" id="loginForm" commandName="loginForm" method="POST">
<div class="brand_area"></div>
<div class="content_area">
<table style="top: 360px; position: relative; margin-left: 333px;">
<tr id="uNameID">
<td class="label">User Name:</td>
<td><form:input id="userNameID" path="userName" class="textInput" /></td>
<td><form:errors path="userName" class="error"/></td>
</tr>
<tr id="pID">
<td class="label">Password:</td>
<td><form:password id="passwordID" path="password" class="textInput" /></td>
<td><form:errors path="password" class="error"/></td>
</tr>
<tr>
<td></td>
<td><span id="saveButton" class="loginButton"
onclick="loginUser()"> <span>Login</span>
</span></td>
</tr>
</table>
</div>
</form:form>
Controller
#RequestMapping(value = "login.test", method = RequestMethod.POST)
public String processForm( LoginForm loginForm, BindingResult result, ModelMap model, HttpSession session) throws SQLException {
String resultedPage;
model.addAttribute("l_nodes", reportService.getAllLiveNodes());
model.addAttribute("s_nodes", reportService.getAllStaticReportNodes());
User user = userService.getUserByName( loginForm.getUserName() );
if( user != null ){
session.setAttribute("userID", user.getUserID());
if( loginForm.getPassword().equals( user.getPassword() ) ){
resultedPage = "home/userHome";
}else{
result.rejectValue( "password", "login.passwordNotValid");
resultedPage = "redirect:login.test";
}
}else{
result.rejectValue( "userName", "login.userNotValid");
resultedPage = "redirect:login.test";
}
return resultedPage;
}
Thanks
In case anyone else research the same...
Add the hasBindErrors tag to your JSP:
<spring:hasBindErrors name="loginForm">
<c:forEach var="error" items="${errors.allErrors}">
<b><spring:message message="${error}" /></b>
<br/>
</c:forEach>
</spring:hasBindErrors>
Well, i generally send back the values using the Model object.
May be this answer might help you.

Submitting a Spring Form in AJax is always null

I am trying to submit a spring form via ajax but the values within the form are always coming across as null (The actual form is not null).
This is how I send the form from the JSP:
$('#fSystemSave').click(function() {
$.post("/live-application/systemSave", {systemForm: $("#systemForm").serialize()}, displayModifiedSystemResults, "html");
});
This is the form:
<form:form id="systemForm"
method="post" action="/live-application/systemSave"
commandName="systemForm">
<tr>
<td colspan="1" align="left">
<strong>SYSTEM SETTINGS</strong>
</td>
</tr>
<tr>
<td valign="top">Name: </td>
<td valign="top"><form:input path="fName" size="20" /> </td>
</tr>
<tr>
<td valign="top" align="left">
<button type="button" id="fSystemSave">Save</button>
</td>
</tr>
</form:form>
And this is the Java controller side:
#RequestMapping(value = "/systemSave", method = RequestMethod.POST)
public void saveSystem(#ModelAttribute("systemForm") SystemForm systemForm, OutputStream outputStream) throws IOException {
logger.info("Save System1: " + systemForm);
logger.info("Save System2: " + systemForm.getfName());
}
So 'Save System1' returns an Object tostring and 'Save System2' returns null. Can anyone spot what I am doing wrong?
Thanks,
I don't know Spring but I think {systemForm: $("#systemForm").serialize()} should just be $("#systemForm").serialize().

form:errors does not display error message when value is rejected

the complete code is in github:
https://github.com/cuipengfei/MPJSP/tree/master/tmp
in the controller, there is a method that handles the submit:
#RequestMapping(value = "/home", method = RequestMethod.POST)
public void handleSubmit(Customer model, BindingResult result) {
System.out.println(model.getUserName());
result.rejectValue("userName", "required.userName", "user name invalid");
}
and in jsp, there is a form like this:
<form:form method="POST" action="home" modelAttribute="Customer">
<table>
<tr>
<td>Username :</td>
<td><form:input path="userName" /></td>
<td><form:errors path="userName" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
the controllers just rejects value every time, but the error message is not displayed.
the complete code can be found here:
https://github.com/cuipengfei/MPJSP/tree/master/tmp
try to set commandName attribute in your form tag
<form:form method="POST" action="home" commandName="Customer">

Categories