Error populating dropdown list from database - spring mvc - hibernate - java

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;
}
}

Related

Spring MVC wrong entity id after an attempt to update it

I try to write simple Spring MVC CRUD webapp and I got a problem updating my rows. I have a table with some users and I can edit any of them clicking "Edit" button in the table (look at the picture). Then I can change its fields in a form, but when I click "Edit" under the form, the id of user entity, that is conveyed to the addUser() method, is 0, though, when I got the entity from db, it wasn't. Also "createdDate" field becomes null. I can't find out the reason of it, so I need some help... This is my code and the picture with my app:
The picture
user.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%#page isELIgnored="false" %>
<%# page session="false" %>
<html>
<head>
<title>Users</title>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
.tg .tg-4eph{background-color:#f9f9f9}
</style>
</head>
<body>
<h1>
Add a user
</h1>
<c:url var="addAction" value="/user/add" />
<form:form action="${addAction}" commandName="user">
<table>
<c:if test="${!empty user.name}">
<tr>
<td>
<form:label path="id">
<spring:message text="ID"/>
</form:label>
</td>
<td>
<form:input path="id" readonly="true" size="8" disabled="true" />
</td>
</tr>
</c:if>
<tr>
<td>
<form:label path="name">
<spring:message text="Name"/>
</form:label>
</td>
<td>
<form:input path="name" />
</td>
</tr>
<tr>
<td>
<form:label path="age">
<spring:message text="Age"/>
</form:label>
</td>
<td>
<form:input path="age" />
</td>
</tr>
<tr>
<td>
<form:label path="isAdmin">
<spring:message text="Is admin"/>
</form:label>
</td>
<td>
<form:input path="isAdmin"/>
</td>
</tr>
<tr>
<td colspan="2">
<c:if test="${!empty user.name}">
<input type="submit"
value="<spring:message text="Edit"/>" />
</c:if>
<c:if test="${empty user.name}">
<input type="submit"
value="<spring:message text="Add"/>" />
</c:if>
</td>
</tr>
</table>
</form:form>
<br>
<h3>Users list</h3>
<table class="tg">
<tr>
<th width="80">ID</th>
<th width="120">Name</th>
<th width="120">Age</th>
<th width="60">IsAdmin</th>
<th width="120">Created date</th>
<th width="60">Edit</th>
<th width="60">Delete</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.age}</td>
<td>${user.isAdmin}</td>
<td>${user.createdDate}</td>
<td><a href="<c:url value='/edit/${user.id}' />" >Edit</a></td>
<td><a href="<c:url value='/remove/${user.id}' />" >Delete</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
UserController
package com.mihusle;
import com.mihusle.model.User;
import com.mihusle.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by MHSL on 16.06.2017.
*/
#Controller
public class UserController {
private UserService userService;
#Autowired
#Qualifier("userService")
public void setUserService(UserService userService) {
this.userService = userService;
}
#RequestMapping(value = "/users", method = RequestMethod.GET)
public String showUsersList(Model model) {
model.addAttribute("user", new User());
model.addAttribute("users", userService.getUsers());
return "user";
}
#RequestMapping(value = "/user/add", method = RequestMethod.POST)
public String addUser(#ModelAttribute("user") User user) {
if (user.getId() == 0) {
userService.addUser(user);
} else {
userService.updateUser(user);
}
return "redirect:/users";
}
#RequestMapping("/remove/{id}")
public String removeUser(#PathVariable("id") int id) {
userService.removeUser(id);
return "redirect:/users";
}
#RequestMapping("/edit/{id}")
public String editUser(#PathVariable("id") int id, Model model) {
model.addAttribute("user", userService.getUserById(id));
model.addAttribute("users", userService.getUsers());
return "user";
}
}
UserDAOImpl
package com.mihusle.dao;
import com.mihusle.model.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;
/**
* Created by MHSL on 16.06.2017.
*/
#Repository
public class UserDAOImpl implements UserDAO {
private static final Logger LOGGER = LoggerFactory.getLogger(UserDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public void addUser(User user) {
Session session = sessionFactory.getCurrentSession();
Calendar calendar = Calendar.getInstance();
Timestamp currentTime = new Timestamp(calendar.getTimeInMillis());
user.setCreatedDate(currentTime);
session.persist(user);
LOGGER.info(user + " was added successfully");
}
#Override
public void updateUser(User user) {
Session session = sessionFactory.getCurrentSession();
session.update(user);
LOGGER.info(user + " was updated successfully");
}
#SuppressWarnings("unchecked")
#Override
public List<User> getUsers() {
Session session = sessionFactory.getCurrentSession();
List<User> users = session.createQuery("FROM User").list();
users.forEach(user -> LOGGER.info(user + " is in the list"));
return users;
}
#Override
public User getUserById(int id) {
Session session = sessionFactory.getCurrentSession();
User user = session.load(User.class, id);
LOGGER.info(user + " was loaded successfully");
return user;
}
#Override
public void removeUser(int id) {
Session session = sessionFactory.getCurrentSession();
User user = session.load(User.class, id);
if (user != null)
session.delete(user);
LOGGER.info(user + " was deleted successfully");
}
}
User
package com.mihusle.model;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Objects;
/**
* Created by MHSL on 16.06.2017.
*/
#Entity
#Table(name = "user", schema = "test")
public class User {
private int id;
private String name;
private Integer age;
private Boolean isAdmin;
private Timestamp createdDate;
#Id
#Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "name", nullable = true, length = 25)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "age", nullable = true)
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#Basic
#Column(name = "isAdmin", nullable = true, columnDefinition = "BIT", length = 1)
public Boolean getIsAdmin() {
return isAdmin;
}
#Column(name = "isAdmin", columnDefinition = "BIT", length = 1)
public void setIsAdmin(Boolean admin) {
isAdmin = admin;
}
#Basic
#Column(name = "createdDate", nullable = true)
public Timestamp getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User that = (User) o;
return id == that.id &&
Objects.equals(name, that.name) &&
Objects.equals(age, that.age) &&
Objects.equals(createdDate, that.createdDate);
}
#Override
public int hashCode() {
return Objects.hash(id, name, age, createdDate);
}
#Override
public String toString() {
return "User{" +
"id = " + id +
", name = '" + name + '\'' +
", age = " + age +
", isAdmin = " + isAdmin +
", createdDate = " + createdDate +
'}';
}
}
I have no idea where the problem may be, so if you need more code, I'm ready to write it. Thanks
I solved this. I had to add <form:hidden path="id" /> to the id input field. I suppose I need to do the same with createdDate field.

how to associate checkbox with text box, so that selected checkbox and corresponding value of text box gets updated in database

I want to associate checkbox id(which is dynamically created) with text box.
For Example : If 5 check boxes are appearing along with 5 text boxes, i want that the check box i select the corresponding value will get update in database.
Problem : if 5 check boxes are appearing on jsp page and if i select 2, 4 and 5th checkboxes, then corresponding text box values i.e. 2,4 and 5th value should be inserted in database.
But in my case checkboxes are inserted correctly but values are not inserting. it is inserting like for 2nd check box ---> it is selecting first textbox,
and for 4th checkbox ----> it is selecting 2nd textbox value and for 5th checkbox it is selecting -----> 3 textbox value.
I known that it is because of this code : Here Attribute List contains three selected checkBox but attribute value contains 5 elements. and it will pick only three.
List<Object[]> inputList = new ArrayList<Object[]>();
for (int i = 0; i < qualification.getAttributeList().length; i++) {
Object[] tmp = {newCompanyId,qualification.getAttributeList()[i],qualification.getAttributeValue()[i]};
inputList.add(tmp);
Can anyone please let me know ho to solve the issue. Please find the attached pics.
Qualification Controller
#RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(ModelAndView model, HttpServletRequest req, HttpServletResponse res,
#ModelAttribute Qualification qualification, HttpSession session) throws AppException {
String userId = session.getAttribute("loggedInUserId").toString();
qualificationDAO.save(qualification, userId);
model.setViewName("qualification");
return model;
}
Qualification.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib prefix="tg" tagdir="/WEB-INF/tags"%>
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<jsp:useBean id="pagedListHolder" scope="request" class="org.springframework.beans.support.PagedListHolder" />
<!-- Main Body Section Start -->
<main class="container padContnr">
<div class="row">
<div class="col-md-12">
<h1>Qualification Rules</h1>
</div>
</div>
<div class="bg-ltgreen padding-10 margin-t-10" id="QualEdit">
<form:form class="form-horizontal" action="save" modelAttribute="qualification" method="post" >
<div class="row">
<div class="col-sm-6 col-xs-12">
<div class="form-group">
<label class="label-bg col-xs-12">Company <span class="red">*</span></label>
<div class="col-xs-12">
<form:select id="company" class="form-control" path="company">
<form:option value="Select" />
<form:options items="${companyList}" itemValue="id" itemLabel="dropdownValue"/>
</form:select>
</div>
</div>
<div class="form-group">
<label class="label-bg col-xs-12">Class <span class="red">*</span></label>
<div class="col-xs-12">
<form:select id="companyClass" class="form-control" path="companyClass" onchange="switchOption();">
<form:option value="Select" />
<form:options items="${classList}" itemValue="id" itemLabel="dropdownValue"/>
</form:select>
</div>
</div>
</div>
<div class="col-sm-6 col-xs-12">
<%-- <div class="form-group">
<label class="label-bg col-xs-12">Status <span class="red">*</span></label>
<div class="col-xs-12">
<form:select class="form-control" path="status" >
<form:option value="Select"></form:option>
<form:options items="${statusList}" itemValue="id" itemLabel="dropdownValue" />
</form:select>
</div>
</div> --%>
<div class="form-group">
<label class="label-bg col-xs-12">Rule <span class="red">*</span></label>
<div class="col-xs-12">
<form:input path="rule" class="form-control" type="text" />
</div>
</div>
</div>
</div>
<div id="QualAtt"class="row margin-t-10">
<div id="QualAtt1" class="col-md-6">
<!-- table data -->
</div>
</div>
<div class="row">
<div class="col-xs-12 margin-t-10">
<!-- <button class="btn btn-primary btnSubmit" type="submit" id="QualSav">Save</button> -->
<button type="submit" class="btn btn-primary btnSubmit"> </button>
<button class="btn btn-default btnCancel" type="button" id="QualCanl">Cancel</button>
</div>
</div>
</form:form>
</div>
</main>
Qualification Model
package com.hcl.ne.model;
import java.util.HashMap;
import java.util.Map;
/**
* #author diwakar_b
*
*/
public class Qualification {
private int id;
private String company;
private String companyClass;
private String rule;
private String lastModifiedOn;
private String lastModifiedBy;
private String status;
private String[] attributeList;
private String[] attributeValue;
private int pagesize;
private String ruleId;
private String[] attributeListNames;
private String[] attributeValueNames;
private String classId;
private String attributeId;
private String attributeName;
private String attributeValues;
public String[] getAttributeValue() {
return attributeValue;
}
public void setAttributeValue(String[] attributeValue) {
this.attributeValue = attributeValue;
}
public String getAttributeValues() {
return attributeValues;
}
public void setAttributeValues(String attributeValues) {
this.attributeValues = attributeValues;
}
public String getAttributeName() {
return attributeName;
}
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public String getAttributeId() {
return attributeId;
}
public void setAttributeId(String attributeId) {
this.attributeId = attributeId;
}
public String[] getAttributeList() {
return attributeList;
}
public void setAttributeList(String[] attributeList) {
this.attributeList = attributeList;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getCompanyClass() {
return companyClass;
}
public void setCompanyClass(String companyClass) {
this.companyClass = companyClass;
}
public String getRule() {
return rule;
}
public void setRule(String rule) {
this.rule = rule;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getLastModifiedOn() {
return lastModifiedOn;
}
public void setLastModifiedOn(String lastModifiedOn) {
this.lastModifiedOn = lastModifiedOn;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public int getPagesize() {
return pagesize;
}
public void setPagesize(int pagesize) {
this.pagesize = pagesize;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRuleId() {
return ruleId;
}
public void setRuleId(String ruleId) {
this.ruleId = ruleId;
}
public String[] getAttributeListNames() {
return attributeListNames;
}
public void setAttributeListNames(String[] attributeListNames) {
this.attributeListNames = attributeListNames;
}
public String[] getAttributeValueNames() {
return attributeValueNames;
}
public void setAttributeValueNames(String[] attributeValueNames) {
this.attributeValueNames = attributeValueNames;
}
public String getClassId() {
return classId;
}
public void setClassId(String classId) {
this.classId = classId;
}
}
PLugin.js
$('#QualSav, #QualCanl').on('click', function() {
$("#QualEdit").hide();
$("#QualRules").hide();
$("#QualSerch").show();
});
// Qualification -- Edit
$('#EditBtnQualification').on('click', function() {
var ruleId=$('table.trClick tbody tr.trActive td:first').html();
$('#ruleId').val(ruleId);
document.qualificationEditForm.submit();
});
function switchOption() {
var selectedValue= $("#companyClass").val();
$.ajax({
type: "GET",
url: "getClass",
data:'classId='+selectedValue,
success: function(data){
var tablebody = $('<tbody>');
var tablerow = "";
$(data.resultMenuForLocation).each(function(index){
tablerow = $('<tr>')
.append($('<td>').append($('<input>').attr({type :'checkbox'}).attr('class','checkBoxSize').attr({value : ''+$(this)[0].id}).attr('id','attributeList').attr('name','attributeList')))
.append($('<td>').append($(this)[0].dropdownValue+''))
.append($('<td>').append($('<input>').attr({type :'text'}).attr('class','form-control').attr('id','attributeValue').attr('name','attributeValue')))
$(tablebody).append(tablerow);
});
$('<table>')
.attr('id','master_table')
.attr('class','myAttr f-size-16')
.html('<thead><tr><th> </th><th>Attribute</th><th>Value</th></tr></thead>')
.append(tablebody)
.appendTo('div#QualAtt1');
}
});
};

insert date from jsp into database

Below code is only a part of the application.First page is Login page when submited, it will go to TimseSheet.jsp page. In Timsesheet.jsp page we need to fill the id and date and save the values to database but it is storing null values in the database table.
Please tell me how to insert date in the table.
In Jsp page:TimseSheet.jsp
<form action="TimseSheetProcess.jsp" method="post">
<td><input type="text" name="empid" required="required" /></td>
<td><input type="date" name="logindate" required="required" /></td>
<input type="submit" value="Submit">
In EmployeeBean class:
public class EmployeeBean {
private String empid;
private Date logindate;
public String getEmp_id() {
return empid;
}
public void setEmp_id(String empid) {
this.empid = empid;
}
public Date getLoginDate() {
return logindate;
}
public void setLoginDate(Date logindate) {
this.logindate = logindate;
}
}
In TimseSheetDao class:
public class TimseSheetDao {
public static int insert(EmployeeBean eb){
int status=0;
PreparedStatement ps = null;
ps=conn.prepareStatement("insert into tab values(?,?");
ps.setString(1,eb.getEmp_id());
ps.setDate(2,eb.getLoginDate());
status=ps.executeUpdate();
}
}
In TimseSheetProcess.jsp:
<%#page import="com.eis.Dao.TimseSheetDao"%>
<jsp:useBean id="obj" scope="session" class="com.eis.bean.EmployeeBean"/>
<jsp:setProperty property="*" name="obj"/>
<% out.print("You are in loop");
int status=TimseSheetDao.insert(obj);
if(status>0) {
out.print("You are successfully registered");
response.sendRedirect("timsesheet.jsp");
}
else{
out.print("Error");
}
%>
Thanks
Your are setting the id and the date at the same parameterindex "1" of the preparement statement! That's wrong ....
ps.setString(1,eb.getEmp_id());
ps.setDate(1,eb.getLoginDate());

post multiple form records in spring

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>

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