insert date from jsp into database - java

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());

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 bind data to list in spring form

I have a spring form with having backing object for it. The form is like this-
<sf:form cssClass="form-horizontal" commandName="campaignModel" method="post">
<sf:input path="campaign.name" class="form-control" />
<sf:input path="landingPageModels.landingPage.url" class="form-control" />
</sf:form>
Model class(Form backing Object) -
CampaignModel.java
public class CampaignModel {
private Campaign campaign = new CampaignImpl();
private List<LandingPageModel> landingPageModels = new Arraylist<LandingPageModel>;
public Campaign getCampaign() {
return campaign;
}
public void setCampaign(Campaign campaign) {
this.campaign = campaign;
}
public List<LandingPageModel> getLandingPageModels() {
return landingPageModels;
}
public void setLandingPageModels(List<LandingPageModel> landingPageModels) {
this.landingPageModels = landingPageModels;
}
LandingPageModel.java is -
public class LandingPageModel {
private LandingPage landingPage = new LandingPageImpl();
private List<LandingPageParameterImpl> landingPageParameters = new ArrayList<LandingPageParameterImpl>();
public LandingPage getLandingPage() {
return landingPage;
}
public void setLandingPage(LandingPage landingPage) {
this.landingPage = landingPage;
}
public List<LandingPageParameterImpl> getLandingPageParameters() {
return landingPageParameters;
}
public void setLandingPageParameters(List<LandingPageParameterImpl> landingPageParameters) {
this.landingPageParameters = landingPageParameters;
}
}
LandingPage.java is -
public class LandingPageImpl extends EntityImpl implements LandingPage {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
} }
So i want that i can insert many objects of landingPage (having their own url property) in landingPageModels list. That means i can have mulitple input tag having url property like this -
<sf:input path="landingPageModels.landingPage.url" class="form-control" />
<sf:input path="landingPageModels.landingPage.url" class="form-control" />
<sf:input path="landingPageModels.landingPage.url" class="form-control" />
But when executing this code, spring gives me error that landingPage property of landingPageModels has not getter setter method. How to solve it and how to take multiple value like this ?
In order to bind a list model property to multiple input fields, you need this in the rendered form:
<input type="text" name="landingPageModels[0].landingPage.url" class="form-control" />
<input type="text" name="landingPageModels[1].landingPage.url" class="form-control" />
<input type="text" name="landingPageModels[2].landingPage.url" class="form-control" />
Which is accomplished by:
<c:forEach items="${campaignModel.landingPageModels}" varStatus="s">
<sf:input path="landingPageModels[${s.index}].landingPage.url" class="form-control" />
</c:forEach>
The error you are getting is correct as landingPageModels is a list.
You would need to use index access like this landingPageModels[0].landingPage.url.
If you have dynamic number of input/url, then you can use <c:forEach> to create dynamic input variable names
<c:forEach items="${campaignModel.landingPageModels}" var="landingPage">
<sf:input path="landingPage.url" class="form- control" />
</c:forEach>
Will the above not works for you to view data? To get them in controller you may have to use dynamic table row concept in HTML or for each single LandingPage entry add to form bean object by clicking add button and render back.
In my case Person command object having List<Token> property, in order to bind the list of tokens we have designed page as attached screen shot below, clicking on Add button hits the controller and add the each token List<Token> and render back to same view and displays added token in list view, it facilitates to add multiple token for Person.
I dont know how to do it with spring form lib input but if you want to bind using simple html input than you can bind list like this
Simple.jsp
<%#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"%>
<html>
<head>
</head>
<body>
<form:form method="post" action="save.html" modelAttribute="contactForm">
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr>
<td><input name="contacts[0].firstname" /></td>
<td><input name="contacts[0].lastname" /></td>
</tr>
<tr>
<td><input name="contacts[1].firstname" /></td>
<td><input name="contacts[1].lastname" /></td>
</tr>
</table>
<br/>
<input type="submit" value="Save" />
</form:form>
</body>
</html>
#controller :
#RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(#ModelAttribute("contactForm") ContactForm contactForm) {
List<Contact> contacts = contactForm.getContacts();
if(null != contacts && contacts.size() > 0) {
ContactController.contacts = contacts;
for (Contact contact : contacts) {
System.out.printf("%s \t %s \n", contact.getFirstname(), contact.getLastname());
}
}
return new ModelAndView("show_contact", "contactForm", contactForm);
}
ContactForm.java
import java.util.List;
public class ContactForm {
private List<Contact> contacts;
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
}
Contact.java
public class Contact {
private String firstname;
private String lastname;
private String email;
private String phone;
public Contact() {
}
//getters and setters
}

Property on model attribute set in one controller method is not available in another controller method

Following contains the code inside my controller class , i am using the method public String getRegistrationForm(Map model) to return a jsp-page with a spring form on it , in this method i am setting userTab.setIsMfaEnabled(new Boolean(true)) , upon submitting the form the method :
public String registerUser(#ModelAttribute("user") UserTab user , BindingResult results , Map model)
is invoked as the handler method , but in this method the property 'isMfaEnabled' of user attribute set in the previous method is null and the line:System.out.println("user.getIsMfaEnabled() is nul"); is printing in the logs . Kindly tell me what is wrong here .
#Controller
#RequestMapping("/register")
public class RegisterUserController {
#Autowired
RegisterUserService registerUserService;
#RequestMapping(value = "/registeruser.action" , method = RequestMethod.POST)
public String registerUser(#ModelAttribute("user") UserTab user , BindingResult results , Map<String,Object> model){
System.out.println("executing regsiterUser ");
if(user == null)
System.out.println(", user is null");
if(results == null)
System.out.println("results is null");
UserTabValiator userTabValidator = new UserTabValiator();
if(user.getIsMfaEnabled() == null)
System.out.println("user.getIsMfaEnabled() is nul");
userTabValidator.validate(user, results);
if(results.hasErrors()){
return "registeruser";
}
try {
boolean val = registerUserService.isExistingUsername(user.getLoginName());
if(val){
System.out.println("username already exists");
model.put("message", "username already exists");
return "registeruser";
}
if(!val){
model.put("username", user.getLoginName());
model.put("message", "registration success ... ");
return "registrationsuccess";
}
} catch (Exception e) {
System.out.println("exception thrown");
e.printStackTrace();
return "errorpage";
}
return "errorpage";
}
#RequestMapping(value="/registeruser.view", method=RequestMethod.GET)
public String getRegistrationForm(Map<String,Object> model){
System.out.println("executing getRegistrationForm");
if(registerUserService == null)
System.out.println("register user service is null");
try{
ArrayList<MfaQuestion> allMfaQuestions = (ArrayList<MfaQuestion>) registerUserService.getAllMfaQuestions();
UserTab userTab = new UserTab();
userTab.setIsMfaEnabled(true);
model.put("user", userTab);
model.put("message", "register new user");
model.put("allMfaQuestions", allMfaQuestions);
return "registeruser";
}
catch(Exception e){
e.printStackTrace();
model.put("user", new UserTab());
model.put("message", "unable to get MFA questions");
return "registeruser";
}
}
}
UserTab Model Class :
package com.persistance.beans;
import java.util.Date;
public class UserTab {
private Integer userTabID;
private String loginName;
private String password;
private Date created;
private Date lastUpdated;
private Date lastLoginAttempt;
private Boolean isAccountLocked;
private Integer loginFailsNumber;
private Boolean isMfaEnabled;
private UserMfaMap userMfaMap;
public String toString(){
String str ="";
System.out.println("[userTabID , loginName , password");
return str;
}
public UserMfaMap getUserMfaMap() {
return userMfaMap;
}
public void setUserMfaMap(UserMfaMap userMfaMap) {
this.userMfaMap = userMfaMap;
}
public UserTab() {
super();
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getLastUpdated() {
return this.lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
public Date getLastLoginAttempt() {
return lastLoginAttempt;
}
public void setLastLoginAttempt(Date lastLoginAttempt) {
this.lastLoginAttempt = lastLoginAttempt;
}
public Boolean getIsAccountLocked() {
return isAccountLocked;
}
public void setIsAccountLocked(Boolean isAccountLocked) {
this.isAccountLocked = isAccountLocked;
}
public Integer getLoginFailsNumber() {
return loginFailsNumber;
}
public void setLoginFailsNumber(Integer loginFailsNumber) {
this.loginFailsNumber = loginFailsNumber;
}
public Boolean getIsMfaEnabled() {
return isMfaEnabled;
}
public void setIsMfaEnabled(Boolean isMfaEnabled) {
this.isMfaEnabled = isMfaEnabled;
}
public Integer getUserTabID() {
return userTabID;
}
public void setUserTabID(Integer userTabID) {
this.userTabID = userTabID;
}
}
RegisterUser JSP page :
<form:form method="POST" action="${pageContext.request.contextPath}/register/registeruser.action" commandName ="user">
<table>
<tr>
<td><form:label path="loginName">UserName</form:label></td>
<td><form:input path="loginName" /></td>
<form:errors path="loginName" cssClass="error"/>
</tr>
<tr>
<td><form:label path="password">Password</form:label></td>
<td><form:input path="password" /></td>
<form:errors path="password" cssClass="error"/>
</tr>
<div id="question1" class="questionblock">
<tr>
<form:select path="userMfaMap.question1" >
<c:forEach items="${allMfaQuestions}" var="mfaQuestion">
<form:option value="${mfaQuestion.mfaQuestionId}">
<c:out value="${mfaQuestion.mfaQuestion}" />
</form:option>
</c:forEach>
</form:select>
</tr>
<tr>
<td><form:label path="userMfaMap.answer1">Answer:</form:label></td>
<td><form:input path="userMfaMap.answer1" /></td>
<form:errors path="userMfaMap.answer1" cssClass="error"/>
</tr>
</div>
<div id="question2" class="questionblock">
<tr>
<form:select path="userMfaMap.question2">
<c:forEach items="${allMfaQuestions}" var="mfaQuestion">
<form:option value="${mfaQuestion.mfaQuestionId}">
<c:out value="${mfaQuestion.mfaQuestion}" />
</form:option>
</c:forEach>
</form:select>
</tr>
<tr>
<td><form:label path="userMfaMap.answer2">Answer:</form:label></td>
<td><form:input path="userMfaMap.answer2" /></td>
<form:errors path="userMfaMap.answer2" cssClass="error"/>
</tr>
</div>
<div id="question3" class="questionblock">
<tr>
<form:select path="userMfaMap.question3">
<c:forEach items="${allMfaQuestions}" var="mfaQuestion">
<form:option value="${mfaQuestion.mfaQuestionId}">
<c:out value="${mfaQuestion.mfaQuestion}" />
</form:option>
</c:forEach>
</form:select>
</tr>
<tr>
<td><form:label path="userMfaMap.answer3">Answer:</form:label></td>
<td><form:input path="userMfaMap.answer3" /></td>
<form:errors path="userMfaMap.answer3" cssClass="error"/>
</tr>
</div>
<tr>
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form:form>
Add code in the JSP form to bind the value of isMfaEnabled
<form:input path="isMfaEnabled" />

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.

Categories

Resources