post multiple form records in spring - java

I am quite new to spring framework and I'm stuck with the following issues:
I am trying to insert multiple records on a single post request using Spring MVC 3.0
I successfully bound the List object and it is populating on JSP and when I submit the
form the request is reaching on the controller method(post) but the returned object does not contain proper values, its printing null.
My code is as follows:
form.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="f"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<f:form commandName="teamBean" method="post">
<f:input path="players[0].fname" />
<f:input path="players[0].lname" />
<f:input path="players[0].phone" />
<f:input path="players[0].email" />
<input type="submit" value="submit" />
</f:form>
</body>
</html>
DynaminFormController.java
#Controller
#RequestMapping("/form")
public class DynaminFormController {
List<Player> players = new ArrayList<>();
#RequestMapping(method = RequestMethod.GET)
public String getForm(Map<String, TeamBean> map) {
TeamBean teamBean = new TeamBean();
players.add(new Player("dd", "dd", "dd", "dd"));
players.add(new Player("cc", "cc", "cc", "cc"));
teamBean.setPlayers(players);
map.put("teamBean", teamBean);
return "form";
}
#RequestMapping(method = RequestMethod.POST)
public String postForm(TeamBean teamBean) {
System.out.println("DynaminFormController.postForm()");
System.out.println(teamBean);//printing null
return "view";
}
}
TeamBean.java
public class TeamBean {
private List<Player> players;
public List<Player> getPlayers() {
return players;
}
public void setPlayers(List<Player> players) {
this.players = players;
}
#Override
public String toString() {
return "TeamBean [players=" + players + "]";
}
}
Player.java
public class Player {
private String fname;
private String lname;
private String phone;
private String email;
public Player(String fname, String lname, String phone, String email) {
this.fname = fname;
this.lname = lname;
this.phone = phone;
this.email = email;
}
///getters setters...
#Override
public String toString() {
return "Player [fname=" + fname + ", lname=" + lname + ", phone="
+ phone + ", email=" + email + "]";
}
}

You need #ModelAttribute on you Post Method
#RequestMapping(method = RequestMethod.POST)
public String postForm(#ModelAttribute("teamBean") TeamBean teamBean) {
System.out.println("DynaminFormController.postForm()");
System.out.println(teamBean);//printing null
return "view";
}

I have resolved my issue, the problem was with spring's input tag ,i don't know why it was not working but just replace the f:input with html's input tag,though u may not get the populated values from controller but it's fine.
<f:form commandName="teamBean" method="post">
<tr>
<td><input class="dy" name="players[0].fname" /></td>
<td><input class="dy" name="players[0].lname" /></td>
<td><input class="dy" name="players[0].phone" /></td>
<td><input class="dy" name="players[0].email" /></td>
</tr>
<input type="submit" value="submit" />
</f:form>

Related

Spring bean is returning NULL in controller class

JSP 1
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Personal Info Page</title>
</head>
<body>
<center>
<h1>Personal Info Page</h1>
</center>
<center>
<form:form method="post" modelAttribute="pcbInfo"
action="/MyFirstWeb3/entrycontactinfo.do">
<table>
<tr>
<td>First Name:</td>
<td><form:input path="fName" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lName" /></td>
</tr>
<tr>
<td>Middle Name:</td>
<td><form:input path="mName" /></td>
</tr>
<tr>
<td>Gender:</td>
<td><form:radiobutton path="gender" value="M" />Male
<form:radiobutton path="gender" value="F" />Female</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Next" /></td>
</tr>
</table>
</form:form>
</center>
</body>
</html>
JSP2
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Contact Info Page</title>
</head>
<body>
<center>
<h1>Contact Info Page</h1>
</center>
<center>
<form:form method="post" modelAttribute="pcbInfo"
action="/MyFirstWeb3/entrybankinfo.do">
<table>
<tr>
<td>Address:</td>
<td><form:input path="address" /></td>
</tr>
<tr>
<td>City:</td>
<td><form:input path="city" /></td>
</tr>
<tr>
<td>State:</td>
<td><form:input path="state" /></td>
</tr>
<tr>
<td>Country:</td>
<td><form:input path="country" /></td>
</tr>
<tr>
<td>Phone:</td>
<td><form:input path="phone" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Next" /></td>
</tr>
</table>
</form:form>
</center>
</body>
</html>
JSP3
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Bank Info Page</title>
</head>
<body>
<center>
<h1>Bank Info Page</h1>
</center>
<center>
<form:form method="post" modelAttribute="pcbInfo"
action="/MyFirstWeb3/processaddpersoninfo.do">
<table>
<tr>
<td>Bank Name:</td>
<td><form:input path="bankName" /></td>
</tr>
<tr>
<td>Acc No:</td>
<td><form:input path="accNo" /></td>
</tr>
<tr>
<td>SSN:</td>
<td><form:input path="SSN" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Save" /></td>
</tr>
</table>
</form:form>
</center>
</body>
#Controller
package com.apex.mfw.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.apex.mfw.bo.BankInfoBO;
import com.apex.mfw.vo.PCBInfo;
#Controller
#SessionAttributes({"pcbInfo"})
public class AddDataController {
BankInfoBO bankInfoBO;
#RequestMapping(value = "/entrypersonalinfo.do")
public ModelAndView entryPersonalInfo() {
System.out.println("Serving the Personalinfo form");
return new ModelAndView("personalinfo","pcbInfo", new PCBInfo());
}
#RequestMapping(value = "/entrycontactinfo.do")
public ModelAndView entryContactInfo(#ModelAttribute PCBInfo pcbInfo, HttpServletRequest req) {
System.out.println("Serving the contactinfo form");
return new ModelAndView("contactinfo","pcbInfo",pcbInfo);
}
#RequestMapping(value = "/entrybankinfo.do")
public ModelAndView entryBankInfo(#ModelAttribute PCBInfo pcbInfo) {
System.out.println("Serving the bankinfo form");
System.out.println("FNAME: " + pcbInfo.getfName());
System.out.println("MNAME: " + pcbInfo.getmName());
System.out.println("LNAME: " + pcbInfo.getlName());
System.out.println("GENDER: " + pcbInfo.getGender());
return new ModelAndView("bankinfo","pcbInfo",pcbInfo);
}
#RequestMapping(value = "/processaddpersoninfo.do")
public ModelAndView addBankInfo(#ModelAttribute PCBInfo pcbInfo, Model model) {
System.out.println("AddInfoController:addBankInfo():Start");
System.out.println("FNAME: " + pcbInfo.getfName());
System.out.println("MNAME: " + pcbInfo.getmName());
System.out.println("LNAME: " + pcbInfo.getlName());
System.out.println("GENDER: " + pcbInfo.getGender());
System.out.println("\n\nAddress: " + pcbInfo.getAddress());
System.out.println("City: " + pcbInfo.getCity());
System.out.println("State: " + pcbInfo.getState());
System.out.println("Country: " + pcbInfo.getCountry());
System.out.println("Phone: " + pcbInfo.getPhone());
bankInfoBO.addBankInfo(pcbInfo);
System.out.println("AddInfoController:addBankInfo():End");
return new ModelAndView("/MyFirstWeb3/entrypersonalinfo.do");
}
public AddDataController() {
}
}
VOBean
package com.apex.mfw.vo;
public class PCBInfo {
String fName;
String lName;
String mName;
String gender;
String address;
String country;
String city;
String state;
String phone;
String bankName;
String accNo;
String SSN;
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public String getAccNo() {
return accNo;
}
public void setAccNo(String accNo) {
this.accNo = accNo;
}
public String getSSN() {
return SSN;
}
public void setSSN(String sSN) {
SSN = sSN;
}
}
Here I am trying to traverse from JSP 1 to 2 to 3 and collect the data from the 3 pages in the above ValueObject bean
but the sys.out lines all print NULL values .. I am feeling pretty beat after trying several solutions on the internet. Help me find what am I doing wrong please.

Error populating dropdown list from database - spring mvc - hibernate

I am new to java and am trying to write an application using spring-mvc and hibernate.
I am getting the error
"Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute"
in a JSP file when I try to populate a dropdown list with elements from a database
#Controller
public class MetalController {
#Autowired
MtMetalService mtMetalService;
#Autowired
MtFormulaService mtFormulaService;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView homePage() {
ModelAndView model =new ModelAndView("homepage");
return model;
}
#RequestMapping(value = "/inputmetal.html", method = RequestMethod.GET)
public ModelAndView metalInputForm() {
MtFormula mtFormula = new MtFormula();
List<MtFormula> formulalist = mtFormulaService.getAll(mtFormula);
ModelAndView model =new ModelAndView("metalinput");
model.addObject(formulalist);
for (MtFormula x: formulalist) {
System.out.println(x.getFormulaCode());
}
return model;
}
#RequestMapping(value = "/metalviewinput.html", method = RequestMethod.GET)
public ModelAndView metalViewForm() {
ModelAndView model =new ModelAndView("metalviewinput");
return model;
}
#RequestMapping(value="/createmetal.html", method = RequestMethod.POST)
public ModelAndView createMetal(#ModelAttribute("mtMetal") MtMetal mtMetal) {
mtMetalService.persist(mtMetal);
ModelAndView model =new ModelAndView("redirect:/inputmetal.html?success=true");
return model;
}
#RequestMapping(value="/viewmetal.html", method={ RequestMethod.GET, RequestMethod.POST})
public ModelAndView McMetalView(
#RequestParam("MetalCode") String metalCode) {
MtMetal mtMetal = new MtMetal();
mtMetal = mtMetalService.getOne(mtMetal, metalCode);
ModelAndView model =new ModelAndView("metalview");
model.addObject("msg", "Metal input form");
model.addObject(mtMetal);
return model;
}
#RequestMapping(value = "/metallist.html", method={ RequestMethod.GET})
public ModelAndView metalListView() {
MtMetal mtMetal = new MtMetal();
List<MtMetal> mtMetalList = mtMetalService.getAll(mtMetal);
ModelAndView model = new ModelAndView("metallistview");
model.addObject(mtMetalList);
return model;
}
}
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org ags/form"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<form:form method="post" action="/labcontrol/createmetal.html">
<c:if test="${param.success eq true}"></c:if> Metal save - Successful
<table border=1>
<tr><th>Metal details entry form</th></tr>
<tr><td>Metal Code1 </td><td> <input type=text
name="metalCode"/></td></tr>
<tr><td>Metal Description </td><td> <input type=text
name="metalDesc"/></td></tr>
<tr><td>Metal Unit of measure </td><td> <input type=text
name="metalUnit"/></td></tr>
<tr><td>Loss Formula </td><td><form:select
path="formulalist">
<form:option
value="-" label="--Please Select"/>
<form:options
items="${formulalist}" itemValue="formulaCode"
itemLabel="formula"/>
</form:select> </td></tr>
<tr><td>Treatment recovery </td><td> <input type=number
name="treatmentRecovery"/></td></tr>
<tr><td>Salable mass </td><td> <input type=number
name="saleableMass"/></td></tr>
<tr><td>Pricing unit </td><td> <input type=number
name="pricePerUnit"/></td></tr>
<tr><td>Gross value </td><td> <input type=number
name="grossValue"/></td></tr>
<tr><td><input type="submit" value="Save record"></td></tr>
</table>
</form:form>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org ags/form"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<form:form method="post" action="/labcontrol/createmetal.html">
<c:if test="${param.success eq true}"></c:if> Metal save - Successful
<table border=1>
<tr><th>Metal details entry form</th></tr>
<tr><td>Metal Code1 </td><td> <input type=text
name="metalCode"/></td></tr>
<tr><td>Metal Description </td><td> <input type=text
name="metalDesc"/></td></tr>
<tr><td>Metal Unit of measure </td><td> <input type=text
name="metalUnit"/></td></tr>
<tr><td>Loss Formula </td><td><form:select
path="formulalist">
<form:option
value="-" label="--Please Select"/>
<form:options
items="${formulalist}" itemValue="formulaCode"
itemLabel="formula"/>
</form:select> </td></tr>
<tr><td>Treatment recovery </td><td> <input type=number
name="treatmentRecovery"/></td></tr>
<tr><td>Salable mass </td><td> <input type=number
name="saleableMass"/></td></tr>
<tr><td>Pricing unit </td><td> <input type=number
name="pricePerUnit"/></td></tr>
<tr><td>Gross value </td><td> <input type=number
name="grossValue"/></td></tr>
<tr><td><input type="submit" value="Save record"></td></tr>
</table>
</form:form>}
Set the modelAttribute property on your form to the correct value.
<form:form modelAttribute="" >...
In your case it should be "mtMetal".
Always name your model attributes when adding them to your model, so that you know what to set in your form.
#Entity
public class MtMetal {
#Id
#GeneratedValue
private int metalId;
private String metalCode;
private String metalDesc;
private String metalUnit;
private double treatmentRecovery;
private double saleableMass;
private double pricePerUnit;
private double grossValue;
#OneToOne
private MtFormula lossFormula;
public MtFormula getLossFormula() {
return lossFormula;
}
public void setLossFormula(MtFormula lossFormula) {
this.lossFormula = lossFormula;
}
public double getTreatmentRecovery() {
return treatmentRecovery;
}
public void setTreatmentRecovery(double treatmentRecovery) {
this.treatmentRecovery = treatmentRecovery;
}
public double getSaleableMass() {
return saleableMass;
}
public void setSaleableMass(double saleableMass) {
this.saleableMass = saleableMass;
}
public double getPricePerUnit() {
return pricePerUnit;
}
public void setPricePerUnit(double pricePerUnit) {
this.pricePerUnit = pricePerUnit;
}
public double getGrossValue() {
return grossValue;
}
public void setGrossValue(double grossValue) {
this.grossValue = grossValue;
}
public String getMetalUnit() {
return metalUnit;
}
public void setMetalUnit(String metalUnit) {
this.metalUnit = metalUnit;
}
public int getMetalId() {
return metalId;
}
public void setMetalId(int metalId) {
this.metalId = metalId;
}
public String getMetalCode() {
return metalCode;
}
public void setMetalCode(String metalCode) {
this.metalCode = metalCode;
}
public String getMetalDesc() {
return metalDesc;
}
public void setMetalDesc(String metalDesc) {
this.metalDesc = metalDesc;
}
}
#Entity
public class MtFormula {
#Id
#GeneratedValue
private int formulaId;
private String formulaCode;
private String formulaDesc;
private double formulaRate;
public int getFormulaId() {
return formulaId;
}
public void setFormulaId(int formulaId) {
this.formulaId = formulaId;
}
public String getFormulaCode() {
return formulaCode;
}
public void setFormulaCode(String formulaCode) {
this.formulaCode = formulaCode;
}
public String getFormulaDesc() {
return formulaDesc;
}
public void setFormulaDesc(String formulaDesc) {
this.formulaDesc = formulaDesc;
}
public double getFormulaRate() {
return formulaRate;
}
public void setFormulaRate(double formulaRate) {
this.formulaRate = formulaRate;
}
}

Trying to create and save list of objects in spring mvc

This is my model class
public class DynamicRow {
private String id;
private String name;
private String email;
public DynamicRow(String id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
public DynamicRow() {
// TODO Auto-generated constructor stub
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "DynamicRow [id=" + id + ", name=" + name + ", email=" + email
+ "]";
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
This is the form class
public class DynamicRowForm {
private List<DynamicRow> dynamicRow = LazyList.decorate(new ArrayList<DynamicRow>(), FactoryUtils.instantiateFactory(DynamicRow.class));
public DynamicRowForm() {
}
public List<DynamicRow> getDynamicRow() {
return dynamicRow;
}
public void setDynamicRow(List<DynamicRow> dynamicRow) {
this.dynamicRow = dynamicRow;
}
}
Below is my controllers
#RequestMapping(value="/createDetails")
public String list(Model model){
DynamicRowForm dynamicRowForm = new DynamicRowForm();
model.addAttribute("DynamicRowForm",dynamicRowForm);
return "test2";
}
#RequestMapping(value="/save")
public String showList(Model model,#ModelAttribute("DynamicRowForm") DynamicRowForm dynamicRowForm) {
System.out.println(dynamicRowForm.getDynamicRow());
return "success";
}
And this is my jsp page named as test2
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var rowCount = 1;
function addMoreRows(form) {
rowCount ++;
var recRow = '<p id="rowCount'+rowCount+'"><tr><td><input name="" type="text" size="17%" maxlength="120" /></td><td><input name="" type="text" maxlength="120" style="margin: 4px 5px 0 5px;"/></td><td><input name="" type="text" maxlength="120" style="margin: 4px 10px 0 0px;"/></td></tr> Delete</p>';
$('#addedRows').append(recRow);
}
function removeRow(removeNum) {
$('#rowCount'+removeNum).remove();
}
</script>
</head>
<body>
<form:form action="save" method="GET" modelAttribute="DynamicRowForm">
<input type="button" onclick="addMoreRows(this.form);" value="AddRow">
<table rules="all" style="background:#fff;">
<tr>
<td style="font-size:14px;" >Name</td>
<td style="font-size:14px;">Email</td>
<td style="font-size:14px;">Mobile</td>
<!-- <td><span style="font:normal 12px agency, arial; color:blue; text-decoration:underline; cursor:pointer;" onclick="addMoreRows(this.form);">
Add More
</span>
</td> -->
</tr>
<tr id="rowId">
<td><form:input path="${dynamicRow.id}" type="" size="17%"/></td>
<td><form:input path="${dynamicRow.name}" type="text" /></td>
<td><form:input path="${dynamicRow.email}" type="text" /></td>
</table>
<div id="addedRows"></div>
<input type="submit" value="Save">
</form:form>
</body>
I know these questions have been asked before, but as am very new to spring mvc and learning things so am trying to get some comfort in this technology..
Anyway, what here I am trying to do is to save multiple row/list of object... but its not getting saved in the list... Please help me out on what is the mistake am doing, and correct me.
Edit
And one more thing I would like to clarify, in my first controller am creating a dynamicRowForm object and adding into model so that my jsp page can access it...and in my second controller am receiving DynamicRowForm object using #ModelAttribute with same name..but here am getting different object.why?
Your inputs need to look like this:
<form:form action="save" method="POST" modelAttribute="DynamicRowForm">
...
<td><form:input path="dynamicRow[0].id" type="text" /></td>
<td><form:input path="dynamicRow[0].name" type="text" /></td>
<td><form:input path="dynamicRow[0].email" type="text" /></td>
...
</form:form>
Which essentially states: on form submission bind the id field to the DynamicRow at index 0 in the form backing Object - DynamicRowForm.
If you do this, then the following should print the values input:
#RequestMapping(value="/save")
public String showList(#ModelAttribute DynamicRowForm dynamicRowForm) {
System.out.println(dynamicRowForm.getDynamicRow().get(0).getId());
System.out.println(dynamicRowForm.getDynamicRow().get(0).getName());
System.out.println(dynamicRowForm.getDynamicRow().get(0).getEmail());
return "success";
}
And one more thing I would like to clarify, in my first controller am
creating a dynamicRowForm object and adding into model so that my jsp
page can access it...and in my second controller am receiving
DynamicRowForm object using #ModelAttribute with same name..but here
am getting different object.why?
Because it is stateless. If you want to work with the same instance you will need to store it in the session between requests. See the following useful discussion.
http://www.intertech.com/Blog/understanding-spring-mvc-model-and-session-attributes/
You are missing indexing here as you are using collection. Try...
<form:input path="${DynamicRowForm.dynamicRow[0].id}" type="" size="17%"/>
and also in your addRow(), you have to use the dynamic index with row count. If it is not working with form:input, try simple html input type.
var count=0;
function addMoreRows(form) {
rowCount ++;
count =++count;
var recRow = '<p id="rowCount'+rowCount+'"><tr><td><input path="users['+count+'].id" id="users'+count+'.id" name="users['+count+'].id" type="" size="17%" maxlength="120" /></td><td><input path="users['+count+'].name" id="users'+count+'.name" name="users['+count+'].name" type="text" maxlength="120" style="margin: 4px 5px 0 5px;"/></td><td><input path="users['+count+'].email" id="users'+count+'.email" name="users['+count+'].email" type="text" maxlength="120" style="margin: 4px 10px 0 0px;"/></td></tr> Delete</p>';
$('#addedRows').append(recRow);
}

I want to add "Edit" functionality. When I click Edit, it adds a duplicate record instead of editing

This is my Operations.java, products.Java class and Products.jsp file:
In which I implemented the Add and Edit functionality. The add button is working fine but the edit button is adding a duplicate record instead of editing the record. Please tell me how do I implement edit function in my program ?
package metier;
import java.util.ArrayList;
public class Operation {
private ArrayList<Produit> produits = new ArrayList<Produit>();
public ArrayList<Produit> getProduits() {
return produits;
}
public void setProduits(ArrayList<Produit> produits) {
this.produits = produits;
}
public void add(Produit p){
produits.add(p);
}
public void remove(Long id){
for(Produit p:produits){
if(p.getId()==id){ //equals
produits.remove(p);
break;
}
}
}
public void edit(Long id){
for(Produit p:produits){
if(p.getId()==id){
p.getId();
p.getName();
p.getContactno();
p.getSPS();
produits.add(p);
break;
}
}
}
public ArrayList getAll(){
return produits;
}
}
package metier;
public class Produit {
private Long id;
private String name, address, contactNo, SparePartsService;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContactno() {
return contactNo;
}
public void setContactno(String contactNo) {
this.contactNo = contactNo;
}
public String getSPS() {
return SparePartsService;
}
public void setSPS(String SparePartsService) {
this.SparePartsService = SparePartsService;
}
public Produit() {
super();
// TODO Auto-generated constructor stub
}
public Produit(String name, String address, String contactNo, String SparePartsService) {
super();
this.name = name;
this.address = address;
this.contactNo = contactNo;
this.SparePartsService = SparePartsService;
}
public Produit(Long id, String name, String address, String contactNo, String SparePartsService) {
super();
this.id = id;
this.name = name;
this.address = address;
this.contactNo = contactNo;
this.SparePartsService = SparePartsService;
}
#Override
public String toString() {
return id + " - " + name + " - " + address + " - " + contactNo + " - " + SparePartsService + " .";
}
public void Show(){
System.out.println(toString());
}
}
<%# page import="web.ProduitBeans"%>
<%# page import="metier.Produit"%>
<%# page import="java.util.Iterator"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Getiteasy.Net</title>
</head>
<body>
<%
ProduitBeans produits;
if(request.getAttribute("modele") != null){
produits = (ProduitBeans) request.getAttribute("modele");
}else{
produits = new ProduitBeans();
}
%>
<h3>Tutorial MVC(Model, View, Controller)</h3>
<h5>Ajouter un nouveau produit</h5>
<form action="prodserv" method="post">
<table border="1" width="45%">
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address"></td>
</tr>
<tr>
<td>Contact No.</td>
<td><input type="text" name="contactNo"></td>
</tr>
<tr>
<td>Spare Parts Service(Yes/No)</td>
<td><input type="text" name="SparePartsService"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Valider"></td>
</tr>
</table>
</form>
<table border="1" width="60%">
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Contact No.</th>
<th>Spare Parts Service</th>
<th>Option</th>
</tr>
<%
Iterator<Produit> list = produits.getListe().iterator();
while(list.hasNext()){
Produit p = list.next();
%>
<tr>
<td><%=p.getId() %></td>
<td><%=p.getName() %></td>
<td><%=p.getAddress() %></td>
<td><%=p.getContactno() %></td>
<td><%=p.getSPS() %></td>
<td>
<form action="prodserv" method="post">
<input type="hidden" name="id" value="<%=p.getId() %>" >
<input type="hidden" name="action" value="supprimer" >
<input type="submit" value="supprimer"/>
</form>
<form action="prodserv" method="post">
<input type="hidden" name="id" value="<%=p.getId() %>" >
<input type="hidden" name="editaction" value="Edit" >
<input type="submit" value="Edit"/>
</form>
</td>
</tr>
<%
}
%>
</table>
What do you want your edit method to do? Look at your edit method. If you find a product with the ID you are just calling the getter methods and you are doing nothing with the data. After that you are just adding the same object again to your list. You need to define what data you want to edit and then overwrite the data with a setter method. And don't add the object again to your list.
Working with an ArrayList for this purpose is very unefficiant, you will be looping your list many many times which will take longer and longer as your list is growing. Better make use of a Map, it "maps" a key to a value so you can call that value directly by the predefined key and don't have to loop the whole list.
In your Operation class:
change the ArrayList<Produit> produits ... to Map<Long,Produit> = new HashMap<>()
(Also I would recommand you making it static, to ensure the you keep the same list across the board)
Add a private static Long idCounter=0L
Then when you Add a new Produit, do:
public void add(Produit p){
idCounter++;
p.setId(idCounter);
produits.put(idCounter,p);
}
Remove:
public void remove(Produit p){
produits.remove(p.getId());
}
Note.
No idcounter--; here because you don't know if it is the last one in your map, So baicly you will be skipping some id's if you removed alot of elements.
The id of the Produit that you want to remove has to be set on the p parameter.
Edit:
public void edit(Produit p){
produits.put(p.getId(),p);
}
Note.
The ID of the Produit that you want to remove has to be set on the p parameter.
getAll:
public Collection<Produit> getAll(){
produits.values();
}
In your JSP page:
You have to somehow tell your controller what action it has to do. You can do this by using an Action parameter.
You have done this for one case (Delete (=supprimer FR)).
<input type="hidden" name="action" value="supprimer" >
To edit you must do it again, so change:
<input type="hidden" name="editaction" value="Edit" >
to
<input type="hidden" name="action" value="Edit" >
Note. "name"-tag is the name of the parameter like number is the name of the variable Int number.
In your Controller (servlet):
your:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("action") != null) {
op.remove(Long.parseLong(req.getParameter("id")));
}
else { // Recuprer les information
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
op.add(new Produit(1L, name, address, contactNo,SparePartsService));
}
In the "else"-clause of you if-satement that checks if action-parameter is null, you only have the functionality to add a Produit.
you must add:
if(req.getParameter("action").equals("Add")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
op.add(new Produit(1L, name, address, contactNo,SparePartsService));
}else if (req.getParameter("action").equals("Edit")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
Long id = Long.ParseLong(req.getParameter("id"));
op.edit(new Produit(id, name, address, contactNo,SparePartsService));
}
Result:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("action") != null) {
op.remove(Long.parseLong(req.getParameter("id")));
}
// Recuprer les information
else if(req.getParameter("action").equals("Add")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
op.add(new Produit(1L, name, address, contactNo,SparePartsService));
}else if (req.getParameter("action").equals("Edit")){
String name = req.getParameter("name");
String address = req.getParameter("address");
String contactNo = req.getParameter("contactNo");
String SparePartsService = req.getParameter("SparePartsService");
Long id = Long.ParseLong(req.getParameter("id"));
op.edit(new Produit(id, name, address, contactNo,SparePartsService));
}
}
Note. You must add a new "else if"-clause for every possible action-parameter value that you want to implement.
I advise you to put the functionality that is within these if-clauses in a seperate private function, if not your doPost(...) function will get very long.
Or even better take a look at the Command-patern.

File Upload in Spring 3 MVC - Null Pointer Exception

I am using spring MVC 3. I have been trying to access the attributes of the uploaded file but I keep getting the following error message. I can access the other fields of the form that is posted but I can't access the uploaded file.
nullhandleForm - Failed to convert property value of type 'java.lang.String' to required type
'org.springframework.web.multipart.commons.CommonsMultipartFile' for property 'file';
nested exception is java.lang.IllegalStateException:
Cannot convert value of type [java.lang.String] to required type [org.springframework.web.multipart.commons.CommonsMultipartFile]
for property 'file': no matching editors or conversion strategy found
HTML/JSP file
<%#page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<p>${Response}</p>
<h1>Upload Songs</h1>
<table>
<form:form action="" commandName="handleForm">
<tr>
<td>Song Name :</td>
<td><form:input path="songName"/></td>
</tr>
<tr>
<td>Artist Name :</td>
<td><form:input path="artistName"/></td>
</tr>
<tr>
<td>Gendre :</td>
<td><form:input path="gendre"/></td>
</tr>
<tr>
<td>description :</td>
<td><form:textarea path="description"/></td>
</tr>
<tr>
<td>Browse File :</td>
<td><form:input type="file" path="file" /></td>
</tr>
<tr>
<td colspan="2" style="text-align: center"><input type="submit" value="submit" /></td>
</tr>
</form:form>
</table>
</body>
The form handlerclass
public class HandleForm {
private String songName;
private String artistName;
private String gendre;
private String description;
private CommonsMultipartFile file;
public CommonsMultipartFile getFile() {
return file;
}
public void setFile(CommonsMultipartFile file) {
this.file = file;
}
public String getArtistName() {
return artistName;
}
public void setArtistName(String artistName) {
this.artistName = artistName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getGendre() {
return gendre;
}
public void setGendre(String gendre) {
this.gendre = gendre;
}
public String getSongName() {
return songName;
}
public void setSongName(String songName) {
this.songName = songName;
}
}
The controller
#Controller
public class AdminController{
#RequestMapping(value = "/admin", method = RequestMethod.GET)
public String showAdmin(){
return "admin/index";
}
#RequestMapping(value = "/admin/upload-songs", method = RequestMethod.GET)
public String showContacts(Model model) {
model.addAttribute(new HandleForm());
return "/admin/upload";
}
#RequestMapping(value = "/admin/upload-songs", method = RequestMethod.POST)
public String doForm(#ModelAttribute(value = "handleForm") HandleForm handleForm, BindingResult result, Model model){
if(result.hasErrors()){
String stringList = null;
List<FieldError> errors = result.getFieldErrors();
for (FieldError error : errors ) {
stringList += error.getObjectName() + " - " + error.getDefaultMessage() + "\n";
}
model.addAttribute("Response", stringList);
//model.addAttribute("songname", handleForm.getSongName()); works fine
//model.addAttribute("filename", handleForm.getFile().getOriginalFilename()); throws an error..?
}
return "/admin/upload";
}
}
Any help would be much appreciated. Thanks in advance
do you need to add the enctype to the form declaration?
enctype="multipart/form-data"
Also make sure you have the resolver for Multipart file in your dispatcher servlet
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="100000"/>
</bean>

Categories

Resources