I am having a loop on my JSP page and want to pass these values in my Spring Controller. On every click on Retry button in JSP, I need all values in my controller for further processing. The code which I tried so far is:
Any help much appreciated.
JSP File
<table class="gridtable">
<tr>
<th>Queue Name</th>
<th>Retry Attempt</th>
<th>Reason for failure</th>
<th>Action</th>
</tr>
<% int i=0; %>
<c:forEach var="queueRowDetail" items="${queueRowDetailList}">
<tr>
<td>${queueRowDetail.queueName}</td>
<td>${queueRowDetail.attempt}</td>
<td>${queueRowDetail.errorDetails}</td>
<td>
<form:form method="post" action="/retry" id="frmFailure_<%=i%>" modelAttribute="queueRowDetail"/>
<form:hidden path="queueName<%=i %>" value="${queueRowDetail.queueName}"/>
<form:hidden path="attempt<%=i %>" value="${queueRowDetail.attempt}"/>
<form:hidden path="errorDetails<%=i %>" value="${queueRowDetail.errorDetails} "/>
<input type="button" value="Retry" onClick="sendobj(<%=i%>)" />
</form>
</td>
</tr>
<% i++; %>
</c:forEach>
function sendObj()
<script>
function sendobj(i)
{
var x = document.getElementById("frmFailure_"+i);
alert(obj);
alert("frmFailure_"+i);
x.submit();// Form submission
}
</script>
QueueRowDetail Class
package com.gartner.gqueuefailureapi.model;
public class QueueRowDetail {
private String queueName;
private String errorDetails;
private int attempt;
private Object payLoad;
public String getQueueName() {
return queueName;
}
public void setQueueName(String queueName) {
this.queueName = queueName;
}
public String getErrorDetails() {
return errorDetails;
}
public void setErrorDetails(String errorDetails) {
this.errorDetails = errorDetails;
}
public int getAttempt() {
return attempt;
}
public void setAttempt(int attempt) {
this.attempt = attempt;
}
public Object getPayLoad() {
return payLoad;
}
public void setPayLoad(Object payLoad) {
this.payLoad = payLoad;
}
}
InderController.Java
#RequestMapping(value = "/retry", method = RequestMethod.POST)
public String retryMessage( #ModelAttribute("queueRowDetail")QueueRowDetail queueRowDetail, ModelMap model) {
model.addAttribute("queuename", queueRowDetail.getQueueName());
return "success";
}
I'm in the process of learning spring and thymeleaf and working on a timekeeping project.
For this I need to validate the number of hours an employee clocks in one day.
I used the tutorial in the spring documentation for this however i keep getting the following error
Neither BindingResult nor plain target object for bean name 'timetable' available as request attribute
Any ideas what I might be doing wrong?
Controller class
#RequestMapping(value="Timetable/AddToTimetable", method = RequestMethod.GET)
public String newUser(Model md) {
md.addAttribute("assignments", serv.findAll());
return "AddToTimetable";
}
#RequestMapping(value = "/createEntry", method = RequestMethod.POST)
public String create(#RequestParam("assignmentId") int assignmentId,
#RequestParam("date") #DateTimeFormat(pattern = "yyyy-MM-dd") Date date,
#RequestParam("hoursWorked") int hoursWorked,
#Valid Timetable timetable, BindingResult bindingResult,
Model md) {
timetable = new Timetable();
timetable.setAssignmentId(assignmentId);
timetable.setDate(date);
timetable.setHoursWorked(hoursWorked);
md.addAttribute("timetables", service.timetableAdd(timetable));
if (bindingResult.hasErrors()) {
return "AddToTimetable";
}
return "redirect:/Timetable";
}
Service class
public BigInteger timetableAdd(Timetable timetable){
KeyHolder keyHolder = new GeneratedKeyHolder();
String sql = "INSERT INTO timetables ( assignmentId, date, hoursWorked) VALUES ( ?, ?, ?)";
template.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement pst = con.prepareStatement(sql, new String[] {"id"});
pst.setInt(1, timetable.getAssignmentId());
pst.setDate(2, new java.sql.Date(timetable.getDate().getTime()));
pst.setInt(3, timetable.getHoursWorked());
return pst;
}
}, keyHolder);
return (BigInteger) keyHolder.getKey();
}
}
Model class
package ro.database.jdbcPontaj.model;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Date;
public class Timetable {
private int timetableId;
private int assignmentId;
private Date date;
private String project;
#NotNull
#Min(0)
#Max(12)
private int hoursWorked;
public int getTimetableId() {
return timetableId;
}
public void setTimetableId(int timetableId) {
this.timetableId = timetableId;
}
public int getAssignmentId() {
return assignmentId;
}
public void setAssignmentId(int assignmentId) {
this.assignmentId = assignmentId;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getHoursWorked() {
return hoursWorked;
}
public void setHoursWorked(int hoursWorked) {
this.hoursWorked = hoursWorked;
}
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
public Timetable() {
}
public Timetable(int timetableId, String project, Date date, int hoursWorked) {
this.timetableId = timetableId;
this.project=project;
this.date = date;
this.hoursWorked = hoursWorked;
}
public Timetable(int timetableId, int assignmentId, Date date, int hoursWorked) {
this.timetableId = timetableId;
this.assignmentId = assignmentId;
this.date = date;
this.hoursWorked = hoursWorked;
}
}
Html
<form method="post" name="comment_form" id="comment_form" th:action="#{/createEntry}" th:object="${timetable}" role="form">
<p> Project</p><br>
<select name="assignmentId">
<option value="" th:each="assignment: ${assignments}" th:value="${assignment.assignmentId}" th:text="${assignment.assignmentId}"></option>
</select>
<p>Date</p> <br>
<input class="datepicker" type="text" name="date"><br>
<p>Number of hours</p>
<input type="text" name="hoursWorked" th:field="*{hoursWorked}"><br>
<p th:if="${#fields.hasErrors('hoursWorked')}" th:errors="*{hoursWorked}">Age Error</p>
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
</form>
UPDATE:
Timetable (skipping bootstrap divs)
<div class="row">
<div class="col-md-10 title">
<h2>Timetable</h2>
</div>
<div class="col-md-2">
</div>
<div class="col-md-12">
<table class="table table-bordered">
<thead>
<tr>
<th>id</th>
<th>assignment</th>
<th>date</th>
<th>number of hours</th>
</tr>
</thead>
<tbody>
<tr th:each = "timetable: ${timetables}">
<td th:text="${timetable.timetableId}">45</td>
<td th:text="${timetable.project}">vasi</td>
<td th:text="${timetable.date}">1 ian</td>
<td th:text="${timetable.hoursWorked}">3000</td>
</tr>
</tbody>
</table>
Service method for Timetable
#Autowired
JdbcTemplate template;
public List<Timetable> findAll(String loginname) {
String sql = " SELECT timetables.timetableId, timetables.assignmentId, timetables.date, " +
"timetables.hoursWorked, users.username, projects.projectName AS project " +
"FROM timetables INNER join assignments on timetables.assignmentId = assignments.assignmentId " +
"INNER JOIN projects on assignments.projectId = projects.projectId " +
"INNER JOIN users on users.userId = assignments.userId where username= ?";
RowMapper<Timetable> rm = new RowMapper<Timetable>() {
#Override
public Timetable mapRow(ResultSet resultSet, int i) throws SQLException {
Timetable timetable = new Timetable(resultSet.getInt("timetableId"),
resultSet.getString("project"),
resultSet.getDate("date"),
resultSet.getInt("hoursWorked"));
return timetable;
}
};
return template.query(sql, rm, loginname);
}
The controller method for Timetable
#RequestMapping(value = {"/Timetable"}, method = RequestMethod.GET)
public String index(Model md){
org.springframework.security.core.Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String loginname = auth.getName();
md.addAttribute("timetables", service.findAll(loginname));
return "Timetable";
}
If I understand correctly you have two html pages one that shows all the assignments and one that you enter the new entry.I think that get the error when there is a validation error in the new entry page.
Substitute these lines
if (bindingResult.hasErrors()) {
return "AddToTimetable";
}
with these ones
if (bindingResult.hasErrors()) {
return "newEntry";//replace the newentry with the html page that you enter the new entry
}
When there is an error, you should go to the page that you tried to enter the new entry and not in the page that has all the assignments.
Ok I am having an issue and have been stuck for a few hours. I am running the current version of spring with Hibernate and need to take data from a form and save it do the database, that's all but it is giving me tons of trouble and have no idea how to go about it. Below is the controller, JSP, Model, and Dao.
Controller
private final String addNewView = "addAward";
#RequestMapping(value = "/addAwardType", method = RequestMethod.GET)
public String addAwardType() {
LOG.debug("Display form to add a new contact.");
return addNewView;
}
#RequestMapping(value = "/addAwardType", method = RequestMethod.POST)
public ModelAndView addAwardType(
#ModelAttribute("AwardTypeModel") AwardType awardType,
BindingResult result) {
return new ModelAndView(addNewView, "AwardType", new AwardTypeModel(awardType));
}
}
JSP
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Add AwardType</h2>
<form:form method="POST" commandName="addAwardType">
<table>
<tr>
<td><form:label path="AwardType.name">Award Name</form:label></td>
<td><form:input path="AwardType.name" /></td>
</tr>
<tr>
<td><form:label path="AwardType.description">Last Name</form:label></td>
<td><form:input path="AwardType.description" /></td>
</tr>
<tr>
<td> <form:checkbox path="AwardType.isActive" value="Active"/></td>
</tr>
<tr>
<td><form:label path="AwardType.created"></form:label></td>
<td><form:input path="AwardType.created" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Award"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
Model
public class AwardTypeModel extends BaseModel {
private int id;
private String name;
private String description;
private boolean active;
private Date created;
private Date modified;
/**
* Construct from persistence object
* A similar constructor will be needed in each model
* #param dbo - the Persistence Object (data base object)
*/
public AwardTypeModel(AwardType dbo){
this.id = dbo.getAwardTypeId();
this.name = dbo.getAwardName();
this.description = dbo.getDescription();
this.active = dbo.isActive();
this.created = dbo.getCreated();
this.modified = dbo.getModified();
}
/* (non-Javadoc)
* #see com.eaglecrk.recognition.model.BaseModel#convertToDb()
*/
#Override
public BasePersistence convertToDb() {
AwardType dbo = new AwardType();
dbo.setAwardTypeId(this.id);
dbo.setAwardName(this.name);
dbo.setDescription(this.description);
dbo.setActive(this.active);
dbo.setCreated(this.created);
dbo.setModified(this.modified);
return dbo;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
}
In my page jsp, i have a form where i can add a user to my database, and i use a validator to show errors when fields are empty, but what i want to do is, when i insert a duplicate entry of the primary key of my table, the validator show me a message that this login for example is already taken instead having an error by Apache!
this is my User POJO :
package gestion.delegation.domaine;
import java.io.Serializable;
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
int id;
String nom;
String prenom;
String login;
String password;
String role;
boolean enable;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean getEnable() {
return this.enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public User(int id, String nom, String prenom, String login,
String password, String role, boolean enable) {
super();
this.id = id;
this.nom = nom;
this.prenom = prenom;
this.login = login;
this.password = password;
this.role = role;
this.enable = enable;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public User() {
super();
}
}
and this is my validator :
package gestion.delegation.validator;
import gestion.delegation.domaine.User;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class AddUserValidator implements Validator{
#Override
public boolean supports(Class<?> clazz) {
return User.class.isAssignableFrom(clazz);
}
#Override
public void validate(Object obj, Errors err) {
ValidationUtils.rejectIfEmptyOrWhitespace(err, "nom", "name.required","Choisissez un nom");
ValidationUtils.rejectIfEmptyOrWhitespace(err, "prenom", "prenom.required", "Choisissez un prenom");
ValidationUtils.rejectIfEmptyOrWhitespace(err, "login", "login.required", "Choisissez un login");
ValidationUtils.rejectIfEmptyOrWhitespace(err, "password", "password.required", "Choisissez un password");
ValidationUtils.rejectIfEmpty(err, "role", "role.required", "Choisissez un role");
}
}
the form :
<c:if test="${not empty msg_success}">
<div class="success">Vous avez ajouter un utilisateur avec
succès !</div>
</c:if>
<form:form name="ajf"
action="${pageContext.request.contextPath}/ajouter_user"
method="post" commandName="user">
<table id="tabmenu">
<tr>
<td id="idtab">Nom :</td>
<td><form:input type="text" path="nom"
class="round default-width-input" name="name_" /></td>
<td><form:errors path="nom" Class="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Prénom :</td>
<td><form:input type="text" path="prenom" name="prenom_"
class="round default-width-input" /></td>
<td><form:errors path="prenom" cssClass="errorbox" />
</tr>
<tr>
<td id="idtab">Login :</td>
<td><form:input type="text" path="login" name="login_"
cssClass="round default-width-input" /></td>
<td><form:errors path="login" cssClass="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Password :</td>
<td><form:input type="password" path="password" name="pass_"
class="round default-width-input" /></td>
<td><form:errors path="password" cssClass="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Séléctionner un rôle :</td>
<td><form:select path="role">
<form:option value="" label="" />
<form:option value="ROLE_ADMIN">Administrateur</form:option>
<form:option value="ROLE_USER">Simple utilisateur</form:option>
</form:select></td>
<td><form:errors path="role" cssClass="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Activé :</td>
<td><form:input type="checkbox" value="true" path="enable" />
Oui</td>
</tr>
<tr></tr>
<tr></tr>
<tr>
<td><input
class="button round blue image-right ic-right-arrow"
type="submit" value="Créer" /></td>
<td><input
class="button round blue image-right ic-right-arrow"
type="reset" value="Initialiser" /></td>
</tr>
</table>
</form:form>
Any Idea?
I'm afraid that a Validator will not be sufficient in this case. Although you could extend your AddUserValidator class to check whether the given user name is free, it will not
work in a situation in which two users simultaneously try to register using the same user name - the validation will pass, however one of the users will get an error from the database.
To protect yourself against such situations I would place the registration logic in a try catch block and in case of an error display a proper message to the user. This would be kind of an application-level validation.
Spring validator simply checks your object in accordance with the prescribed rules before you bring it into the database. It does not know anything about the database. To display the error that occurred while working with a database, you need to catch the exception manually.
In your Controller Just Check the duplication by querying from Model Repository.
#Model Entity
#Table(name = "people")
public class People {
#Column(name = "nic")
#NotEmpty(message = "*Please provide your nic")
private String nic;
#Repository
public interface PeopleRepository extends JpaRepository<People, Integer>{
People findByNic(String nic);
}
#Controller
#RequestMapping(value = "/welcome", method = RequestMethod.POST)
public ModelAndView createNewPeople(Model model,, BindingResult bindingResult) {
ModelAndView modelAndView = new ModelAndView();
People peopleExistsEmail = peopleService.findUserByNic(people.getNic());
if (peopleExistsEmail != null) {
bindingResult
.rejectValue("nic", "error.people",
"There is already a person registered with the nic provided");
}
if (bindingResult.hasErrors()) {
modelAndView.setViewName("welcome");
} else {
peopleService.savePeople(people);
modelAndView.addObject("successMessage", "People has been registered successfully");
modelAndView.addObject("people", new People());
} catch (Exception e) {
e.printStackTrace();
}
}
return modelAndView;
}
So this is the Right Answer :
The method in DAO class implementation is like that :
public boolean AddUser(User user) {
boolean t=true;
final String User_INSERT1 = "insert into utilisateurs (login, password, nom, prenom,enable) "
+ "values (?,?,?,?,?)";
final String User_INSERT2="insert into roles (login,role) values(?,?)";
/*
* On récupère et on utilisera directement le jdbcTemplate
*/
MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("SHA");
String hash = encoder.encodePassword(user.getPassword(), "");
final String check ="select count(*) from utilisateurs where login = ?";
int result= getJdbcTemplate().queryForInt(check, new Object[]{String.valueOf(user.getLogin())});
if (result==0) {
getJdbcTemplate()
.update(User_INSERT1,
new Object[] {user.getLogin(),
hash, user.getNom(),
user.getPrenom(), user.getEnable(),
});
getJdbcTemplate().update(User_INSERT2, new Object[]{user.getLogin(),user.getRole()});
return t;
}
else { t = false ; return t;}
}
The controller :
#RequestMapping(value ="/ajouter_user", method = RequestMethod.POST)
public String add(#ModelAttribute User us,BindingResult result,ModelMap model) {
AddUserValidator uservalid=new AddUserValidator();
uservalid.validate(us, result);
if (result.hasErrors()) {
model.addAttribute("usersystem", userservice.getAllUsers());
return "gestionUser";
}else {
boolean e = userservice.AddUser(us);
if (e==false){
model.addAttribute("msg_failed","true");
}
else {
model.addAttribute("msg_success","true");}
model.addAttribute("usersystem", userservice.getAllUsers()); /*verifier*/
return "gestionUser";
}
}
And for showing the error in the jsp file :
<c:if test="${not empty msg_failed}">
<div class="errorblock">Il existe déjà un utilisateur avec cet login </div>
</c:if>
The method in DAO class implementation is like that :
public final long insert(final User user) throws MyException {
String sql = "INSERT INTO users ....";
String chkSql = "SELECT count(*) FROM users WHERE username=:username";
Map namedParams = new HashMap();
namedParams.put("username", user.getUsername());
long newId = namedTemplate.queryForInt(chkSql, namedParams);
if (newId > 0) {
try {
throw new MyException(-1);
} catch (MyException e) {
throw e;
}
}
newId = ...;// could be generated if not inc field or triggered...
namedParams.put("username", user.getUserName());
...
...
namedParams.put("id", newId);
namedTemplate.update(sql, namedParams);
return newId;
}
MyException like that:
public class MyException extends Exception{
private static final long serialVersionUID = 1L;
int a;
public MyException(int b) {
a=b;
}
}
Controller:
#RequestMapping(value = "/user", method = RequestMethod.POST)
public final ModelAndView actionUser(
final ModelMap model,
#ModelAttribute("myitemuser") #Valid final User user,
final BindingResult bindResult,
...);
...
try {
userService.addUser(user); // or dao... ;)
} catch (Exception e) {
UserValidator userValidator = new UserValidator();
userValidator.custError(bindResult);
}
UserValidator like that:
...
#Override
public final void validate(final Object object, final Errors errors) {
User user = (User) object;
...
if (user.getPassword().isEmpty()) {
errors.rejectValue("password", "error.users.emptypass");
}
}
public final void custError(final Errors errors){
errors.rejectValue("username"/* or login */, "error.users.uniqname");
}
...
Ну как то так))))
i need your help as the title says i have a problem inserting multiple rows from a jsp form. The code is from an answer from this site.
Controller
#ModelAttribute("programform")
public ProgramForm populatePojos() {
// Don't forget to initialize the pojos list or else it won't work
ProgramForm programform = new ProgramForm();
List<Programs> programs = new ArrayList<Programs>();
for(int i=0; i<2; i++) {
programs.add(new Programs());
}
programform.setPrograms(programs);
return programform;
}
#RequestMapping(value = "/createprog")
public ModelAndView tiles2(#ModelAttribute("programform") ProgramForm programform,
BindingResult result) {
//Map<String, Object> model = new HashMap<String, Object>();
//model.put("articles", articleService.listArticles());
return new ModelAndView("createprogram");
}
#RequestMapping(value = "/saveprogram", method = RequestMethod.POST)
public ModelAndView saveProgram(#ModelAttribute("programform") ProgramForm programform,
BindingResult result) {
for(Programs programs : programform.getPrograms()) {
System.out.println(programs.getProgram_id());
articleService.addProgram(programs);
}
jsp
<c:url var="saveProgramUrl" value="/articles/saveprogram.html" />
<form:form modelAttribute="programform" method="POST" action="${saveProgramUrl}">
<table>
<tr>
<th>ProgramId</th>
<th>Date</th>
<th>Type</th>
<th>Start</th>
<th>End</th>
<th>Location</th>
<th>User</th>
<th>Program Name</th>
</tr>
<tr>
<th><form:input path="programs[0].program_id" /></th>
<th> <form:input path="programs[0].date" id="datepick" class="date-pick"/>
<script type="text/javascript">
datepickr('datepick', { dateFormat: 'Y-m-d' });
</script></th>
<th><form:input path="programs[0].type" /></th>
<th><form:input path="programs[0].start" /></th>
<th><form:input path="programs[0].end" /></th>
<th><form:input path="programs[0].location" /></th>
<th><form:input path="programs[0].user_id" /></th>
<th><form:input path="programs[0].program_name" /></th>
</tr>
<tr>
<th><form:input path="programs[1].program_id" /></th>
<th> <form:input path="programs[1].date" id="datepick" class="date-pick"/>
<script type="text/javascript">
datepickr('datepick', { dateFormat: 'Y-m-d' });
</script></th>
<th><form:input path="programs[1].type" /></th>
<th><form:input path="programs[1].start" /></th>
<th><form:input path="programs[1].end" /></th>
<th><form:input path="programs[1].location" /></th>
<th><form:input path="programs[1].user_id" /></th>
<th><form:input path="programs[1].program_name" /></th>
</tr>
</table>
<br/>
<input type="submit" value="Insert User" />
</form:form>
Program
package net.roseindia.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "program")
public class Programs {
#Id
#Column(name = "Program_Id")
private int program_id;
#Column(name = "Date")
private String date;
#Column(name = "Duty_Type")
private String type;
#Column(name = "Duty_Start_Time")
private String start;
#Column(name = "Duty_End_Time")
private String end;
#Column(name = "Location")
private String location;
#Column(name = "User_Id")
private int user_id;
#Column(name = "Program_Name")
private String program_name;
public int getProgram_id() {
return program_id;
}
public void setProgram_id(int program_id) {
this.program_id = program_id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getProgram_name() {
return program_name;
}
public void setProgram_name(String program_name) {
this.program_name = program_name;
}
public Programs() {
}
}
ProgramForm
package net.roseindia.model;
import java.util.List;
public class ProgramForm {
private List<Programs> programs;
public List<Programs> getPrograms() {
return programs;
}
public void setPrograms(List<Programs> programs) {
this.programs = programs;
}
}
When i push the button to save this to programs nothing inserted in the database, what i am doing wrong?
To add multiple rows you need to lazy init your list. Please change your code in the #ModelAttribute("programform") as per following and then try again.
#ModelAttribute("programform")
public ProgramForm populatePojos() {
// Don't forget to initialize the pojos list or else it won't work
ProgramForm programform = new ProgramForm();
List<Programs> programs = LazyList.decorate(new ArrayList<Programs>(), FactoryUtils.instantiateFactory(Programs.class));
for(int i=0; i<2; i++) {
programs.add(new Programs());
}
programform.setPrograms(programs);
return programform;
}
With having list inilialized as above you can also add more fields run time using javascript and can get those values binded in your list.
After doing this changes if it won't work then you need to do changes in your jsp page. Instead of using the use simple tag but don't forget to specify the same value in name attribute as you have specified in the path attribute here.
Hope this helps you. Cheers.