Model attribute inconsistent after form submission - spring-boot

I'm still trying to figure out what's happening on the backend here. Working with Spring Boot/Thymeleaf. I have a form template that updates a model attribute object on save. I'm trying to use the updated values on the backend, however it's inconsistent among my functions and I'm not sure why.
Thymeleaf template
<div layout:fragment="content" class="container">
<form action="#" th:action="#{/utility/exportbadges}" th:object="${badgeExport}" method="post">
<div class="form-group col-md-6">
<label class="col-form-label-sm">Badge type</label>
<select th:field="*{type}" class="form-control">
<option th:each="badgeType : ${T(org.myorg.myproject.model.badge.BadgeType).values()}"
th:value="${badgeType}"
th:text="${badgeType}">
</option>
</select>
</div>
<div class="form-group col-md-3">
<label class="col-form-label-sm">Use background?</label>
<input type="checkbox" th:field="*{background}" class="form-control">
</div>
<div class="form-group col-md-3">
<label class="col-form-label-sm">Mark preprinted?</label>
<input type="checkbox" th:field="*{preprinted}" class="form-control">
</div>
<div class="form-group col-md-3">
<label class="col-form-label-sm">Save to path (/tmp default):</label>
<input type="text" th:field="*{saveDir}" class="form-control" placeholder="/tmp">
</div>
<div class="form-group col-md-12 mt-2">
<div class="col-sm-10">
<input class="btn btn-primary" id="save" type="submit" value="Export" />
<input class="btn btn-secondary" type="reset" value="Reset" />
</div>
</div>
</form>
</div>
#RequestMapping(value = "/utility/exportbadges")
public String exportBadges(Model model) {
final BadgeExport badgeExport = new BadgeExport();
model.addAttribute("badgeExport", badgeExport);
return "utility/exportbadges";
}
POST method. The object is correct in this function. Any field that's edited in the form above reflects in this function. However, on redirect, the object is as if it only has default instantiation/has been unedited.
#RequestMapping(value = "/utility/exportbadges", method = RequestMethod.POST)
public String exportBadgeFlow(Model model,
#ModelAttribute("badgeExport") final BadgeExport badgeExport) {
log.info("BadgeExport badge type: {}", badgeExport.getType());
log.info("BadgeExport save dir pre export: {}", badgeExport.getSaveDir());
switch(badgeExport.getType()) {
case "Attendee":
log.error("Attendee export not yet implemented");
break;
case "Vip":
return "redirect:exportbadges/vip-badges.pdf";
case "Specialty":
return "redirect:exportbadges/specialty-badges.pdf";
case "Staff":
return "redirect:exportbadges/staff-badges.pdf";
case "Guest":
return "redirect:exportbadges/guest-badges.pdf";
}
return "redirect:exportbadges";
}
Redirect function. Badge type will be null and saveDir will be /tmp as default instead of updated value in form.
#RequestMapping(value = "/utility/exportbadges/vip-badges.pdf")
public ResponseEntity<String> getAllVipBadgePdf(#ModelAttribute("badgeExport") final BadgeExport badgeExport) throws IOException {
log.info("BadgeExport badge type: {}", badgeExport.getType());
log.info("BadgeExport save dir during export: {}", badgeExport.getSaveDir());
}

Related

How can I do calculation based on other fields in thymeleaf?

I am working with Spring boot, Spring-data, ThymeLeaf. I have some fields. "Passenger Name", "Age", "Source", "Destination", "No of tickets", "Ticket Price", "Discount".
The following html code:
<div class="form-group has-error has-feedback" data-z="1b5278b0" id="passengerName1" data-th-classappend="${#fields.hasErrors('passengerName')}? 'has-error has-feedback'" data-th-class="form-group">
<label for="passengerName" class="col-md-3 control-label" data-th-text="#{label_ticketbooking_passengerName}">passengerName</label>
<div class="col-md-3">
<input id="passengerName" name="passengerName" data-th-value="*{{passengerName}}" type="text" class="form-control inputmask" placeholder="passengerName" data-th-placeholder="#{label_ticketbooking_passengerName}" data-toggle="tooltip" />
</div>
</div>
<div class="form-group has-error has-feedback" data-z="1b5278b0" id="age-field" data-th-classappend="${#fields.hasErrors('age')}? 'has-error has-feedback'" data-th-class="form-group">
<label for="age" class="col-md-3 control-label" data-th-text="#{label_ticketbooking_age}">age</label>
<div class="col-md-3">
<input id="age" name="age" data-th-value="*{{age}}" type="text" class="form-control inputmask" placeholder="age" data-th-placeholder="#{label_ticketbooking_age}" data-toggle="tooltip" data-inputmask-alias="numeric" data-inputmask-digits="0" min="1" />
</div>
</div>
<div class="form-group has-error has-feedback" data-z="1b5278b0" id="source1" data-th-classappend="${#fields.hasErrors('source')}? 'has-error has-feedback'" data-th-class="form-group">
<label for="source" class="col-md-3 control-label" data-th-text="#{label_ticketbooking_source}">source</label>
<div class="col-md-3">
<input id="source" name="source" data-th-value="*{{source}}" type="text" class="form-control inputmask" placeholder="source" data-th-placeholder="#{label_ticketbooking_source}" data-toggle="tooltip" />
</div>
</div>
<div class="form-group has-error has-feedback" data-z="1b5278b0" id="destination1" data-th-classappend="${#fields.hasErrors('destination')}? 'has-error has-feedback'" data-th-class="form-group">
<label for="destination" class="col-md-3 control-label" data-th-text="#{label_ticketbooking_destination}">destination</label>
<div class="col-md-3">
<input id="destination" name="destination" data-th-value="*{{destination}}" type="text" class="form-control inputmask" placeholder="destination" data-th-placeholder="#{label_ticketbooking_destination}" />
</div>
</div>
<div class="form-group has-error has-feedback" data-z="1b5278b0" id="noOfTickets-field" data-th-classappend="${#fields.hasErrors('noOfTickets')}? 'has-error has-feedback'" data-th-class="form-group">
<label for="noOfTickets" class="col-md-3 control-label" data-th-text="#{label_ticketbooking_noOfTickets}">noOfTickets</label>
<div class="col-md-3">
<input id="noOfTickets" name="noOfTickets" data-th-value="*{{noOfTickets}}" type="text" class="form-control inputmask" placeholder="noOfTickets" data-th-placeholder="#{label_ticketbooking_noOfTickets}" data-toggle="tooltip" aria-describedby="noOfTicketsStatus" data-inputmask-alias="numeric" data-inputmask-digits="0" min="1" />
</div>
</div>
<div class="form-group has-error has-feedback" data-z="ed99c550" id="ticketPrice-field" data-th-classappend="${#fields.hasErrors('ticketPrice')}? 'has-error has-feedback'" data-th-class="form-group">
<label for="ticketPrice" class="col-md-3 control-label" data-th-text="#{label_ticketbooking_ticketPrice}">ticketPrice</label>
<div class="col-md-3">
<input id="ticketPrice" name="ticketPrice" data-th-value="*{{ticketPrice}}" type="text" class="form-control inputmask" placeholder="ticketPrice" data-th-placeholder="#{label_ticketbooking_ticketPrice}" data-toggle="tooltip" />
</div>
</div>
<div class="form-group has-error has-feedback" data-z="d1a1d590" id="ticketdiscount-field" data-th-classappend="${#fields.hasErrors('ticketDiscount')}? 'has-error has-feedback'" data-th-class="form-group">
<label for="ticketDiscount" class="col-md-3 control-label" data-th-text="#{label_ticketbooking_ticketdiscount}">ticketDiscount</label>
<div class="col-md-3">
<input id="ticketDiscount" name="ticketDiscount" data-th-value="*{{ticketDiscount}}" type="text" class="form-control inputmask" placeholder="ticketDiscount" data-th-placeholder="#{label_ticketbooking_ticketdiscount}" data-toggle="tooltip" data-inputmask-alias="numeric" data-inputmask-digits="0" />
</div>
</div>
<div class="form-group has-error has-feedback" data-z="ed99c550" id="totalPrice-field" data-th-classappend="${#fields.hasErrors('totalPrice')}? 'has-error has-feedback'" data-th-class="form-group">
<label for="totalPrice" class="col-md-3 control-label" data-th-text="#{label_ticketbooking_totalPrice}">totalPrice</label>
<div class="col-md-3">
<input id="totalPrice" name="totalPrice" data-th-value="*{{totalPrice}}" type="text" class="form-control inputmask" placeholder="totalPrice" data-th-placeholder="#{label_ticketbooking_totalPrice}" data-toggle="tooltip" />
</div>
</div>
Here totalPrice should be calculated based on totalPrice = (noOfTickets * ticketPrice ) - ticketDiscount
Note: ticketDiscount may applicable or not. If applicable need to minus else no need to subtract it.
How can I achieve this?
There are several things you should take into account and several approaches you can use. Lets simplify things a little bit and suppose you have
Form DTO
#Data
public class TestDto {
private int ticketPrice;
private int noOfTickets;
private int ticketDiscount;
}
and Controller
#Controller
public class TestController {
#RequestMapping(name = "/", method = RequestMethod.GET)
public ModelAndView get() {
TestDto dto = new TestDto();
dto.setNoOfTickets(10);
dto.setTicketPrice(12);
return new ModelAndView("main", "dto", dto);
}
#RequestMapping(name = "/", method = RequestMethod.POST)
public String post(#ModelAttribute("dto") TestDto dto) {
System.out.println(dto);// can process input values
return "main";
}
}
Important. I assume you haveth:object="${dto}" in you form. If you don't, then just use dto.fieldName instead of fieldName like dto.ticketPrice instead of ticketPrice and $ instead of *
Option 1. Use Thymeleaf syntax. totalPrice will change after each form submit (POST request)
<form action="/" th:object="${dto}" method="post">
<input type="number" th:id="ticketPrice" th:field="*{ticketPrice}"/>
<input type="number" th:id="noOfTickets" th:field="*{noOfTickets}"/>
<input type="number" th:id="ticketDiscount" th:field="*{ticketDiscount}"/>
<span th:text="*{noOfTickets * ticketPrice - (ticketDiscount != 0 ? ticketDiscount: 0)}"
th:id="totalPrice"/>
<input type="submit" value="Subscribe!"/>
</form>
Option 2. Calculate value in java code POST changes to the server is also required to update the total value. Simple case can just use method with all the calculations in your DTO. This option works only if you have all the info for your calculations in this DTO
public class TestDto {
// ... same code as before
public int getTotalPrice() {
return noOfTickets * ticketPrice - (ticketDiscount != 0 ? ticketDiscount: 0);
}
}
This is easy to use just like any other field in your dto
<span th:text="*{totalPrice}"></span>
<span th:text="${dto.totalPrice}"></span>
<span th:text="*{getTotalPrice()}"></span>
If you need some extra info for your calculations, you probably can use service as suggested by #mrtasln. And for our simple case it can look like:
#Service("myService")
public class MyServices {
// Option 1
public int calculateTotal(MyDto dto){
return dto.getNoOfTickets() * dto.getTicketPrice() - (dto.getTicketDiscount() != 0 ? dto.getTicketDiscount(): 0);
}
// Option 2
public int calculateTotal2(int noOfTickets, int ticketPrice, int ticketDiscount){
return noOfTickets * ticketPrice - (ticketDiscount != 0 ? ticketDiscount: 0);
}
}
And xml part can be something like one of:
<span th:id="totalPriceFromService"
th:text="${#myService.calculateTotal(dto)}"></span>
<span th:id="totalPriceFromService2"
th:text="*{#myService.calculateTotal2(ticketPrice, noOfTickets, ticketDiscount)}"></span>
<span th:id="totalPriceFromService2"
th:with="tp=*{ticketPrice},nt=*{noOfTickets},td=*{ticketDiscount}"
th:text="${#myService.calculateTotal2(tp, nt, td)}"></span>
Option 3. The Javascript way is the only dynamic option to calculate changes. No need to perform POST to update the total value.
You can use some library to help you there, but simple case should
Define some JavaScript function like calculateTotal()
Put oninput="calculateTotal()" attribute on each input field you want to listen
Something like this:
<form action="/" th:object="${dto}" method="post">
<input type="number" th:id="ticketPrice" th:field="*{ticketPrice}" oninput="calculateTotal()"/>
<input type="number" th:id="noOfTickets" th:field="*{noOfTickets}" oninput="calculateTotal()"/>
<input type="number" th:id="ticketDiscount" th:field="*{ticketDiscount}" disabled="disabled"/>
<span th:id="totalPriceJS"></span>
<input type="submit" value="Subscribe!"/>
</form>
<script type="text/javascript">
function calculateTotal() {
var price = document.getElementById("ticketPrice").value;
var quantity = document.getElementById("noOfTickets").value;
var discount = document.getElementById("ticketDiscount").value;
var totalInput = document.getElementById("totalPriceJS");
//do all the calculations here
var total = price * quantity
if (discount) total -= discount;
totalInput.innerHTML = total
}
calculateTotal(); // don't forget to call this function on the first run
</script>
Try this calculation:
<div th: "${ticketDiscount !=null} ? result=${noOfTickets * totalPrice - ticketDiscount } : result=${noOfTickets * totalPrice}">
<span th:text="${result}"></span>
</div>
Here I am checking the value of ticketdiscount is null or not.
In Spring , you can do it with using service.Example code below :
Service class :
#Component("calculateService")
public class CalculateService {
public Integer calculateTotalPrice(Integer noOfTickets ,Integer ticketPrice, Integer ticketDiscount ){
return (noOfTickets * ticketPrice ) - ticketDiscount;
}
}
Html File :
<span th:text="${#calculateService.calculateTotalPrice(noOfTickets ,ticketPrice ,ticketDiscount)}"></span>

How tell the view an error has occured from controller? (Spring MVC)

How can I say trigger error/validation messages in the view from the controller in a better way? Currently, I do this by sending boolean attributes. For example, in creating a product, I have two possible errors. Invalid format of UPC of a product, or duplicate upc. I also have a validati
#RequestMapping("/createProduct")
public String createProduct(Model model, #RequestParam(value = "name") String name,
#RequestParam(value = "upc") String upc, #RequestParam(value = "category") String categoryName,
#RequestParam(value = "description") String description, #RequestParam(value = "price") BigDecimal price,
#RequestParam(value = "stock") int stock){
model.addAttribute("activeTab", 3);
if(Validator.invalidUpcFormat(upc)){
model.addAttribute("invalidFormat", true); //trigger for invalid format
return "management";
}
Category category = productService.getCategory(categoryName);
Product product = new Product(upc, category, name, description, price);
InventoryProduct inventoryProduct = new InventoryProduct(product, stock);
try {
managerService.add(inventoryProduct);
model.addAttribute("productCreated", true);
} catch (DuplicateProductException e) {
model.addAttribute("upc", upc);
model.addAttribute("duplicateProduct", true); // trigger for duplicate product
}
return "management";
}
And here is my view:
<div id="menu3"
class="tab-pane fade <c:if test="${activeTab == 3}">in active</c:if>">
<div class="container-fluid" style="padding: 2%;">
<div class="row">
<div class="col-md-12"
style="padding-left: 15%; padding-right: 15%;">
<c:if test="${productCreated}">
<div class="alert alert-success fade in">
<a href="#" class="close" data-dismiss="alert"
aria-label="close">×</a> <strong>Success!</strong>
Product has been created!
</div>
</c:if>
<c:if test="${duplicateProduct}">
<div class="alert alert-warning fade in">
<a href="#" class="close" data-dismiss="alert"
aria-label="close">×</a> <strong>Oh no!</strong>
Product with the UPC ${upc} already exists!
</div>
</c:if>
<c:if test="${invalidFormat}">
<div class="alert alert-warning fade in">
<a href="#" class="close" data-dismiss="alert"
aria-label="close">×</a> <strong>Oops!</strong>
Invalid UPC format!
</div>
</c:if>
<form
action="${pageContext.request.contextPath}/manager/createProduct"
method="post">
<div class="form-group">
<label for="Name">Name </label> <input type="text" name="name"
class="form-control" required />
</div>
<div class="form-group">
<label for="UPC">UPC </label> <input type="number" name="upc"
class="form-control" required />
</div>
<div class="form-group">
<div class="form-group">
<label for="category">Category</label> <select
class="form-control" name="category" required>
<option selected disabled value="">SELECT CATEGORY</option>
<c:forEach items="${categories}" var="item">
<option>${item.getName()}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" rows="5" name="description"></textarea>
</div>
<div class="form-group">
<label for="price">Price </label> <input type="number"
name="price" class="form-control" required />
</div>
<div class="form-group">
<label for="stock">Stock </label> <input type="number"
name="stock" class="form-control" required />
</div>
<button type="submit" class="btn btn-primary">Add
product</button>
</form>
</div>
</div>
</div>
</div>
Is there a better of doing this other than sending boolean triggers?
You could use Spring BindingResult. This is typical filled with the result of Binding and Validation results. But you can also add errors by hand.
But first you need to refactor your code, so that you use an single command/form-backing object instead of all the #Param values
public class CreateProductCommand {
private String name;
private String upc;
private String categoryName;
.... //other fields
public CreateProductCommand (){} //parameter less conturctor
Getter+Setter
}
Controller
#RequestMapping("/createProduct")
public ModelAndView createProduct(CreateProductCommand createProductCommand, BindingResult bindingResult) //Binding result must be the parameter direct next to the object that should been validated!!!
{
if (someustomValidationForUcpFail()) {
bindingResult.rejectValue("upc", //the field name of the invalid field
"error.Message.Key",
"Default Error Message");
}
if (bindingResult.hasErrors()) {
ModelMap model = new ModelMap();
model.add("createProductCommand", createProductCommand);
return new ModelAndView("createForm", model)
} else {
Product product = ...
return new ModelAndView("showProduct", "product", product)
}
}
jsp:
You need to use springs form and input tag:
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:springForm="http://www.springframework.org/tags/form"
version="2.0">
....
<springForm:form action="<c:url value="/manager/createProduct">" method="POST" modelAttribute="createProductCommand">
<springForm:input path="name"/> <form:errors path="name" />
<springForm:input path="ucp"/> <form:errors path="ucp" />
....
</springForm:form>
....

FormCollection parameter is empty while using #Ajax.BeginForm and html5 controls

I'm developing ASP.NET MVC5 project with boostrap, jquery, jquery UI. Submit is working fine but FormCollection in create Action is arriving empty in HomeController. I don't know what I'm doing wrong or is missing. PLease need help. Below snippet code.
Index.cshtml:
<div class="modal fade" id="modal" tabindex="-1" role="dialog">
<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">Empleado</h4>
</div>
<div class="modal-body">
#using (Ajax.BeginForm("Create", "Home", new AjaxOptions() { HttpMethod = "post" }, new { id = "dialog", name = "dialog" }))
{
<div class="panel">
<div class="panel-body">
<div class="form-group">
<label class="control-label">Nombres</label>
<input type="text" class="form-control" id="modalNombres" placeholder="Nombres" />
</div>
<div class="form-group">
<label class="control-label">Apellidos</label>
<input type="text" class="form-control" id="modalApellidos" placeholder="Apellidos" />
</div>
<div class="form-group">
<label class="control-label">Fecha de Nacimiento</label>
<input type="text" class="form-control" id="modalFechaNacimiento" placeholder="Fecha Nacimiento" />
</div>
<div class="form-group">
<label class="control-label">Tipo Documento</label>
<select class="form-control" id="modalTipoDocumento">
<option class="placeholder" selected disabled value="">--- Seleccione ---</option>
#foreach (var item in ViewBag.TiposDocumento)
{
<option value="#item.Id">#item.Descripcion</option>
}
</select>
</div>
<div class="form-group">
<label class="control-label">Número de Documento</label>
<input type="text" class="form-control" id="modalNumeroDocumento" placeholder="Número Documento" />
</div>
</div>
<div class="panel-footer">
<button type="button" role="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" role="button" class="btn btn-primary" id="btnGrabar">Grabar</button>
</div>
</div>
}
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
HomeController is:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
string nombres = collection["modalNombres"];
return RedirectToAction("Index");
}
catch
{
return View();
}
}
None of you <input> elements have name attributes so there is nothing sent to the server. Change
<input type="text" class="form-control" id="modalNombres" placeholder="Nombres" />
to
<input type="text" class="form-control" name="modalNombres" placeholder="Nombres" />
There is no need for id attributes unless you using javascript/jquery to refer to them.
However, I very strongly recommend you go to the MVC site and work through some basic tutorials and learn how to generate a view in MVC. You should have a model, use the strongly typed html helpers to bind to the properties of your model, and the POST method should have a parameter for the model so it is bound (you should never use FormCollection in MVC)
Note also, you using Ajax.BeginForm() which uses ajax to post the form values so return RedirectToAction("Index"); in your POST method is pointless. Ajax calls stay on the same page, they do not redirect.

While form submitting using ajax..getting Post not supported error ...don't know what is the error?

I am using form submission using AJAX in Spring MVC and Thymeleaf. When I try to submit it it shows
Post method is not supported
I can't figure out the mistake in my code:
<form class="form-horizontal" action="#" th:action="#{/teacher/teacherProfileUpdation}" th:object="${teacherProfileDetailsList}"
id="saveTeacherForm" method="POST" >
<br />
<div class="row">
<div class="col-lg-14 col-md-12">
<br />
<h5 style="margin-left: 15%;">Personal Details</h5>
<hr />
<div class="form-group">
<label class="col-sm-3 control-label">Name</label>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher first name" id="txtTeacherFname" th:field="*{firstName}" type="text" class="form-control" />
</div>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher middle name" id="txtTeacherMname" th:field="*{middleName}" type="text" class="form-control" />
</div>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher last name" id="txtTeacherLname" th:field="*{lastName}" type="text" class="form-control" />
</div>
</div>
</div>
<div class="col-lg-14 col-md-12">
<div class="form-actions">
<input type="hidden" id="hdnStudentByIdInSchoolAdmin" value="0" />
<input type="button" class="btn btn-info pull-right" id="btnUpdateTeacherProfile" value="Save" />
</div>
</div>
</div>
JS:
saveTeacherProfile :function(){
$("#saveTeacherForm").ajaxForm({
success : function(status) {
alert("success");
},
}).submit();
}
Controller:
#RequestMapping(value = "/updateTeacherProfile", method = RequestMethod.POST)
public String updateTeacherProfile( TeacherProfileDetails teacherProfileDetails){
System.out.println("-----------"+teacherProfileDetails.getFirstName()+"-------------");
System.out.println("-----------"+teacherProfileDetails.getLastName()+"-------------");
System.out.println("-----------"+teacherProfileDetails.getMiddleName()+"-------------");
return "success";
}
You are posting the form, but most likely your Spring controller is not configured to accept POST requests. Try this in your server-side Controller class for this page:
#RequestMapping(..., method = { RequestMethod.GET, RequestMethod.POST }, ...)
public void myControllerMethod()
{
#RequestMapping(..., method = { RequestMethod.GET, RequestMethod.POST }, ...)
public String updateTeacherProfile( TeacherProfileDetails teacherProfileDetails){
//ur Logic
}

Cannot submit a form on SpringMVC

I am fairly new to SpringMVC and have a form that can not submit to the back-end. I created the form as following and when I submit it error 404 will be returned. I changed action to /MyProject/contact but did not work.
<form class="form-horizontal" role="form" method="post"
action="/contact">
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Name
</label> <input type="text" class="form-control" id="name"
name="name" placeholder="Your name" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Email
Address</label> <input type="email" class="form-control" id="email"
name="email" placeholder="Your email" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Phone
Number</label> <input type="number" class="form-control" id="phone"
name="phone" placeholder="Phone number" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Enquiry</label>
<textarea class="form-control" rows="4" name="message"
placeholder="Please enter your enquiry"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-2 " style="float: right;">
<input id="submit" name="submit" type="submit" value="Send"
class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<! Will be used to display an alert to the user>
</div>
</div>
</form>
Controller
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
Error
HTTP Status 404 - /contact
type Status report
message /contact
description The requested resource is not available.
Its beacuse spring does not know how to pass the param Contact contact to your controller method. You need to do couple of things to make it work. Change your form to like below.
<form class="form-horizontal" role="form" method="post" modelAttribute="contact" action="/contact">
Your controller to take contact as model attribute.
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(#ModelAttribute Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
For a better understanding of what a model attribute does, there are plenty of samples and explanation online. Hope this helps.
I could solve the problem by help of minion's answer, following this tutorial and adding following link
#RequestMapping(value = "/contact", method = RequestMethod.GET)
public ModelAndView contactForm() {
System.err.println("here in GET");
return new ModelAndView("contact", "command", new Contact());
}

Resources