I have a problem with Ajax: I want to fill the form when someone insert a book's isbn, if the book already exist.
I tried this solution, but it doesn't work
Here is the form.
<form action="/Libreria_Tweb/Operation" method="post" enctype="multipart/form-data" name="operation" onsubmit="return controlla()">
<p class="submit">
<select name="tipoInfo" onchange="showDiv(this)">
<option value="addBook"> Inserisci libro </option>
<option value="alterBook"> Modifica libro </option>
</select>
</p>
<div id="alter" style="text-align: left; display: none;"> <p>
<label>Vecchio ISBN </label> <input type="text" name="oldIsbn" />
</p></div>
<p>
<label>ISBN:</label> <input type="text" name="isbn" onchange="makeRequest(this.value)"/>
</p>
<p>
<label>Titolo:</label> <input type="text" name="titolo" />
</p>
<p>
<label>Autore: </label><input type="text" name="autore" />
</p>
<p>
<label>Categoria: </label>
<select name="categoria">
<option value="musica">Musica</option>
<option value="letteratura">Letteratura</option>
<option value="cucina">Cucina</option>
<option value="informatica">Informatica</option>
</select>
</p>
<p>
<label>Prezzo:</label> <input type="text" name="prezzo" />
</p>
<p>
<label>Copertina:</label> <input type="file" name="copertina" />
</p>
<p class="submit">
<input type="submit" name="operation" value="Invia" />
<input type="reset" value="Reset" />
</p>
</form>
Here is the method makeRequest(isbn):
function makeRequest(isbn) {
var xmlHttpReq = getXMLHttpRequest();
xmlHttpReq.onreadystatechange = getReadyStateHandler(xmlHttpReq);
xmlHttpReq.open("POST", "/Operation?operation=getBook&isbn="+isbn, true);
xmlHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttpReq.send(null);
}
And here is the Servlet for take data:
Object[] arr = dbm.getElemById(request);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print(arr);
where getElemById return an array wich contains all book's data.
PS: I can't use JQuery, Json, etcetera..., only Ajax and "simple" Java.
(Sorry for my English)
Related
I'm trying to upload a file to cloudinary. I'm stucked at how to only get parts of image from the form. It keeps on throwing exception: Invalid image file. If I remove all text inputs in the form, the uploading is successful. I guess that happens because the form also has text inside. Please help me solve this. I'm really grateful for your support.
Here is my code:
Form.jsp:
<form role="form" action="<c:url value="/admin/product/update"/>" method="post" enctype="multipart/form-data">
<input name="id" value="${product.id}" hidden="">
<div class="form-group">
<label>Name:</label> <input class="form-control" value="${product.name}" name="name" />
</div>
<div class="form-group">
<label>Price:</label> <input class="form-control" value="${product.price}" type="number" name="price" />
</div>
<div class="form-group">
<label>Quantity:</label> <input class="form-control" value="${product.quantity}" type="number" name="quantity" />
</div>
<div class="form-group">
<label>Image:</label> <input class="form-control" value="${product.image}" name="image" />
</div>
<div class="form-group">
<label>Description </label> <br>
<textarea rows="4" cols="50" name="description" value="${product.description}" ></textarea>
</div>
<div class="form-group">
<label>Category</label>
<div class="checkbox">
<select name="catid">
<c:forEach items="${categorylist}" var="c">
<option value="${c.id}">${c.name}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label>image</label> <input type="file" name="image" value="${product.image }" />
</div>
Servlet.java
BeanUtils.populate(product, request.getParameterMap());
//if (catid != product.getCategory().getId()) {
// Category category = new Category();
category = dao2.getCategoryByID(catid);
product.setCategory(category);
Map result = null;
Collection<Part> fileParts = request.getParts();
for (Part part : fileParts) {
String fileName = part.getSubmittedFileName();
result = UploadImage.uploadImage(fileName, part);
String url = String.valueOf(result.get("url"));
product.setImage(url);
if (result == null) {
throw new RuntimeException("Loi upload");
}
}
dao.update(product);
The Cloudinary upload method supports uploading media files from the sources like a local path, a remote URL, a private storage URL (S3 or Google Cloud storage), a base64 data URI, or an FTP URL.
Based on your code, it seems that you are only supplying the filename of the image.
String fileName = part.getSubmittedFileName();
result = UploadImage.uploadImage(fileName, part);
You would need to update the code to input the local path of the image.
I am trying to save an image inserted by an <input> field in a form by the user to a folder named imgs under the WEB-INF folder and store in the table column of the product the path of that photo so i can later display them in a products page for my online shop.
I don't know how to send the image to the java file (using jdbc server) so i can save it and also how i can save it. I have researched online but I have not fount what i am looking for. Below is my .jsp file.
<body>
<%
if(request.getParameter("btn") != null){
String name = request.getParameter("name");
String description = request.getParameter("description");
double price = Double.valueOf( request.getParameter("price"));
String brand = request.getParameter("brand");
String type = request.getParameter("type");
int quantity = Integer.parseInt( request.getParameter("quantity"));
File picture =
Client client = Client.create();
WebResource webResource =client.resource("...link.../"+name+"/"+description+"/"+price+"/"+brand+"/"+type+"/"+quantity+"/"+picture);
ClientResponse myresponse = webResource.accept("text/plain").get(ClientResponse.class);
}
%>
<div class="p-5" >
<h1 id="title" class="d-flex justify-content-center" style="font-size:4rem;">Edit your Profile</h1>
<form class="container " method="post">
<div class="form-row">
<div class="form-group col-6">
<label for="name">Product name:</label>
<input class="form-control" type="text" name="name"><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-6">
<label for="description">Description:</label>
<textarea class="form-control" name="description" cols="40" rows="5"></textarea><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-3">
<label for="price">Price:</label>
<input class="form-control" type="number" name="price"><br>
</div >
<div class="form-group col-6">
<label for="brand">Product brand:</label>
<input class="form-control" type="text" name="brand"><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-6">
<label for="type">Product type(running, walking, casual ,etc...):</label>
<input class="form-control" type="text" name="type"><br>
</div >
<div class="form-group col-6">
<label for="quantity">Available quantity:</label>
<input class="form-control" type="text" name="quantity"><br>
</div >
</div>
<div class="form-row">
<div class="form-group col-6">
<label for="picture">Product picture:</label>
<input class="form-control" type="file" name="picture"><br>
</div >
</div>
<button type="submit" name="btn">Sign in</button>
</form>
</div>
</body>
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.
I have this page where a teacher can invite a student to the platform. This works just fine, but now I would like to implement multiple invites on the same page. In short, there now is a form with the possibility to invite 1 student at a time, but I would like to expand this to 5 students in one post method.
This is the page to invite 1 student:
<div class="container">
<div class="wrapper">
<form class="form-activate" th:action="#{/invite}" method="post" th:object="${user}">
<h2 class="form-activate-heading" th:text="#{invite.title}">Nodig een student uit</h2>
<p th:text="#{invite.email}">Vul hier het e-mailadres in van de student die je wil uitnodigen:</p>
<div class="form-group">
<input type="text" name="email" id="email" class="form-control input-lg" data-validation="email"
placeholder="Email" tabindex="2" th:attr="placeholder=#{general.email}"/>
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<input type="submit" class="btn btn-secondary" value="Invite" th:attr="value=#{invite.enter}"/>
</div>
</div>
</form>
</div>
Now I tried modifying this page for 2 users:
<div class="container">
<div class="wrapper">
<form class="form-activate" th:action="#{/invite}" method="post">
<h2 class="form-activate-heading" th:text="#{invite.title}">Nodig een student uit</h2>
<p th:text="#{invite.email}">Vul hier het e-mailadres in van de student die je wil uitnodigen:</p>
<div class="form-group" th:object="${user}">
<input type="text" name="email" th:field="*{email}" class="form-control input-lg" data-validation="email"
placeholder="Email" tabindex="2" th:attr="placeholder=#{general.email}"/>
</div>
<div class="form-group" th:object="${user}">
<input type="text" name="email" th:field="*{email}" class="form-control input-lg" data-validation="email"
placeholder="Email" tabindex="2" th:attr="placeholder=#{general.email}"/>
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<input type="submit" class="btn btn-secondary" value="Invite" th:attr="value=#{invite.enter}"/>
</div>
</div>
</form>
</div>
Then in my post method I tried to do it like this:
#RequestMapping(value="/invite", method = RequestMethod.POST)
public ModelAndView SendInvite(ModelAndView modelAndView, #ModelAttribute User user1, #ModelAttribute User user2, BindingResult bindingResult, RedirectAttributes redirectAttributes, HttpServletRequest request){
List<User> students = new ArrayList<>();
students.add(user1);
students.add(user2);
for (User user : students) {
But the page is not even loading anymore, here is my get method:
#RequestMapping(value="/invite", method = RequestMethod.GET)
public ModelAndView showInvitePage(ModelAndView modelAndView, #ModelAttribute User user){
return modelAndView;
}
Which gives me the following error:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor' (teacher/invite:20)] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute
at org.springframework.web.servlet.support.BindStatus.(BindStatus.java:144)
Is it even possible what I'm trying to do ?
EDIT: I'm trying to implement to solution Aleksandrs has given me, but Spring throws an error:
#RequestMapping(value="/invite", method = RequestMethod.GET)
public ModelAndView showInvitePage(ModelAndView modelAndView){
List<String> emailList = new ArrayList<>();
modelAndView.addObject(emailList);
return modelAndView;
}
#RequestMapping(value="/invite", method = RequestMethod.POST)
public ModelAndView SendInvite(ModelAndView modelAndView, List<String> emailList){
System.out.println(emailList.get(0));
Eventhough I have instantiated the emailList in the Get method, I get the following error:
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.util.List]: Specified class is an interface] with root cause
org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.util.List]: Specified class is an interface
EDIT2:
Finally got it working, thanks to Aleksandrs for the help! Solution:
#RequestMapping(value="/teacher/invite", method = RequestMethod.GET)
public ModelAndView showInvitePage(ModelAndView modelAndView){
logger.info("Entered showInvitePage function");
List<String> email = new ArrayList<>();
modelAndView.addObject("email", email);
return modelAndView;
}
#RequestMapping(value="/invite", method = RequestMethod.POST)
public ModelAndView SendInvite(ModelAndView modelAndView, #AuthenticationPrincipal User currentUser, #RequestParam List<String> email){
email.forEach(address -> {
// send the invites
});
And the invite page:
<form class="form-activate" th:action="#{/invite}" method="post" >
<p th:text="#{invite.email}">Vul hier het e-mailadres in van de student die je wil uitnodigen:</p>
</div>
<div class="form-group">
<input type="text" name="email" id="email" class="form-control input-lg" data-validation="email"
placeholder="Email" tabindex="2" th:attr="placeholder=#{general.email}"/>
</div>
<div class="form-group">
<input type="text" name="email" id="email2" class="form-control input-lg" data-validation="email"
placeholder="Email" tabindex="2" th:attr="placeholder=#{general.email}"/>
</div>
<div class="form-group">
<input type="text" name="email" id="email3" class="form-control input-lg" data-validation="email"
placeholder="Email" tabindex="2" th:attr="placeholder=#{general.email}"/>
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<input type="submit" class="btn btn-secondary" value="Invite" th:attr="value=#{invite.enter}"/>
</div>
</div>
</form>
As Pandian said the "user" binded twice but in this case you can use simple array to pass list of String into controller. Because the actual user must have many fields which isn't present in your template. So can recoment use something like this in template:
<form class="form-activate" th:action="#{/invite}" method="post">
<h2 class="form-activate-heading" th:text="#{invite.title}">Nodig een student uit</h2>
<p th:text="#{invite.email}">Vul hier het e-mailadres in van de student die je wil uitnodigen:</p>
<div class="form-group">
<input type="text" name="email[]" class="form-control input-lg" data-validation="email"
placeholder="Email" tabindex="2" th:attr="placeholder=#{general.email}"/>
</div>
<div class="form-group">
<input type="text" name="email[]" class="form-control input-lg" data-validation="email"
placeholder="Email" tabindex="2" th:attr="placeholder=#{general.email}"/>
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<input type="submit" class="btn btn-secondary" value="Invite"
th:attr="value=#{invite.enter}"/>
</div>
</div>
</form>
And in the controller:
#RequestMapping(value = "/invite", method = RequestMethod.POST)
public ModelAndView SendInvite(List<String> emailAddressList) {
// some stuff here
}
EDIT:
So, I'm not sure that my JavaScript code works but in your case HTML must be likethis:
<form class="form-activate" th:action="#{/invite}" method="post" id="myForm">
<h2 class="form-activate-heading" th:text="#{invite.title}">Nodig een student uit</h2>
<p th:text="#{invite.email}">Vul hier het e-mailadres in van de student die je wil uitnodigen:</p>
<div class="form-group">
<input type="text" name="email[]" id="email" class="form-control input-lg" data-validation="email"
placeholder="Email" tabindex="2" th:attr="placeholder=#{general.email}"/>
<span style="cursor: pointer;"
onclick="myForm.innerHTML = myForm.innerHTML + '' + this.parentNode.cloneNode(true);">+</span>
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<input type="submit" class="btn btn-secondary" value="Invite"
th:attr="value=#{invite.enter}"/>
</div>
</div>
</form>
And in controller I'll try to do like that:
#RequestMapping(value = "/invite", method = RequestMethod.POST)
public ModelAndView SendInvite(ModelAndView modelAndView, #RequestParam List<String> email) {
email.stream()
.forEach(address -> {
User u = userService.findByEmail(address);
if (u == null) {
// send email here for current user;
}
});
// some other stuff
}
I can try to run it on my pc if you can tell me some test password.
Issues : same model "user" binded twice on same element with name "email"
Below Code working fine for me
<form action="#" th:action="#{/accessSite}" method="post">
<div th:object="${userVO}">
<table>
<tr>
<td>Name:</td>
<td><input type="text" th:field="*{name}" /></td>
<td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name
Error</td>
</tr>
</table>
</div>
<div th:object="${employeeVO}">
<table>
<tr>
<td>Name:</td>
<td><input type="text" th:field="*{empname}" /></td>
<td th:if="${#fields.hasErrors('empname')}" th:errors="*{empname}">Name
Error</td>
</tr>
</table>
</div>
Submit
#RequestMapping("/accessSite")
public String accessSite( UserVO userVO, EmployeeVO employeeVO,BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "form";
}
return "result";
}
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>