I tried to do an HTML form with "generate pdf" button. The button converts HTML form to PDF successfully, but it doesn't retrieve the text field values (firstname) in HTML to PDF.
carrier.html
<form id="carrierform" method="post" action="PDFServlet">
<div class="wrapper">
<span id="wrappspan">First Name:*</span>
<input type="text" class="input" id="firstname">
</div>
<div class="wrapper">
<span id="wrappspan">Middle Name:</span>
<input type="text" class="input" id="middlename" >
</div>
<div class="wrapper">
<span id="wrappspan">Last Name:*</span>
<input type="text" class="input" id="lastname" >
</div>
<div class="wrapper">
<span id="wrappspan">Date of birth:*</span>
Day<input id="spinner1">
Month<input id="spinner2">
Year<input id="spinner3">
</div>
<div class="wrapper" >
<span id="wrappspan">Sex:*</span>
<input type="radio" name="sex" value="Male" size="17">Male
<input type="radio" name="sex" value="Female" size="17">Female
</div>
<div class="wrapper">
<span id="wrappspan">Degree:*</span>
<select>
<option class="selectWrap" value="1">B-TECH</option>
<option class="selectWrap" value="2">M-TECH</option>
<option class="selectWrap" value="3">MS</option>
</select>
</div>
<div class="wrapper">
<span id="wrappspan">Type:</span>
<select>
<option class="selectWrap" value="1">Full Time</option>
<option class="selectWrap" value="2">Part Time</option>
<option class="selectWrap" value="3">Open</option>
</select>
</div>
<div class="wrapper">
<span id="wrappspan">Resume:*</span>
<input id="filebrowse" type="file" name="datafile" size="40">
<input type="submit" value="upload" />
</div>
<div class="wrapperbutton">
<!-- <button id="getvalue">Submit</button> -->
</div>
<button id="cmd" >generate PDF</button>
</form>
web.xml
<servlet>
<servlet-name>PDFServlet</servlet-name>
<servlet-class>pdfconverter.PDFServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PDFServlet</servlet-name>
<url-pattern>/PDFServlet</url-pattern>
</servlet-mapping>
PDFServlet.java
public class PDFServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException{
super.init(config);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
doPost(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("application/pdf"); // Code 1
Document document = new Document();
try{
PdfWriter.getInstance(document,
response.getOutputStream()); // Code 2
document.open();
// Code 3
PdfPTable table = new PdfPTable(2);
table.addCell("Firstname");
table.addCell(request.getParameter("firstname"));
table.addCell("Middlename");
table.addCell("4");
table.addCell("Lastname");
table.addCell("6");
table.addCell("Date of birth");
table.addCell("6");
table.addCell("Sex");
table.addCell("6");
table.addCell("Degree");
table.addCell("6");
table.addCell("Type");
table.addCell("6");
// Code 4
document.add(table);
document.close();
}catch(DocumentException e){
e.printStackTrace();
}
}}
Give name instead of id for the input tag.
<form id="carrierform" method="post" action="PDFServlet">
<div class="wrapper">
<span id="wrappspan">First Name:*</span>
<input type="text" class="input" name="firstname"/>
</div>
<div class="wrapper">
<span id="wrappspan">Middle Name:</span>
<input type="text" class="input" name="middlename" />
</div>
<div class="wrapper">
<span id="wrappspan">Last Name:*</span>
<input type="text" class="input" name="lastname" />
</div>
<div class="wrapper">
<span id="wrappspan">Date of birth:*</span>
Day<input name="spinner1"/>
Month<input name="spinner2"/>
Year<input name="spinner3"/>
</div>
<div class="wrapper" >
<span id="wrappspan">Sex:*</span>
<input type="radio" name="sex" value="Male" size="17"/>Male
<input type="radio" name="sex" value="Female" size="17"/>Female
</div>
<div class="wrapper">
<span id="wrappspan">Degree:*</span>
<select>
<option class="selectWrap" value="1">B-TECH</option>
<option class="selectWrap" value="2">M-TECH</option>
<option class="selectWrap" value="3">MS</option>
</select>
</div>
<div class="wrapper">
<span id="wrappspan">Type:</span>
<select name="class">
<option class="selectWrap" value="1">Full Time</option>
<option class="selectWrap" value="2">Part Time</option>
<option class="selectWrap" value="3">Open</option>
</select>
</div>
<div class="wrapper">
<span id="wrappspan">Resume:*</span>
<input id="filebrowse" type="file" name="datafile" size="40"/>
<input type="submit" value="upload" />
</div>
<button id="cmd" >generate PDF</button>
</form>
Related
I am working with Java ArrayList and thymeleaf. I need to use the list in thymeleaf for adding value dynamically. I don't understand how to do that?
Model
public class MedicineDTO {
private Long brandId;
private Long stockId;
private double quantity;
private double discount;
private double total;
}
public class InvoiceDTO {
private String customerName;
private String mobileNumber;
private List<MedicineDTO> medicineDTOList;
private double averageDiscount;
private double totalDiscount;
private double grandTotal;
}
Controller
#RequestMapping(value = "/pos")
public String getPOS(Model model) {
List<Brand> brandList = brandService.getAllBrands();
List<MedicineDTO> medicineDTOList = new ArrayList<>();
InvoiceDTO invoiceDTO = new InvoiceDTO();
invoiceDTO.setMedicineDTOList(medicineDTOList);
model.addAttribute("medicinedto", new MedicineDTO());
model.addAttribute("invoicedto", invoiceDTO);
model.addAttribute("brands", brandList);
return "pos";
}
#PostMapping(value="/pos/payment")
public String makePayment(InvoiceDTO invoiceDTO){
System.out.println(invoiceDTO);
service.makePayment(invoiceDTO);
return "invoice/invoice";
}
pos.html
<form id="posForm" th:action="#{/pos/payment}" th:object="${invoicedto}" method="post">
<div class="card-body">
<div class="form-group row">
<label class="col-sm-2 col-form-label" for="name">Customer Name</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="name"
th:field="*{customerName}"
placeholder="Enter Customer Name">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label" for="mobile">Mobile No</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="mobile"
th:field="*{mobileNumber}"
placeholder="Enter Mobile Number">
</div>
</div>
<div class="col-sm-4 col-md-2">
<button type="button" class="btn btn-success btn-sm add-row">
Add
</button>
<button type="reset" class="btn btn-primary btn-sm">
Reset
</button>
</div>
<table class="table" id="brand_tbl">
<thead>
<tr>
<th>Brand Name</th>
<th>Expired Date</th>
<th>Stock</th>
<th>Quantity</th>
<th>Price</th>
<th>Discount %</th>
<th>Total</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr th:object="${medicinedto}">
<td>
<select id="selectBrand1" class="form-control select2"
th:field="*{brandId}"
onchange="changeBrand(this);"
style="width: 100%;">
<option value=""> --</option>
<option th:each="brand : ${brands}"
th:value="${brand.id}"
th:utext="${brand.name}">
</select>
</td>
<td style="width:15%">
<select id="selectDate1" class="form-control select2"
onchange="changeDate(this);"
style="width: 100%;">
<option value=""> --</option>
</select>
</td>
<td style="width:10%">
<input type="number" class="form-control" id="stock1"
placeholder="" disabled>
<input type="hidden" id="stockId1" th:field="*{stockId}">
</td>
<td style="width:10%">
<input type="number" class="form-control" id="quantity1"
th:field="*{quantity}"
onchange="changeQuantity(this);"
placeholder="">
</td>
<td style="width:12%">
<input type="number" class="form-control" id="price1"
placeholder="" disabled>
</td>
<td style="width:12%">
<input type="number" class="form-control" id="discount1"
onchange="changeDiscount(this);"
placeholder="0">
<input type="hidden" id="discountAmount1" th:field="*{discount}">
</td>
<td style="width:12%">
<input type="number" class="form-control" id="total1"
th:field="*{discount}"
placeholder="" readonly>
</td>
<td>
<button type="button"
class="btn btn-block btn-danger btn-sm delete-row">
Delete
</button>
</td>
<div th:text="${invoicedto.medicineDTOList.add(medicinedto)}" th:remove="all"></div>
</tr>
</tbody>
</table>
</br>
</br>
</br>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="average_discount">
Average Discount
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="average_discount"
th:field="*{averageDiscount}"
onchange="changeAverageDiscount();">
</div>
<div class="col-sm-1">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label justify-content-end" for="total_discount">
Total Discount
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="total_discount"
th:field="*{totalDiscount}"
readonly>
</div>
<div class="col-sm-1">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="vat">
Vat
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="vat" disabled>
</div>
<div class="col-sm-1">
<input type="checkbox" id="vat_checkbox" name="vat_checkbox">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="tax">
Tax
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="tax" disabled>
</div>
<div class="col-sm-1">
<input type="checkbox" id="tax_checkbox" name="tax_checkbox">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="total_tax">
Total Tax
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="total_tax" disabled>
</div>
<div class="col-sm-1">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="grand_total">
Grand Total
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="grand_total"
th:field="*{grandTotal}"
readonly>
</div>
<div class="col-sm-1">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="paid_amount">
Paid Amount
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="paid_amount"
onchange="changePaidAmount();">
</div>
<div class="col-sm-1">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="change">
Change
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="change" disabled>
</div>
<div class="col-sm-1">
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
I am trying to add list value in thymeleaf frontend this way. I am passing two object from controller to html. And i am using <div th:text="${invoicedto.medicineDTOList.add(medicinedto)}" th:remove="all"></div> for adding medicindto object. But It passes null list to controller. Do you have any idea how i solve my problem? thanks in advance.
Thymeleaf is used to process HTML templates, add data to it, do some checks such as th:if, th:unless and also loops through an array of objects using th:each etc. But all of this is done on the server side. Once the HTML template has been delivered to the client (the browser in this case), thymeleaf is not applicable there.
So on the client side, you have to rely on HTML and JavaScript to get everything done, including preparing your data to be submitted in the form.
Based on the explanation above, you can do some more research on how to handle list on html forms. I found this solution to be appropriate for your use case, you can study it and use it.
He has used Ratings[' + rating + '][Value] in his solution, you will use something like medicineDTOList[' + index + '][brandId]. Why medicineDTOList? because in InvoiceDto which is your form's th:object, the list of MedicineDto is called medicineDTOList.
The [index] refers to the array index, which will correspond to the position of the MedicineDto in your arraylist and [brandId] correspond to the property of the MedicineDto at that index.
Upon submitting the form, java will parse the form's data into your "DTO" which is InvoiceDTO.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" type="text/css" media="all" th:href="#{/css/bootstrap.min.css}">
<title>Home</title>
</head>
<body class="p-3 mb-2 bg-light text-black">
<div class="container">
<div id="logoutDiv">
<h1 th:text="${'Welcome ' + name}">Name</h1>
<form action="#" th:action="#{/logout}"method="POST">
<button type="submit" class="btn btn-secondary float-right">Logout</button>
</form>
</div>
<div id="contentDiv" style="clear: right;">
<nav style="clear: right;">
<div class="nav nav-tabs" id="nav-tab" role="tablist">
<a class="nav-item nav-link active" id="nav-files-tab" data-toggle="tab" href="#nav-files" role="tab" aria-controls="nav-files" aria-selected="true">Files</a>
<a class="nav-item nav-link" id="nav-notes-tab" data-toggle="tab" href="#nav-notes" role="tab" aria-controls="nav-notes" aria-selected="false">Notes</a>
<a class="nav-item nav-link" id="nav-credentials-tab" data-toggle="tab" href="#nav-credentials" role="tab" aria-controls="nav-credentials" aria-selected="false">Credentials</a>
</div>
</nav>Upload<
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade show active" id="nav-files" role="tabpanel" aria-labelledby="nav-files-tab">
<p th:text="${message}" th:if="${message ne null}" class="alert alert-primary"></p>
<form action="#" enctype="multipart/form-data" th:action="#{'/file/uploadFile'}" th:method="POST" >
<div class="container">
<div class="row" style="margin: 1em;">
<div class="col-sm-2">
<label for="fileUpload">Upload a New File:</label>
</div>
<div class="col-sm-6">
<input type="file" class="form-control-file" id="fileUpload" name="fileUpload">
</div>
<div class="col-sm-4">
<button type="submit" class="btn btn-dark">/button>
</div>
</div>
</div>
</form>
<div class="table-responsive">
<table class="table table-striped" id="fileTable">
<thead>
<tr>
<th style="width: 20%" scope="col"></th>
<th style="width: 80%" scope="col">File Name</th>
</tr>
</thead>
<tbody>
<tr th:each="file : ${files}">
<td>
<a target="_blank" class="btn btn-success" th:href="#{/file/{filename}(fileName = ${file.filename})}">View</a>
<a class="btn btn-danger" th:href="#{/file/delete{filename}(filename = ${file.filename})}" >Delete</a>
</td>
<th scope="row" th:text="${file.filename}" ></th>
</tr>
</tbody>
</table>
</div>
</div>
<div class="tab-pane fade" id="nav-notes" role="tabpanel" aria-labelledby="nav-notes-tab">
<button style="margin: 0.25em;" type="button" class="btn btn-info float-right" onclick="showNoteModal()">
+ Add a New Note
</button>
<div class="table-responsive">
<table class="table table-striped" id="userTable">
<thead>
<tr>
<th style="width: 20%" scope="col"></th>
<th style="width: 20%" scope="col">Title</th>
<th style="width: 60%" scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr th:each="note : ${notes}">
<td>
<button id="edit-note" type="button" class="btn btn-success"
th:attr="data-id=${note.getNoteId},
data-title=${note.getNoteTitle},
data-description=${note.getNoteDescription}"
onclick="showNoteModal (this.getAttribute('data-id'),this.getAttribute('data-title'),this.getAttribute('data-description'))">Edit/View</button>
<a id="delete-note" class="btn btn-danger" th:href="#{/note/delete/{noteId}(noteId = ${note.getNoteId()})}">Delete</a>
</td>
<th id="notetitle" scope="row" th:text="${note.getNoteTitle()}">Example Title</th>
<td id="notedescription" th:text="${note.getNoteDescription()}">Example Description </td>
</tr>
</tbody>
</table>
</div>
<div class="modal fade" id="noteModal" tabindex="-1" role="dialog" aria-labelledby="noteModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="noteModalLabel">Note</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
-Here is the error that I get-
<form action="#" method="POST" th:action="#{/note/add}" th:object="${Notes}">
<input type="hidden" name="noteId" id="note-id">
<div class="form-group">
<label for="note-title" class="col-form-label">Title</label>
<input type="text" name= "noteTitle" class="form-control" id="note-title" maxlength="20" required th:field="*{noteTitle}">
</div>
<div class="form-group">
<label for="note-description" class="col-form-label">Description</label>
<textarea class="form-control" name="noteDescription" id="note-description" rows="5" maxlength="1000" required th:field="*{noteDescription}"></textarea>
</div>
<button id="noteSubmit" type="submit" class="d-none"></button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="$('#noteSubmit').click();">Save changes</button>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane fade" id="nav-credentials" role="tabpanel" aria-labelledby="nav-credentials-tab">
<button style="margin: 0.25em;" type="button" class="btn btn-info float-right" onclick="showCredentialModal()">
+ Add a New Credential
</button>
<div class="table-responsive">
<table class="table table-striped" th:object="${credentials}" id="credentialTable">
<thead>
<tr>
<th style="width: 20%" scope="col"></th>
<th style="width: 35%" scope="col">URL</th>
<th style="width: 20%" scope="col">Username</th>
<th style="width: 25%" scope="col">Password</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<button type="button" class="btn btn-success">Edit</button>
<a class="btn btn-danger">Delete</a>
</td>
<th scope="row">Example Credential URL</th>
<td>Example Credential Username</td>
<td>Example Credential Password</td>
</tr>
</tbody>
</table>
</div>
<div class="modal fade" id="credentialModal" tabindex="-1" role="dialog" aria-labelledby="credentialModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="credentialModalLabel">Credential</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="#" method="POST">
<input type="hidden" name="credentialId" id="credential-id">
<div class="form-group">
<label for="note-title" class="col-form-label">URL</label>
<input type="text" name= "url" class="form-control" id="credential-url" maxlength="100" required>
</div>
<div class="form-group">
<label for="note-title" class="col-form-label">Username</label>
<input type="text" name= "username" class="form-control" id="credential-username" maxlength="30" required>
</div>
<div class="form-group">
<label for="note-title" class="col-form-label">Password</label>
<input type="text" name= "password" class="form-control" id="credential-password" maxlength="30" required>
</div>
<button id="credentialSubmit" type="submit" class="d-none"></button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="$('#credentialSubmit').click();">Save changes</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script th:src="#{/js/jquery-slim.min.js}"></script>
<script th:src="#{/js/popper.min.js}"></script>
<script th:src="#{/js/bootstrap.min.js}"></script>
<!--For opening the note modal-->
<script type="text/javascript">
// For opening the note modal
function showNoteModal(noteId, noteTitle, noteDescription) {
$('#note-id').val(noteId ? noteId : '');
$('#note-title').val(noteTitle ? noteTitle : '');
$('#note-description').val(noteDescription ? noteDescription : '');
$('#noteModal').modal('show');
}
// For opening the credentials modal
function showCredentialModal(credentialId, url, username, password) {
$('#credential-id').val(credentialId ? credentialId : '');
$('#credential-url').val(url ? url : '');
$('#credential-username').val(username ? username : '');
$('#credential-password').val(password ? password : '');
$('#credentialModal').modal('show');
}
</script>
</body>
</html>
-I get an error when trying to parse the Note Form into my Note Controller. I try to parse my model object Notes in the form in my HTML home form into the Controller but it can not except the fields from the form. My first error is this:
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "home" - line 109, col 148), Line 109 is the fields from the form
I also get a second error: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'Notes' available as request attribute-
--- Note Controller ---
#Controller
#RequestMapping("note")
public class NoteController {
private NoteService noteServices;
private UserService userService;
public NoteController(NoteService noteServices, UserService userService) {
this.noteServices = noteServices;
this.userService = userService;
}
// Add an new note
#PostMapping("add")
public String addNote(#ModelAttribute(value="Notes")Notes Notes, Authentication authentication, Model model) throws IOException {
String userName = authentication.getName();
User user = userService.getUser(userName);
Integer userid = user.getId();
if(Notes.getNoteId() == null){
noteServices.addNote(Notes,userid);
}else{
noteServices.editNote(Notes);
}
return "result";
}
#GetMapping("/delete/{noteId:.+}")
public String deleteNote(#PathVariable Integer noteId, Authentication authentication, RedirectAttributes redirectAttributes){
noteServices.deleteNote(noteId);
redirectAttributes.addFlashAttribute("deleteNoteSuccess","Note deleted successfully.");
return "redirect:/result";
}
private Integer getUserId(Authentication authentication) {
String userName = authentication.getName();
User user = userService.getUser(userName);
return user.getId();
}
}
---
--- POJO Model ---
public class Notes {
private Integer noteId;
private String noteTitle;
private String noteDescription;
private Integer userId;
public Notes(String noteTitle, String noteDescription, Integer userId) {
this.noteTitle = noteTitle;
this.noteDescription = noteDescription;
this.userId = userId;
}
public Integer getNoteId() {
return noteId;
}
public void setNoteId(Integer noteId) {
this.noteId = noteId;
}
public String getNoteTitle() {
return noteTitle;
}
public void setNoteTitle(String noteTitle) {
this.noteTitle = noteTitle;
}
public String getNoteDescription() {
return noteDescription;
}
public void setNoteDescription(String noteDescription) {
this.noteDescription = noteDescription;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
}
Here I have a form that accepts package details and I have added dynamic form fields to get all the itineraries of that package. Please comment on what I must add to my question to make it more clear.
insert function
#PostMapping("/save-tour-package")
public String saveTourPackage(#ModelAttribute("tourPackage") TourPackage tourPackage, #RequestParam String[] day, #RequestParam String[] itinerary_title, #RequestParam String[] itinerary_description, #RequestParam String[] itinerary_altitude) {
// save package to database
TourPackage tour = tourPackageService.saveTourPackage(tourPackage);
for (int i = 0; i < day.length; i++) {
Itinerary ite = new Itinerary();
ite.setPackages(tour);
ite.setDay(day[i]);
ite.setTitle(itinerary_title[i]);
ite.setDescription(itinerary_description[i]);
ite.setAltitude(itinerary_altitude[i]);
itineraryRepo.save(ite);
}
return "redirect:/";
}
save service implementation
#Override
public TourPackage saveTourPackage(TourPackage tourPackage) {
return this.tourPackagesRepo.save(tourPackage);
}
view file
<div layout:fragment="content">
<div class="container">
<form th:action="#{/save-tour-package}" th:object="${tourPackage}" method="POST">
<div class="form-group">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" th:field="*{title}" placeholder="Title">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" id="description" th:field="*{description}"
placeholder="Description"></textarea>
</div>
<div class="row">
<div class="col-3">
<div class="form-group">
<label for="geography">Geography</label>
<input type="text" class="form-control" id="geography" th:field="*{geography}"
placeholder="Geography">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control" id="location" th:field="*{location}"
placeholder="Location">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="difficulty">Difficulty</label>
<input type="text" class="form-control" id="difficulty" th:field="*{difficulty}"
placeholder="Difficulty">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="altitude">Altitude</label>
<input type="text" class="form-control" id="altitude" th:field="*{altitude}"
placeholder="Altitude">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="religion">Religion</label>
<input type="text" class="form-control" id="religion" th:field="*{religion}"
placeholder="Title">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="ethnic_people">Ethnic People</label>
<input type="text" class="form-control" id="ethnic_people" th:field="*{ethnic_people}"
placeholder="Ethnic People">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="accommodation">Accommodation</label>
<input type="text" class="form-control" id="accommodation" th:field="*{accommodation}"
placeholder="Title">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="transportation">Transportation</label>
<input type="text" class="form-control" id="transportation" th:field="*{transportation}"
placeholder="Transportation">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="minimum_pax">Minimum Pax</label>
<input type="text" class="form-control" id="minimum_pax" th:field="*{minimum_pax}"
placeholder="Minimum Pax">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="price">Price</label>
<input type="text" class="form-control" id="price" th:field="*{price}" placeholder="Price">
</div>
</div>
</div>
<div class="row">
<div class="col-2">Day</div>
<div class="col-3">Title</div>
<div class="col-3">Description</div>
<div class="col-3">Altitude</div>
<div class="col-1"></div>
</div>
<div class="row delete-field append-new-field">
<div class="col-2">
<input type="text" class="form-control" name="day">
</div>
<div class="col-3">
<input type="text" class="form-control" name="itinerary_title">
</div>
<div class="col-3">
<input type="text" class="form-control" name="itinerary_description">
</div>
<div class="col-3">
<input type="text" class="form-control" name="itinerary_altitude">
</div>
<div class="col-1">
<i class="fas fa-minus-circle"></i>
</div>
</div>
Add Fields
<div class="form-group">
<button type="submit" class="btn btn-info col-2"> Save Tour Package</button>
</div>
</div>
</form>
</div>
</div>
<div layout:fragment="after-script">
<script>
function addItineraryFields() {
var html = '<div class="row delete-field"><div class="col-2">\n' +
' <input type="text" class="form-control" name="day">\n' +
' </div>\n' +
' <div class="col-3">\n' +
' <input type="text" class="form-control" name="itinerary_title">\n' +
' </div>\n' +
' <div class="col-3">\n' +
' <input type="text" class="form-control" name="itinerary_description">\n' +
' </div>\n' +
' <div class="col-3">\n' +
' <input type="text" class="form-control" name="itinerary_altitude">\n' +
' </div>' +
' <div class="col-1">\n' +
' <i class="fas fa-minus-circle"></i>\n' +
' </div></div>';
$('.append-new-field').append(html);
}
$(document).on('click', '.delete-row', function(e) {
$(this).closest('.delete-field').remove();
return false;
});
</script>
</div>
My web app is basically: jsp + angularjs, but this datepicker is running with jQuery because of the template I am using.
Before explaining what is happening, my DTO's attributes matches my entity attributes, both java.util.Date, I am just informing that I already verified the attributes type because I got many 400 bad requests because of that.
I have a modal where I have many fields, but I inserted recently two datepickers (bootstrap) and till then app is crashing, when I send the POST via ajax to my java controller, I am receiving a bad request (400), I think that it is because the format is wrong (mm/dd/yyyy). I formatted correctly the date to pt_BR for Brazil but it is not working.
BoxApp.controller("UsuariosController", function($scope, $http) {
$scope.usuarios={};
$scope.usuariosParaAlterar={};
$scope.iniciar = function() {
$http.get('/boxmlV2/usuario').success(function (response) {
$scope.usuarios = response;
});
};
$scope.iniciar();
$scope.setSelected = function(selecao){
$scope.usuariosParaAlterar = selecao;
};
/**
* Trecho para validar o form ao submeter.
*/
$scope.submitted = false;
$scope.submitForm = function(formUsuarios) {
$scope.submitted = true;
if (formUsuarios.$valid) {
$("#dataValidadeConta").datepicker({
format: 'dd/mm/yyyy',
language: 'pt-BR'
});
$("#dataValidadeSenha").datepicker({
format: 'dd/mm/yyyy',
language: 'pt-BR'
});
$scope.editaUsuario();
}
};
$scope.editaUsuario = function() {
$http.post('/boxmlV2/usuario/salvarUsuario', {
ativo : $scope.usuariosParaAlterar.ativo,
idUsuario : idUsuario.value,
nome : nome.value,
senha : senha.value,
email : email.value,
bloqueado : $scope.usuariosParaAlterar.bloqueado,
dataValidadeConta : $scope.usuariosParaAlterar.dataValidadeConta,
dataValidadeSenha : $scope.usuariosParaAlterar.dataValidadeSenha,
resetSenha : $scope.usuariosParaAlterar.resetSenha,
perfil : $scope.usuariosParaAlterar.perfil
}).then(function(response) {
$scope.sucesso();
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
$scope.sucesso = function() {
$scope.closeMyPopup();
$scope.iniciar();
};
$scope.closeMyPopup = function() {
$(myModal_autocomplete).modal('hide');
};
$scope.preparaInsercao = function() {
nome.value = "";
senha.value = "";
email.value = "";
$(idUsuario).val("");
$(idUsuario).hide();
$(idLabel).hide();
};
});
<!-- START MODAL -->
<div id="myModal_autocomplete" class="modal fade" role="dialog"
aria-hidden="true" style="display: none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true"></button>
<h4 class="modal-title">Cadastro de Usuário</h4>
</div>
<div class="modal-body form">
<form name="form" id="form_sample_2" role="form"
class="form-horizontal ng-pristine ng-valid" novalidate>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Ativo:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<div class="clearfix">
<div>
<label class="btn btn-default active"> <input
type="radio" name="ativo"
ng-model="usuariosParaAlterar.ativo" value="true">
Sim <br />
</label> <label class="btn btn-default"> <input
type="radio" name="ativo"
ng-model="usuariosParaAlterar.ativo" value="false">
Não <br />
</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Nome:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input type="text" ng-model="usuariosParaAlterar.nome"
class="form-control" id="nome" maxlength="100" name="nome"
required> <span style="color: red"
ng-show="submitted && form.nome.$error.required">Campo
Nome Obrigatório.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Senha:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input type="password" ng-model="usuariosParaAlterar.senha"
class="form-control" maxlength="100" name="senha"
placeholder="Do E-mail De Recebimento do XML" id="senha"
required> <span style="color: red"
ng-show="submitted && form.senha.$error.required">Campo
Senha Obrigatório.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">E-mail:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input type="email" ng-model="usuariosParaAlterar.email"
class="form-control" id="email" maxlength="100"
name="email" required> <span style="color: red"
ng-show="submitted && form.email.$error.required">Campo
E-mail Obrigatório.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Bloqueado:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<div class="clearfix">
<div>
<label class="btn btn-default active"> <input
type="radio" name="bloqueado"
ng-model="usuariosParaAlterar.bloqueado" value="true">
Sim <br />
</label> <label class="btn btn-default"> <input
type="radio" name="bloqueado"
ng-model="usuariosParaAlterar.bloqueado" value="false">
Não <br />
</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Data Validade Conta:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input
class="form-control form-control-inline input-medium date-picker"
name="dataValidadeConta" id="dataValidadeConta"
ng-model="usuariosParaAlterar.dataValidadeConta"
size="16" type="text" value="" required/> <span
class="help-block"> Selecione a data </span>
<span style="color: red"
ng-show="submitted && form.dataValidadeConta.$error.required">Campo
Data Validade Conta Obrigatório.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Data Validade Senha:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input
class="form-control form-control-inline input-medium date-picker"
ng-model="usuariosParaAlterar.dataValidadeSenha"
name="dataValidadeSenha" id="dataValidadeSenha"
size="16" type="text" value="" required/> <span
class="help-block"> Selecione a data </span>
<span style="color: red"
ng-show="submitted && form.dataValidadeSenha.$error.required">Campo
Data Validade Senha Obrigatório.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Resetar Senha:<span
class="required" aria-required="true"> * </span>
</label>
<div class="col-md-9">
<div class="clearfix">
<div>
<label class="btn btn-default active"> <input
type="radio" name="resetSenha"
ng-model="usuariosParaAlterar.resetSenha" value="true">
Sim <br />
</label> <label class="btn btn-default"> <input
type="radio" name="resetSenha"
ng-model="usuariosParaAlterar.resetSenha" value="false">
Não <br />
</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Perfil
Usuário:<span class="required" aria-required="true">
* </span>
</label>
<div class="col-md-9">
<div class="clearfix">
<div>
<label class="btn btn-default active"> <input
type="radio" name="perfil"
ng-model="usuariosParaAlterar.perfil" value="true">
Admin <br />
</label> <label class="btn btn-default"> <input
type="radio" name="perfil"
ng-model="usuariosParaAlterar.perfil" value="false">
Usuário <br />
</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label id="idLabel" class="control-label col-md-3">ID:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input type="text" ng-model="usuariosParaAlterar.idUsuario"
class="form-control" id="idUsuario" maxlength="100"
name="idUsuario" required disabled> <span
style="color: red"
ng-show="submitted && form.idUsuario.$error.required">Campo
ID Obrigatório.</span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary"
ng-click="submitForm(form)">
<i class="fa fa-check"></i> Salvar
</button>
</div>
</div>
</div>
</div>
<!-- END MODAL -->
Controller:
package br.com.kolss.boxml.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import br.com.kolss.boxml.dto.RetornoDTO;
import br.com.kolss.boxml.dto.UsuarioDTO;
import br.com.kolss.boxml.enums.RetornoEnum;
import br.com.kolss.boxml.service.UsuarioService;
#Controller
public class CadastroUsuariosController {
#Autowired
private UsuarioService usuarioService;
#RequestMapping(value="/usuario", method=RequestMethod.GET)
public ModelAndView iniciar(ModelMap modelMap){
return new ModelAndView("usuario");
}
#RequestMapping(value="/usuario",method=RequestMethod.GET,produces={"application/json"})
public #ResponseBody List<UsuarioDTO> obterTodos(ModelMap modelMap){
return usuarioService.obterTodos();
}
#RequestMapping(value = "/usuario/salvarUsuario", method = RequestMethod.POST, produces = { "application/json" })
public #ResponseBody RetornoDTO insereOuEditaUsuario(
#RequestBody UsuarioDTO usuarioDTO) {
usuarioService.insereOuEditaUsuario(usuarioDTO);
return new RetornoDTO(RetornoEnum.SUCESSO);
}
}
The date formatting to pt_BR only applies to how it is displayed in the datepicker control. Note that you are sending back a string mm/dd/yyyy to the server, you need to be sure that it is parsed as such at the controller.
I want to send a variable from jQuery to my Servlet. Here is my jQuery:
<script>
$('#myModal').on('show.bs.modal', function(e) {
var metrics_key = $('.createAlarm').val();
var metrics_label = $(".createAlarm option:selected").text();
// Now you have the key and label in variables.
// Write the key into the textfield.
$('#myModal input[name="name"]').val(metrics_key);
// Change the HTML of an element to the label.
$('#myModal label[for="priority"]').html(metrics_label);
var val = $('#priority').text();
console.log(val);
$.post('/sampleapp/createAlarm', { val : val},
function() { // on success
alert("Insertion successful! of "+val);
})
.fail(function() { //on failure
alert("Insertion failed." +val);
});
});
</script>
On the servlet, I am using:
String Metric = request.getParameter("val");
Please find below the HTML Code. When I select a value from dropdown and click on Create Alarm button, the bootstrap modal pops up. I want to pass all those values from the popup to my servlet. I am able to do all that except the value I am setting in jQuery.
<div class="container" style="padding-top: 60px;" >
<select class="createAlarm" id="createAlarm" name="metrics">
<option value="cpuUsage">CPU Usage</option>
<option value="memoryUsage">Memory Usage</option>
<option value="diskRead">Disk Read</option>
<option value="diskWrite">Disk Write</option>
<option value="diskUsage">Disk Usage</option>
<option value="netUsage">Net Usage</option>
</select>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" data-whatever="Create Alarm">Create Alarm</button>
</div>
<!-- Modal- Create Alarm -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Create Alarm</h4>
</div>
<form action="/CMPE283_Project2/createAlarm" method="post" id="addcard" class="form-horizontal" role="form">
<div class="modal-body" style="height: 170px;">
<div class="form-group" style="height: 30px;">
<label for="title" class="col-md-3 control-label">Name</label>
<div class="col-md-9">
<input type="text" class="form-control" name="alarmName">
</div>
</div>
<div class="form-group" style="height: 30px; margin-bottom:30px;">
<label for="title" class="col-md-3 control-label">Description</label>
<div class="col-md-9">
<textarea class="form-control" name="desc"></textarea>
</div>
</div>
<div class="form-group">
<label for="priority" id="priority" name="priority" class="col-md-3 control-label">
<input type="text" class="form-control" name="name">
</label>
<div class="col-md-9">
<div class="col-md-3">
<select name="sign" class="form-control">
<option value="lessthan"><</option>
<option value="greaterthan">></option>
<option value="lessthanequalto"><=</option>
<option value="greaterthanequalto">>=</option>
</select>
</div>
<div class="col-md-3">
<input type="text" class="form-control" name="threshold">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button class="btn btn-primary" id="formSubmit" type="submit">Create Alarm</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
But i m getting null value for the Metric. Please help. Thanks.
insead of post try to use this way
$.ajax({
url : url,
type : "post",
data : values,
success : function(data) {
if (data.errorCode == "SUCCESS") {
} else {
}
},
error : function() {
alert("failure");
}
where values is you form or JSON
otherway try {"val" : val}