I have a .jsp page which is generated using my "menuModel", Now after visualising this page, the user inserts his/her name and clicks on the Confirm My Order button.
By clicking on this button I want to copy the data of this menuModel to another model named "ordersModel". Due to the fact that this ordersModel is not instantiated, I don't know how to copy the data of menuModel into ordersModel.
<form:form id="myOrderMenuId" action="${pageContext.request.contextPath}/OrderSent" method="post" commandName="ordersModel" >
<c:forEach items="#{menuModel.foodList}" var="foodModel" varStatus="status">
<c:if test="${foodModel.quantity != 0}">
<!-- <form:hidden value='${foodModel.foodName}' path='orders[${status.index}].foodName'/>
<form:hidden value='${foodModel.quantity}' path='orders[${status.index}].quantity'/> -->
<div>
<table class="itemList">
<tr>
<td style="width: 170px">
<span id="foodNameId${foodModel.foodId}"><c:out value="${foodModel.foodName}"/></span>
</td>
<td>
<span id="quantityId${foodModel.foodId}" style="margin-left: 110px;"><c:out value="${foodModel.quantity}"/></span>
</td>
<td>
<span id="priceId${foodModel.foodId}" style="margin-left: 110px;"><c:out value="${foodModel.price}"/></span>
<span> €</span>
</td>
<td>
<span class="eachPrice" id="totalPriceId${foodModel.foodId}" style="margin-left: 110px;"><c:out value="${foodModel.totalPrice}"/></span>
<span> €</span>
</td>
</tr>
</table>
</div>
</c:if>
</c:forEach>
<span class="itemList" style="color: #80FF00; margin-left: -300px">Total:</span>
<span id="totalPayment" class="itemList" style="color: #80FF00; margin-left: 5px"></span>
<span class="itemList" style="color: #80FF00;"> €</span><br/>
<div class="itemList" style="margin-left:-1130px">Your Name: <input path="ownerName" name="orderName" class="myInbox" id="orderName"/></div>
<button id="viewMyOrder" class="greyButton" style="position:relative; left: -530px">Confirm My Order</button>
</form:form>
And this is my OrdersModel:
public class OrdersModel {
private String ownerName;
private List<Order> orders;
//getters and setters
}
How is it possible to copy the data into the ordersModel, as I commented in the code.
UPDATE
My Controller looks like this:
#RequestMapping(value = "/myOrder", method = RequestMethod.POST)
public String viewMyOrder(Model model,
#ModelAttribute("menuModel")MenuModel menuModel) {
logger.info("You are in view my order page.");
List<FoodModel> foodModelList = new ArrayList<FoodModel>();
for (FoodModel foodModel : menuModel.getFoodList()) {
FoodModel foodModelNew = new FoodModel();
if (foodModel.getQuantity()!=0){
foodModelNew.setFoodId(foodModel.getFoodId());
foodModelNew.setFoodName(foodModel.getFoodName());
foodModelNew.setQuantity(foodModel.getQuantity());
foodModelNew.setPrice(foodModel.getPrice());
foodModelNew.setTotalPrice(foodModel.getQuantity() * foodModel.getPrice());
}
foodModelList.add(foodModelNew);
}
menuModel.setFoodList(foodModelList);
return "myOrder";
}
#RequestMapping(value = "/OrderSent", method = RequestMethod.POST)
public String orderSent(#ModelAttribute("ordersModel")OrdersModel ordersModel,
#RequestParam("orderName") String owner, Model model) {
logger.debug("Your order has been received");
model.addAttribute("owner", owner);
return "orderSent";
}
}
Why don't you just populate OrdersModel.orders with the FoodModels in the controller and then render the JSP?
<form:form id="myOrderMenuId" action="${pageContext.request.contextPath}/OrderSent" method="post" commandName="ordersModel" >
<c:forEach items="#{ordersModel.order}" var="foodModel" varStatus="status">
...
Controller:
#RequestMapping(value = "/myOrder", method = RequestMethod.POST)
public String viewMyOrder(Model model, #ModelAttribute("menuModel")MenuModel menuModel) {
logger.info("You are in view my order page.");
OrdersModel ordersModel = new OrdersModel()
List<FoodModel> foodModelList = new ArrayList<FoodModel>();
for (FoodModel foodModel : menuModel.getFoodList()) {
Order foodModelNew = new Order();
if (foodModel.getQuantity()!=0){
foodModelNew.setFoodId(foodModel.getFoodId());
foodModelNew.setFoodName(foodModel.getFoodName());
foodModelNew.setQuantity(foodModel.getQuantity());
foodModelNew.setPrice(foodModel.getPrice());
foodModelNew.setTotalPrice(foodModel.getQuantity() * foodModel.getPrice());
}
ordersModel.add(foodModelNew);
}
model.addAttribute("ordersModel", ordersModel);
return "myOrder";
}
Related
I am using ExcelReader to upload new sheet of containing data and get all old data from the DbSet.I am using Entity Framework POCO way to POST/GET data. I want to use same view for both POST/GET.I have two submit button one for saving current data and one for get all data from datacontext.Now my View Code is below I followed the steps included here!
I getting following error "System.Reflection.AmbiguousMatchException". I am guessing this because of HTNL.Beginfrom() creating it because of action result name.
Can any one help me how to resolve this issue if I need to use #Html.AntiForgeryToken();
#Html.ValidationSummary(); in my both the GET/POST call.
[MultipleButton(Name = "action", Argument = "Index")]
public ActionResult Index(HttpPostedFileBase uploadfile,dataViewModel dataView1)
{
// code for upload
}
[MultipleButton(Name = "action", Argument = "ExcelData")]
public ActionResult ExcelData()
{
ReadContext Context = new ReadContext();
return View(Context.dataext.ToList());
}
My View code:
#{
ViewBag.Title = "Read Excel File and Display in mvc5";
}
#model System.Data.DataTable
#using System.Data
<h2>Read Excel File and Display in mvc5</h2>
#using (Html.BeginForm("Index", "ReadExcel", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken();
#Html.ValidationSummary();
<label class="text-info">Upload Excel File</label>
<input type="file" class="form-control" name="uploadfile" id="uploadfile" />
<input type="submit" value="submit" class="btn btn-default" name="action:Index" />
<input type="submit" value="data" class="btn btn-default" name="action:ExcelData" />
if (Model != null)
{
<table class="table table-responsive table-bordered">
<thead>
<tr>
#foreach(DataColumn column in Model.Columns)
{
<th>#column.ColumnName</th>
}
</tr>
</thead>
<tbody>
#foreach(DataRow row in Model.Rows)
{
<tr>
#foreach(DataColumn col in Model.Columns)
{
<td>#row[col.ColumnName]</td>
}
</tr>
}
</tbody>
</table>
}
}
As the title describes, using thymeleaf I display the contents of a list and then I put "Update" buttons next to each item on the list that send the particular object to an editing form page.
Here is the controller method for adding the list to the list view:
#RequestMapping("/list")
public String list(Model model){
List<Employee> employees = repository.findAll();
model.addAttribute("employees", employees);
return "list";
}
And here is the thymeleaf html code:
<tr th:each="emp : ${employees}">
<td th:text="${emp.id}"></td>
<td th:text="${emp.name}"></td>
<td th:text="${emp.surname}"></td>
<td th:text="${emp.age}"></td>
<td th:text="${emp.department}"></td>
<td>
<form th:action="#{/update}" method = "POST" th:object="${emp}">
<input type="hidden" th:field="*{id}"></input>
<input type="hidden" th:field="*{name}" ></input>
<input type="hidden" th:field="*{surname}"></input>
<input type="hidden" th:field="*{age}"></input>
<input type="hidden" th:field="*{department}"></input>
<button type = "submit">Update</button>
</form>
</td>
</tr>
And here is the receiving method:
#RequestMapping("/update")
public String update(#ModelAttribute("emp") Employee emp){
return "update";
}
I keep getting the following exception:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'emp' available as request attribute
Please let me know if you have any ideas on accomplishing this task.
This could be help.Change your controller like this.Its work for me.
model.addAttribute("emp", new Employee());
#RequestMapping("/list")
public String list(Model model){
List<Employee> employees = repository.findAll();
model.addAttribute("emp", new Employee());
model.addAttribute("employees", employees);
return "list";
}
I have a form ,when I am using spring form tags with the path attribute,I get the following error
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'selectedPerson' available as request attribute
However when I use the regular HTML input with the name attribute I don't see any issues.
What am I doing wrong.
Here is the controller code
#RequestMapping(value="/savePersonChanges.htm",method=RequestMethod.POST)
public ModelAndView savePersonChanges(HttpSession session,#Valid #ModelAttribute(value="selectedPerson")PersonBean editedPersonBean,BindingResult bindingResult){
ModelAndView mav=new ModelAndView();
mav.setViewName(LANDING_PAGE;
mav.addObject(TAB_SELECTOR,"EditPerson");
if(session!=null){
Rpt_date=(java.util.Date)session.getAttribute("editDate");
}
if(bindingResult.hasErrors()){
mav.addObject("errorDescription",errorDescription );
}
else{
/* Call service that updates database with table changes */
try{
PersonService.updatePerson(Rpt_date, editedPersonBean
}
catch(Exception e){
log.logError("Exception while updating Person", e.toString());
}
}
return mav;
}
The form is as follows:
<form:form modelAttribute="selectedPerson" id="editPersonForm">
<table id="selectPerson">
<tbody>
<tr>
<td>
<select id="personId" name="personId" onchange="getPersonDetails(this)">
<c:choose>
<c:when test="${empty selectedPerson}">
<option value="0" selected ="selected">Select A Person</option>
<c:forEach var="personIdItem" items="${editPersonProperties.personproperties}">
<option value="${personIdItem.personId}"><spring:escapeBody>${personIdItem.personName}</spring:escapeBody></option>
</c:forEach>
</c:when>
<c:otherwise>
<c:forEach var="personIdItem" items="${editPersonProperties.personproperties}">
<c:if test="${personIdItem.personId eq selectedPerson.personId}">
<option value="${personIdItem.personId}" selected ="selected">${personIdItem.personName}</option>
</c:if>
<c:if test="${personIdItem.personId ne selectedPerson}">
<option value="${personIdItem.personId}"><spring:escapeBody>${personIdItem.personName}</spring:escapeBody></option>
</c:if>
</c:forEach>
</c:otherwise>
</c:choose>
</select>
</td>
</tr>
</tbody>
</table>
<!-- Person Details -->
<table id="editPersonTable">
<tr>
<td>First Name</td>
<td> <form:input type ="text" path="fname" value="${selectedPerson.fname}"></form:input></td>
<td>Last Name</td>
<td> <form:input type ="text" path="lname" value="${selectedPerson.lname}"/></td>
</tr>
</table>
<div class="editcancelstyle">
<input id="savebtn" type="button" onclick="savePerson()" value="Save" />
<input id="cancelbtn" type="button" onclick="cancelPersonEdits ()"value="Cancel" />
</div>
</form:form>
I understand that the path attribute will bind the field to the form. However, I keep getting the bind error. If I replace using plain HTML, the controller sees the edited values for the fname and lname for the SelectedPerson bean.
Here is your problem, when you do :
<form:... modelAttribute="selectedPerson" ...>, the selectedPerson is the key of model object mapped from the holder of both Model & View class ( ex : ModelAndView), suppose you bind a model in your controller with new ModelAndView ("yourForm", "selectedPerson", new Person()),
#RequestMapping(value = "/form")
public ModelAndView userInput() {
ModelAndView mv = new ModelAndView("personForm", "selectedPerson", new Person());
return mv;
}
now the Person is mapped with selectedPerson so when this form returned as the response from controller, your form has already been bound to the Person model, so that you use path to refer to this Person's attributes (ex. path="name" , means it refers to Person's name attribute)
In your form, on modelAttribute="selectedPerson", the selectedPerson is not binded to any models, since "selectedPerson" is never assigned to any object because you didn't do any binding first before processing ( submitting ) the form.
this is why you got
> java.lang.IllegalStateException: Neither BindingResult nor plain
> target object for bean name 'selectedPerson' available as request
> attribute.
Note that to get this binding works, add also the following on the top of your form
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
you can then populate the fields of the form (assuming you put action="result.html"):
#RequestMapping(value = "/result")
public ModelAndView processUser( #ModelAttribute("selectedPerson") Person person, BindingResult result) {
if (result.hasErrors()) {
return new ModelAndView("errorPage","message","Something goes wrong");
}
/*System.out.println(person.getName());*/
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("personResult");
modelAndView.addObject("person", person);
return modelAndView;
}
#{
ViewBag.Title = "Country";
}
<fieldset>
<legend>List countries</legend>
<div class="row">
<div class="col-md-8">
<h5>
#Html.ActionLink("New Country", "Create", "Country")
</h5>
<table class="table table-bordered">
#foreach (var c in ViewBag.Countries)//NullReference Exceptio
{
<tr>
<td>#c.CountryName</td>
<td>
<span class="glyphicon glyphicon-edit"></span>
<span class="glyphicon glyphicon-remove"></span>
</td>
</tr>
}
</table>
</div>
</div>
</fieldset>
What can be used to handle this ?
There are Already 7 To 8 CountryNames in database.But And I have already used nullable variable in program ,How to handle this exception?
// Below is the index method of Country Controller
public class CountryController : Controller
{
private MyProjectDbEntities db = new MyProjectDbEntities();
// GET: Country
public ActionResult Index()
{
ViewBag.Message = db.Countries.ToList();
return View();
}
ViewBag.Message = db.Countries.ToList();
You are referencing to this as ViewBag.Countries in your view.
In Spring MVC, I have a search form. If user submit search form, result should show in same page.
It is redirecting to same page But I'm not getting attributes in JSP from controller.
qSearch.jsp
<form:form name="quickSearchForm" id="searchFormId" method="POST" action="./searchQuick.html" modelAttribute="searchForm" onsubmit="return validateForm()">
<table>
<tr>
<th>Change/Defect ID</th><td><form:input type="text" name="identifier" path="identifier"/></td>
</tr>
</table>
<div class="icons">
<span><button style="left:0px" type="reset" name="clear" style="border-radius: 25px;">CLEAR</button></span>
<span><button style="right:0px" type="submit" name="submit" style="border-radius: 25px;" >SEARCH</button></span>
</div>
</form:form>
<hr>
<div>
<c:if test="${empty SEARCH_RESULTS_KEY}">
<table style="border-collapse: collapse;" border="1" class="showResults">
<tr>
<td colspan="7">No Results found</td>
</tr>
</table>
</c:if>
<c:if test="${! empty SEARCH_RESULTS_KEY}">
<table style="border-collapse: collapse;" border="1" class="showResults">
<tr>
<td colspan="7">Result found</td>
</tr>
</table>
</c:if>
Controller
#RequestMapping(value="/qSearch", method = RequestMethod.GET)
public String getQuickSearchmodel(Model model) {
System.out.println("Welcome to search tool\n");
ArchivalIssue archivalIssue=new ArchivalIssue();
model.addAttribute("searchForm", archivalIssue);
return "quickSearchPage";
}
#RequestMapping(value = "/searchQuick", method = RequestMethod.POST)
public ModelAndView getAllArchivalIssues(HttpServletRequest request){
String identifier = request.getParameter("identifier");
List<ArchivalIssue> archivalIssue = archivalIssueService.getAllArchivalIssue(identifier);
ModelAndView mav = new ModelAndView("redirect:/qSearch"); //Add model to display results
mav.addObject("SEARCH_RESULTS_KEY", archivalIssue); //Add result object to model
return mav;
}
please someone help me, how to get result in JSP. I'm always getting no result found.
I think you should not redirect in this case. Because redirect will create new GET request to server. The quickSearchPage and getAllArchivalIssues should return same view
#RequestMapping(value = "/searchQuick", method = RequestMethod.POST)
public ModelAndView getAllArchivalIssues(HttpServletRequest request){
String identifier = request.getParameter("identifier");
List<ArchivalIssue> archivalIssue = archivalIssueService.getAllArchivalIssue(identifier);
//return quickSearchPage, so that the client can render the list archivalIssue
ModelAndView mav = new ModelAndView("quickSearchPage");
mav.addObject("SEARCH_RESULTS_KEY", archivalIssue); //Add result object to model
return mav;
}
When the return value contains redirect: prefix, The rest of the view name will be treated as the redirect URL. And the browser will send a new request to this redirect URL. So the handler method mapped to this URL will be executed.
just return the same page as response with model attributes.
Are you using JSTL is there any changes required
${empty param.SEARCH_RESULTS_KEY}