How to read and pass data from servlet to JSP - java

A question about read and pass data from servlet to JSP
I want to create a Java EE project. Totally, it has 5 files in this project.
JSP Files: EmployeeInfo.jsp, EmployeeDetails.jsp
Servlets: EmployeeRegistrationServlet, EmployeeSearchServlet
Bean: Employee
EmployeeInfo.jsp file that gets either Employee Id or Employee Information. It have two Submit buttons. If user wants to search an Employee, an ID would be entered and it will call EmployeeSearchServlet, if user wants to add new Employee information, then EmployeeRegistrationServlet will be called with customer information entered. Here is the code:
EmployeeSearchServlet is supposed to search an employee with employee id that was entered by the end user. The job of the servlet is to find particular employee within a collection. Once the employee is found, the flow will be forwarded to EmployeeDetails.jsp.
EmployeeRegistrationServlet is supposed to add employees into a collection where store employees in memory.
If an employee is found, details of employee will be displayed on EmployeeDetails.jsp.
If a new employee is added, details of employee will be displayed on EmployeeDetails.jsp.
Here is my EmployeeInfo.jsp
<body>
<h1 align="center">Employee Information</h1>
<!--Form of find employee by employeeID -->
<form action="EmployeeSearchServlet" method="POST">
<fieldset>
<legend>Find Employee</legend>
Employee ID: <input type="text" name="findEmployeeID"><br>
<input type="submit" name="findEmployeeSubmit" value="Find Employee">
</fieldset>
</form>
<p></p>
<!--Form of add employee-->
<form action="EmployeeRegistrationServlet" method="POST">
<fieldset>
<legend>Employee Information</legend>
<table>
<tr>
<td>Employee ID (key)*: </td>
<td><input type="text" name="employeeID"></td>
</tr>
<tr>
<td>First Name:* </td>
<td><input type="text" name="firstName"></td>
</tr>
<tr>
<td>Last Name:* </td>
<td><input type="text" name="lastName"></td>
</tr>
<tr>
<td>Email: </td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Phone: </td>
<td><input type="text" name="phone"></td>
</tr>
<tr>
<td>Hire Date: </td>
<td><input type="text" name="hireDate"></td>
</tr>
<tr>
<td>Manager ID: </td>
<td><input type="text" name="managerID"></td>
</tr>
<tr>
<td>Department ID: </td>
<td><input type="text" name="departmentID"></td>
</tr>
</table>
<input type="submit" name="addEmployeeSubmit" value="Add Employee">
</fieldset>
</form>
</body>
Here is my Employee bean.
public class Employee {
private String employeeID;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
private String hireDate;
private String managerID;
private String departmentID;
public Employee(String newEmployeeID,
String newFirstName,
String newLastName,
String newEmail,
String newPhoneNumber,
String newHireDate,
String newManagerID,
String newDepartmentID){
this.employeeID = newEmployeeID;
this.firstName = newFirstName;
this.lastName = newLastName;
this.email = newEmail;
this.phoneNumber = newPhoneNumber;
this.hireDate = newHireDate;
this.managerID = newManagerID;
this.departmentID = newDepartmentID;
}
public void setEmployeeID(String newEmployeeID){
this.employeeID = newEmployeeID;
}
public void setFirstName(String newFirstName){
this.firstName = newFirstName;
}
public void setLastName(String newLastName){
this.lastName = newLastName;
}
public void setEmail(String newEmail){
this.email = newEmail;
}
public void setPhoneNumber(String newPhoneNumber){
this.phoneNumber = newPhoneNumber;
}
public void setHireDate(String newHireDate){
this.hireDate = newHireDate;
}
public void setManagerID(String newManagerID){
this.managerID = newManagerID;
}
public void setDepartmentID(String newDepartmentID){
this.departmentID = newDepartmentID;
}
public String getEmployeeID() {
return employeeID;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getHireDate(){
return hireDate;
}
public String getManagerID(){
return managerID;
}
public String getDepartmentID(){
return departmentID;
}
}
here is my EmployeeRegistrationServlet
#WebServlet("/EmployeeRegistrationServlet")
public class EmployeeRegistrationServlet extends HttpServlet {
private Map<String,Employee> employees;
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String employeeID = request.getParameter("employeeID").trim();
String firstName = request.getParameter("firstName").trim();
String lastName = request.getParameter("lastName").trim();
String email = request.getParameter("email").trim();
String phone = request.getParameter("phone").trim();
String hireDate = request.getParameter("hireDate").trim();
String managerID = request.getParameter("managerID").trim();
String departmentID = request.getParameter("departmentID").trim();
employees = new HashMap<String,Employee>();
Employee newAdd = new Employee(employeeID, firstName, lastName, email, phone, hireDate, managerID, departmentID);
request.getRequestDispatcher("../../../../WebContent/EmployeeDetail.jsp").forward(request,response);
}
}
My question is how to use EmployeeDetail.jsp read bean object passed from EmployeeRegistrationServlet? And how to Find an employee by searching the employee ID?
Please give me some suggestions. Thanks a lot.

My question is how to use EmployeeDetail.jsp read bean object passed from EmployeeRegistrationServlet?
You need to set the Object in request / session attribute to be available to forwarded jsp
how to Find an employee by searching the employee ID?
depends on your data store, for example if you are using mysql you need to use jdbc and query to get record by id
See
example on jsp wiki
servlet wiki

You have many choices. I would encourage you to look at this tutorial, and consider using <jsp:useBean id="myObject" class="myClass" scope="session"/> tags:
http://www.jsptut.com/forms.jsp
Here is the full JSTL tutorial from Oracle:
http://docs.oracle.com/javaee/5/tutorial/doc/bnakc.html

Related

Attempting to make a button in thymeleaf that increments a user's balance

Attempting to make have options for the user that they can press a few buttons to increase the current "balance" of the "buyer". As of now, my buttons do nothing and I'm sure there is extremely stupid I'm doing on a rather easy thing. Thanks for any help in advance.
Entity:
#Entity
#Table(schema = "toner_buyer")
public class Buyer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "BUYER_ID")
private Long buyerId;
#Column(name = "FIRST_NAME")
private String firstName;
#Column(name = "LAST_NAME")
private String lastName;
#Column(name = "BUYER_ADDRESS")
private String buyerAddress;
#Column(name = "BUYER_BALANCE")
private int balance;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "buyer")
private Set<Toner> toners;
public Buyer(){}
public Buyer(String firstName, String lastName, String buyerAddress, int balance) {
this.firstName = firstName;
this.lastName = lastName;
this.buyerAddress = buyerAddress;
this.balance = balance;
}
public Buyer(String firstName, String lastName, String buyerAddress, int balance, Set<Toner> toners) {
this.firstName = firstName;
this.lastName = lastName;
this.buyerAddress = buyerAddress;
this.balance = balance;
this.toners = toners;
}
public Set<Toner> getToners() {
return toners;
}
public void setToners(Set<Toner> toners) {
this.toners = toners;
}
public Long getBuyerId() {
return buyerId;
}
public void setBuyerId(Long buyerId) {
this.buyerId = buyerId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getBuyerAddress() {
return buyerAddress;
}
public void setBuyerAddress(String buyerAddress) {
this.buyerAddress = buyerAddress;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
}
Controller:
#Controller
public class BuyerController {
private BuyerService buyerService;
#Autowired
private TonerService tonerService;
#Autowired
public void setBuyerService(BuyerService buyerService){
this.buyerService = buyerService;
}
#RequestMapping("/add-buyer")
public String showBuyerPager(Model model){
//List
List<Buyer> buyers = buyerService.findAllBuyers();
List<Toner> toners = tonerService.findAllToners();
//sending list to view
model.addAttribute("buyers", buyers);
model.addAttribute("toners", toners);
//creating objects in view
model.addAttribute("buyer", new Buyer());
model.addAttribute("toner", new Toner());
return "add-buyer";
}
#GetMapping("/showBuyerForm")
public String addBuyerForm(Model model){
model.addAttribute("buyer", new Buyer());
model.addAttribute("toner", new Toner());
model.addAttribute("buyerId", new Buyer().getBuyerId());
return "add-buyer";
}
#PostMapping("/addBuyer")
public String postBuyerForm(#ModelAttribute("buyer") Buyer buyer, Model model){
buyerService.saveBuyer(buyer);
model.addAttribute("buyer", new Buyer());
return "redirect:/";
}
#PostMapping("/deleteBuyer/{id}")
public String deleteBuyer(#PathVariable Long id){
buyerService.deleteBuyer(id);
return "redirect:/";
}
#PostMapping("/addToBuyerBal/{id}")
public String addToBuyerBalance(Model model, #PathVariable Long id, #ModelAttribute("add") int add){
Buyer mBuyer = buyerService.findOne(id);
mBuyer.setBalance(mBuyer.getBalance() + add);
return "redirect:/";
}
#PostMapping("/purcahseToner/{toner}")
public String buyToner(#PathVariable Toner toner){
Buyer buyer = new Buyer();
return "redirect:/";
}
#PostMapping("/saleToner/{toner}")
public String saleToner(){
return "redirect:/";
}
}
Thymeleaf view:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
<link href="styles.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<header> Welcome to Toner Stock </header>
<h1>Add Buyer</h1>
<div id="mynav" align="center">
<ul>
<li>Home</li>
<li>Add Buyer</li>
<li>Add Manager</li>
<li>Current Stock</li>
<li>Transactions</li>
</ul>
</div>
<div id="display-table" align="center">
<form th:action="#{/addBuyer}" th:object="${buyer}" style="width:100%" method="post">
<table>
<td><label>First Name: </label></td>
<td><input type="text" th:field="*{firstName}"/></td>
<td><label>Last Name: </label></td>
<td><input type="text" th:field="*{lastName}"/></td>
<td><label>Enter Address: </label></td>
<td><input type="text" th:field="*{buyerAddress}"/></td>
<td><input type="submit" value="save"/></td>
</table>
</form>
</div>
<div>
<div>
<table id="info-table" align="center" border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
<th>Select Toner</th>
<th>Current Balance</th>
<th>Add to Balance</th>
<th>Delete Buyer</th>
<th>Purchase Item</th>
<th>Sale Item</th>
</tr>
<tr th:each="buyer : ${buyers}">
<td th:text="${buyer.firstName}"></td>
<td th:text="${buyer.lastName}"></td>
<td th:text="${buyer.buyerAddress}"></td>
<td>
<select>
<option th:each="toner : ${toners}"
th:text="${toner.tonerName}"
th:value="${toner.id}">
</option>
</select>
</td>
<td th:text="${buyer.balance}"></td>
<td>
<form th:action="#{/addToBuyerBal/{id}(id=${buyer.buyerId})}" th:object="${buyer}" method="post">
<button type="submit" value="25" onclick="return confirm('Are you sure you want to pay $25?')">$25</button>
<button type="submit" value="50" onclick="return confirm('Are you sure you want to pay $50?')">$50</button>
<button type="submit" value="100" onclick="return confirm('Are you sure you want to pay $100?')">$100</button>
</form>
</td>
<td>
<form th:action="#{/deleteBuyer/{id}(id=${buyer.buyerId})}" th:object="${buyer}" method="post">
<input type="hidden" th:field="${buyer}">Delete</input>
<button type="submit" onClick="return confirm('Are you sure you want to delete a Manager?')"/>
</form>
</td>
<td>
<form th:action="#{/purcahseToner/{toner}(toner=${buyer.toners})}" th:object="${buyer}" method="post">
<input type="hidden" th:field="*{toners}">Purchase</input>
<button type="submit" onclick="return confirm('Are you sure you want to make this purchase?')"/>
</form>
</td>
<td>
<form th:action="#{/saleToner/{toner}(toner=${buyer.toners})}" th:object="${buyer}" method="post">
<input type="hidden" th:field="*{toners}">Sale</input>
<button type="submit" onclick="return confirm('Are you sure you want to sale this?')"/>
</form>
</td>
</tr>
</table>
</div>
</div>
</body>
</html>

Spring form ID field not populated on POST

In the below Spring form, my object's ID field is populated, but when I receive the submission in the controller method, all of the form's fields are populated except for the ID field. I've quintuple-checked that the field type and getter/setter types are all the same non-primitive, as I've seen many of the other questions on SO similar to this and that seems to be the common issue. The controller doesn't have any method-level #ModelAttributes, so it isn't being populated otherwise.
Here's the declaration of the POST method, as I debugged it on the first containing line and found that the form's id field is empty:
#RequestMapping(value="/{orgId}", method=RequestMethod.POST)
public String editOrganizationPost(#PathVariable int orgId,
#Valid #ModelAttribute(ORG_FORM) OrganizationForm orgForm,
BindingResult result, RedirectAttributes att,
HttpServletRequest request) {
Here's the form object:
public class OrganizationForm {
private Integer id;
#NotBlank
private String name;
#NotBlank
private String description;
private Set<User> users;
int moveToOrganizationId = 0;
String moveToOrganizationName;
int[] moveFromOrganizationUserSelect = null; // List of selected users
// to be moved to a new
// organization
public Integer getId() {
return id;
}
public void setId(Integer 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 Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public int getMoveToOrganizationId() {
return this.moveToOrganizationId;
}
public void setMoveToOrganizationId(int moveToOrganizationId) {
this.moveToOrganizationId = moveToOrganizationId;
}
public String getMoveToOrganizationName() {
return this.moveToOrganizationName;
}
public void setMoveToOrganizationName(String moveToOrganizationName) {
this.moveToOrganizationName = moveToOrganizationName;
}
public int[] getMoveFromOrganizationUserSelect() {
return this.moveFromOrganizationUserSelect;
}
public void setMoveFromOrganizationUserSelect(
int[] moveFromOrganizationUserSelect) {
this.moveFromOrganizationUserSelect = moveFromOrganizationUserSelect;
}
public boolean isNew() {
return this.id == null || this.id == 0;
}
}
Here is the markup from the JSP file:
<form:form method="post" action="${submitUrl}" commandName="organizationForm">
<form:errors path="*" />
<form:hidden path="id" />
<table class="adminTable editContent">
<tr class="bg_lgtGrey">
<td><fmt:message
key="manageOrganizations.organizationForm.name" />:</td>
<td><form:input path="name" cssClass="inputbox"
tabindex="4" /></td>
</tr>
<tr class="bg_lgtGrey">
<td><fmt:message
key="manageOrganizations.organizationForm.description" />:</td>
<td><form:textarea path="description"
cssClass="inputbox" tabindex="4" /></td>
</tr>
<tr>
<td colspan="2" align="right"><c:choose>
<c:when test="${!organizationForm.new}">
<input type="submit" class="btn btn-primary"
id="submit_button" value="Update" />
</c:when>
<c:otherwise>
<input type="submit" class="btn btn-primary"
id="submit_button" value="Create" />
</c:otherwise>
</c:choose></td>
</tr>
</table>
</form:form>
And here is the generated HTML:
<form id="organizationForm" action="/admin/organizations/1" method="post">
<input id="id" name="id" type="hidden" value="1">
<table class="adminTable editContent">
<tbody><tr class="bg_lgtGrey">
<td>Organization Name:</td>
<td><input id="name" name="name" class="inputbox" tabindex="4" type="text" value="Organization1"></td>
</tr>
<tr class="bg_lgtGrey">
<td>Organization Description:</td>
<td><textarea id="description" name="description" class="inputbox" tabindex="4"></textarea></td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" class="btn btn-primary" id="submit_button" value="Update">
</td>
</tr>
</tbody></table>
</form>
I used Chrome devtools to catch the POST data and here it is:
id=1&name=Organization1&description=
...yet at the breakpoint at the first line of the editOrganizationPost method, the form.id field is set to 0.
I have spent forever trying to figure out why it will bind the name and description but not the ID when sent. I could obviously just inject the ID from the path variable but I am dumbfounded as to why it wouldn't just populate the field naturally.
I had the same problem.. the id field would always be set to 0. Changing the id field to something else didn't work either. After more hit and trail, removing
disabled="true"
from
<form:input path"id" disabled="true"/>
fixed the issue.
I assumed
<form:hidden path="id">
would give the same error but it didn't.

Implementing a java bean into a jsp servlet

I am trying to connect my JSP servlets to a posgress database and I am currently using a java bean class which is playing the role of the middle man. I am experiencing some difficulties with making the registration form successfully store user information into the database. I would really appreciate if you would kindly help me out.
Thanks a lot in advance.
JSP servlet:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Register here</title>
</head>
<body>
<form method="post" action="registration.jsp">
<center>
<table border="1" width="30%" cellpadding="5">
<thead>
<tr>
<th colspan="2">Enter Information Here</th>
</tr>
</thead>
<tbody>
<tr>
<td>First Name</td>
<td><input type="text" name="fname" value="" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lname" value="" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="" /></td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="uname" value="" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass" value="" /></td>
</tr>
<tr>
<td>Current Country</td>
<td><input type="text" name="country" value="" /></td>
</tr>
<tr>
<td>Current City</td>
<td><input type="text" name="city" value="" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Reset" /></td>
</tr>
<tr>
<td colspan="2">Already have an account? Login Here</td>
</tr>
</tbody>
</table>
</center>
</form>
</body>
The Java Bean that I use :
public class UserBean {
private int id;
private String username;
private String password;
private String email;
private String firstName;
private String lastName;
private String endDate;
private boolean validated;
public UserBean() {
// Empty constructor
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getEmail() {
return email;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEndDate() {
return endDate;
}
public boolean isValidated() {
return validated;
}
public void setId(int id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setEmail(String email) {
this.email = email;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public void setValidated(boolean validated) {
this.validated = validated;
}
}
Your POJO JavaBean won't magically get populated with the data. It has no connection to the database and no way to get or save data.
You need a controller that fetches data from the DB, creates model objects, and populates them with the data. The controller is also responsible for saving beans
You could write this yourself but it's generally better to use existing ORM frameworks like JPA2, a custom persistence provider API like Hibernate, or something like MyBatis. If you really want, you can hand-roll your controller with direct JDBC calls, injecting the connection from the environment, but that tends to produce a lot of boilerplate code for little benefit even with things like Spring JDBC to help smooth things over.
Some IDEs, like NetBeans and Eclipse, can even auto-generate models and controllers for you, though I've never been very happy with the results (particularly the failure to use a parent-class and generic methods and the lack of any sort of useful error handling).

Spring form send null model object to database

I want to send data from form to PostgreSQL. When I send data by form, hibernate save (by save() method) blank record .. I did it manually (for test) without using form and then everything is ok.
Spitter.class (entity for user)
#Entity
#Table(name="spitter")
public class Spitter implements Serializable {
private static final long serialVersionUID = 829803238866007413L;
#Id
//#SequenceGenerator(name = "hibernate_sequence")
#GeneratedValue(strategy=GenerationType.AUTO) #Column(name="spitter_id")
private Long id;
#Column(unique=true) #Size(min=3, max=20) #Pattern(regexp = "^[a-zA-Z0-9]+$", message="Nie poprawna nazwa uzytkownika.")
private String username;
#Size(min=5, max=15, message="Haslo musi miec minimum 5 znakow.")
private String password;
#Size(min=3, max=25, message="Blad w imieniu i nazwisku.")
private String fullName;
#OneToMany(mappedBy="spitter")
private List<Spittle> spittles;
#Email(message="Nie poprawny adres email.")
private String email;
private boolean updateByEmail;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public List<Spittle> getSpittles() {
return spittles;
}
public void setSpittles(List<Spittle> spittles) {
this.spittles = spittles;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setUpdateByEmail(boolean updateByEmail) {
this.updateByEmail = updateByEmail;
}
public boolean isUpdateByEmail() {
return updateByEmail;
}
#Override
public boolean equals(Object obj) {
Spitter other = (Spitter) obj;
return other.fullName.equals(fullName) && other.username.equals(username) && other.password.equals(password);
}
#Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
}
SpitterController.class
createSpitterProfile - shows form (edit.jsp) and sends model object (spitter) to form
addSpitterFromForm - receives binding data from form and save it to database and redirects to simply user profile
showSpitterProfile - there is of course null model object exception
#Controller
#RequestMapping("/spitters")
public class SpitterController {
private final SpitterService spitterService;
#Inject //#Autowired
public SpitterController(SpitterService spitterService) {
this.spitterService = spitterService;
}
//...
#RequestMapping(method = RequestMethod.GET, params = "new")
public String createSpitterProfile(Model model) {
model.addAttribute("spitter", new Spitter());
return "spitters/edit";
}
#RequestMapping(method = RequestMethod.POST)
public String addSpitterFromForm(#Valid Spitter spitter, BindingResult bindingResult) {
if(bindingResult.hasErrors())
return "spitters/edit";
spitterService.saveSpitter(spitter);
return "redirect:/spitters/" + spitter.getUsername();
}
#RequestMapping(value="/{username}", method = RequestMethod.GET)
public String showSpitterProfile(#PathVariable String username, Model model) {
model.addAttribute(spitterService.getSpitter(username));
return "spitters/view";
}
edit.jsp (registration form for new user (Spitter))
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="s" uri="http://www.springframework.org/tags"%>
<div>
<h2>New account test</h2>
<sf:form method="POST" modelAttribute="spitter"
enctype="multipart/form-data">
<fieldset>
<table>
<tr>
<th><sf:label path="fullName">Full name:</sf:label></th>
<td><sf:input path="fullName" size="15" /><br/>
<sf:errors path="fullName" cssClass="error" />
</td>
</tr>
<tr>
<th><sf:label path="username">Username:</sf:label></th>
<td><sf:input path="username" size="15" maxlength="15" />
<small id="username_msg">No spaces, please.</small><br/>
<sf:errors path="username" cssClass="error" />
</td>
</tr>
<tr>
<th><sf:label path="password">Password:</sf:label></th>
<td><sf:password path="password" size="30"
showPassword="true"/>
<small>6 characters or more (be tricky!)</small><br/>
<sf:errors path="password" cssClass="error" />
</td>
</tr>
<tr>
<th><sf:label path="email">Email Address:</sf:label></th>
<td><sf:input path="email" size="30"/>
<small>In case you forget something</small><br/>
<sf:errors path="email" cssClass="error" />
</td>
</tr>
<tr>
<th></th>
<td>
<sf:checkbox path="updateByEmail"/>
<sf:label path="updateByEmail">Send me email updates!</sf:label>
</td>
</tr>
<tr>
<th></th>
<td>
<input name="commit" type="submit"
value="I accept. Create my account." />
</td>
</tr>
</table>
</fieldset>
</sf:form>
</div>
and blank saved record to Postgres..
Try adding #modelattribute in this method .It fill fetch the required model object.
#RequestMapping(method = RequestMethod.POST)
public String addSpitterFromForm(**#ModelAttribute("spitter")** #Valid Spitter spitter, BindingResult bindingResult) {
if(bindingResult.hasErrors())
return "spitters/edit";
spitterService.saveSpitter(spitter);
return "redirect:/spitters/" + spitter.getUsername();
}
and just to check if it is getting the values from form,syso some values like syso(spitter.getUserName) to check if values are coming.
ALso, I believe that you are making a constructor and passing service to it ,so there is no need of #Inject
#Inject //#Autowired///Why are you injecting it if it is a constructor?
public SpitterController(SpitterService spitterService) {
this.spitterService = spitterService;
}
You have enctype="multipart/form-data in your FORM,
Check that you have something like that in your App-servlet.xml:
<bean id="multipartResolver" class=
"org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:maxUploadSize="500000" />

Add rows on table on button click using spring mvc and bind added rows to modelAttribute

I have a table for which I am passing list of student objects from my spring controller method, On page load 3 rows are populated. I want the user to be able to add more rows delete existing rows on button click. Can anyone tell me how to achieve this. See below my controller and jsp code. On clicking add I want to add 3 more rows selecting check box and clicking delete row should delete the row. i want the the added columns to be binded
I am very new to jQuery is this possible without jQuery. If not please tell me in detail how to achieve this using jQuery
Student Entity
#Entity
#Table(name="STUDENT_REGISTRATION")
public class Student {
private int studentId;
private String firstName;
private String lastName;
private Date dob;
private String sex;
private String status;
private Date doj;
private int deptId;
private String deptName;
private int batchId;
private String batchName;
private int roleId;
private String roleName;
private String regNo;
public Student(){
}
public Student(int studentId, String firstName, String lastName, Date dob,
String sex, String status, Date doj, int deptId,
String deptName, int batchId, String batchName, int roleId,
String roleName, String regNo) {
super();
this.studentId = studentId;
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
this.sex = sex;
this.status = status;
this.doj = doj;
this.deptId = deptId;
this.deptName = deptName;
this.batchId = batchId;
this.batchName = batchName;
this.roleId = roleId;
this.roleName = roleName;
this.regNo = regNo;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="STUDENT_ID")
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
#Column(name="STUDENT_FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name="STUDENT_LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name="DOB")
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
#Column(name="SEX")
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
#Column(name="STATUS")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Column(name="DOJ")
public Date getDoj() {
return doj;
}
public void setDoj(Date doj) {
this.doj = doj;
}
#Column(name="DEPT_ID")
public int getDeptId() {
return deptId;
}
public void setDeptId(int deptId) {
this.deptId = deptId;
}
#Column(name="DEPT_NAME")
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
#Column(name="BATCH_ID")
public int getBatchId() {
return batchId;
}
public void setBatchId(int batchId) {
this.batchId = batchId;
}
#Column(name="BATCH_NAME")
public String getBatchName() {
return batchName;
}
public void setBatchName(String batchName) {
this.batchName = batchName;
}
#Column(name="ROLE_ID")
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
#Column(name="ROLE_NAME")
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
#Column(name="REG_NO")
public String getRegNo() {
return regNo;
}
public void setRegNo(String regNo) {
this.regNo = regNo;
}
}
Student DTO
public class StudentDTO {
private int studentId;
private String firstName;
private String lastName;
private Date dob;
private String sex;
private String status;
private Date doj;
private int deptId;
private String deptName;
private int batchId;
private String batchName;
private int roleId;
private String roleName;
boolean select;
private String regNo;
public StudentDTO(){
}
public StudentDTO(int studentId, String firstName, String lastName,
Date dob, String sex, String status, Date doj, int deptId,
String deptName, int batchId, String batchName, int roleId,
String roleName, boolean select, String regNo) {
super();
this.studentId = studentId;
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
this.sex = sex;
this.status = status;
this.doj = doj;
this.deptId = deptId;
this.deptName = deptName;
this.batchId = batchId;
this.batchName = batchName;
this.roleId = roleId;
this.roleName = roleName;
this.select = select;
this.regNo = regNo;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getDoj() {
return doj;
}
public void setDoj(Date doj) {
this.doj = doj;
}
public int getDeptId() {
return deptId;
}
public void setDeptId(int deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public int getBatchId() {
return batchId;
}
public void setBatchId(int batchId) {
this.batchId = batchId;
}
public String getBatchName() {
return batchName;
}
public void setBatchName(String batchName) {
this.batchName = batchName;
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public boolean isSelect() {
return select;
}
public void setSelect(boolean select) {
this.select = select;
}
public String getRegNo() {
return regNo;
}
public void setRegNo(String regNo) {
this.regNo = regNo;
}
}
Here I am adding 3 Student Objects
public List<StudentDTO> addStudentToList(){
List<StudentDTO> studentList = new ArrayList<StudentDTO>();
StudentDTO stud = new StudentDTO();
for(int i=0; i<3; i++){
studentList.add(stud);
}
return studentList;
}
Student Controller class
#RequestMapping(value="/addStudent", method=RequestMethod.GET)
public ModelAndView getStudentForm(ModelMap model)
{ List<StudentDTO> studentList = studentService.getStudentAttributesList();
//List<Integer> userIdForDropDown = userDAO.getAllUserIdForDropDown();
//model.addAttribute("userIdDropDown",userIdForDropDown);
List<String> deptList = configDAO.getDeptListForDropDown();
model.addAttribute("deptlist",deptList);
List<String> batchList = configDAO.getAllBatchForDropDrown();
model.addAttribute("batchList", batchList);
ModelAndView mav = new ModelAndView("add_student");
Student stu = new Student();
mav.getModelMap().put("add_student", stu);
StudentForm studentForm = new StudentForm();
studentForm.setStudentList(studentList);
model.addAttribute("studentForm",studentForm);
return mav;
}
#RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String saveStudent(#ModelAttribute("add_student") StudentForm studenfForm, BindingResult result, SessionStatus status, ModelMap model) throws ParseException{
/*if(result.hasErrors()){
return "add_student";
}*/
List<StudentDTO> newList = (List<StudentDTO>) studenfForm.getStudentList();
List<Student> newList1 = new ArrayList<Student>();
for(StudentDTO stud:studenfForm.getStudentList()){
Student student = new Student();
student.setBatchId(stud.getBatchId());
student.setBatchName(stud.getBatchName());
student.setDeptId(stud.getDeptId());
student.setDeptName(stud.getDeptName());
SimpleDateFormat sdf = new SimpleDateFormat("DD/MM/YYYY");
Date dateWithoutTime = sdf.parse(sdf.format(new Date()));
student.setDob(stud.getDob());
student.setDoj(stud.getDoj());
student.setFirstName(stud.getFirstName());
student.setLastName(stud.getLastName());
student.setRegNo(stud.getRegNo());
student.setRoleId(stud.getRoleId());
student.setRoleName(stud.getRoleName());
student.setStatus(stud.getStatus());
student.setSex(stud.getSex());
student.setStudentId(stud.getStudentId());
newList1.add(student);
}
Integer saveStatus = studentDAO.saveStudentInfo(newList1);
//Integer res = roleDAO.saveRole(role);
if(saveStatus!=null){
status.setComplete();
model.addAttribute("savedMsg", "Student record saved Successfully.");
}
return "redirect:addStudent";
}
See my jsp page
<table bgcolor="white" width="1200" height="300" align="center" style="border-collapse: collapse;" border="1" bordercolor="#006699" >
<form:form action="addStudent" method="post" commandName="add_student" modelAttribute="studentForm">
<tr>
<td align="center" style="background-color: lightblue"><h3>Add Student</h3></td>
</tr>
<tr align="left">
<td align="left">
<input type="button" id="addrows" name="addrows" class="addperson" value="Add Rows">
<input type="button" id="removerows" class="removerows" value="Delete Rows" />
<input type="submit" value="Save" />
</td>
</tr>
<tr valign="middle" align="center">
<td align="center" valign="middle">
<table width="1200" height="200" style="border-collapse: collapse;" border="0" bordercolor="#006699" cellspacing="0" cellpadding="0">
<thead>
<tr height="1" bgcolor="lightblue">
<th colspan="1">
No
</th>
<th width="5">
Select
</th>
<th>
Reg No
</th>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Sex
</th>
<th>
DOB
</th>
<th>
DOJ
</th>
<th>
Dept Name
</th>
<th>
Role Name
</th>
<th>
Batch Name
</th>
<th>
Status
</th>
</tr>
</thead>
<tbody>
<c:forEach var="rows" items="${studentForm.studentList}" varStatus="status">
<tr class="${status.index % 2 == 0 ? 'even' : 'odd'}" >
<td width="15">
<b>${status.count}</b>
</td>
<td width="10">
<form:checkbox path="studentList[${status.index}].select"/>
</td>
<td><form:input path="studentList[${status.index}].regNo"/></td>
<td><form:input path="studentList[${status.index}].firstName"/></td>
<td><form:input path="studentList[${status.index}].lastName"/></td>
<td><form:select path="studentList[${status.index}].sex">
<form:option value="NONE" label="--- Select ---"/>
<form:option value="M" label="Male"/>
<form:option value="F" label="Female"/>
</form:select></td>
<td><form:input path="studentList[${status.index}].dob"/></td>
<td><form:input path="studentList[${status.index}].doj"/></td>
<td><form:select path="studentList[${status.index}].deptName">
<form:option value="NONE" label="--- Select ---"/>
<form:options items="${deptlist}" />
</form:select></td>
<td><form:select path="studentList[${status.index}].roleName">
<form:option value="NONE" label="--- Select ---"/>
<form:option value="ROLE_STUDENT" label="Student"/>
<form:option value="ROLE_BATCHREP" label="Batch Rep"/>
</form:select></td>
<td><form:select path="studentList[${status.index}].batchName">
<form:option value="NONE" label="--- Select ---"/>
<form:options items="${batchList}" />
</form:select>
</td>
<td><form:select path="studentList[${status.index}].status">
<form:option value="NONE" label="--- Select ---"/>
<form:option value="E" label="Enable"/>
<form:option value="D" label="Disable"/>
</form:select></td>
</tr>
</c:forEach>
</tbody>
</table>
</td>
</tr>
<tr align="center">
<td width="100" align="center"><B>
${savedMsg}
</B>
</td>
</tr>
</form:form>
</table>
Even though this thread is older, For the benefit of others who is in need of this.
Let me explain with a minimal code and User example with firstName, email, userName and gender fields so that people won't get confused with bigger code.
Consider you are sending 3 empty users in usersList from controller this will creates 3 empty rows. If you inspect/view page source you will see
Rows(<input> tags) with different id's like list0.firstName
list1.firstName
Rows(<input> tags) with different names like list[0].firstName
list[1].firstName
Whenever form is submitted id's are not considered by server(added for only for helping client side validations), but name attribute will be interpreted as request parameter and are used to construct your modelAttribute, hence attribute names are very important while inserting rows.
Adding row
So, How to construct/append new rows?
If i submit 6 users from UI, controller should receive 6 user object from usersList. Steps to achieve the same is given below
1. Right click -> view page source. You will see rows like this(you can see *[0].* in first row and *[1].* in second row)
<tr>
<td><input id="list0.firstName" name="list[0].firstName" type="text" value=""/></td>
<td><input id="list0.email" name="list[0].email" type="text" value=""/></td>
<td><input id="list0.userName" name="list[0].userName" type="text" value=""/></td>
<td>
<span>
<input id="list0.gender1" name="list[0].gender" type="radio" value="MALE" checked="checked"/>Male
</span>
<span>
<input id="list0.gender2" name="list[0].gender" type="radio" value="FEMALE"/>Female
</span>
</td>
</tr>
<tr>
<td><input id="list1.firstName" name="list[1].firstName" type="text" value=""/></td>
<td><input id="list1.email" name="list[1].email" type="text" value=""/></td>
<td><input id="list1.userName" name="list[1].userName" type="text" value=""/></td>
<td>
<span>
<input id="list1.gender1" name="list[1].gender" type="radio" value="MALE" checked="checked"/>Male
</span>
<span>
<input id="list1.gender2" name="list[1].gender" type="radio" value="FEMALE"/>Female
</span>
</td>
</tr>
Copy first row and construct a javascript string and replace '0' with variable name index. As given in below sample
'<tr>'+
'<td><input id="list'+ index +'.firstName" name="list['+ index +'].firstName" type="text" value=""/></td>'+
'<td><input id="list'+ index +'.email" name="list['+ index +'].email" type="text" value=""/></td>'+
...
'</tr>';
Append the constructed row to the <tbody>. Rows get added in UI also on submission of form newly added rows will be received in controller.
Deleting row
Deleting row is little bit complicated, i will try to explain in easiest way
Suppose you added row0, row1, row2, row3, row4, row5
Deleted row2, row3. Do not just hide the row but remove it from the
DOM by catching event.
Now row0,row1,row4,row5 will get submitted but in the controller your
userList will have 6 user object but user[2].firstName will be null
and user[3].firstName will be null.
So in your controller iterate and check for null and remove the
user.(Use iterator don't use foreach to remove user object)
Posting code to benefit beginners.
// In Controller
#RequestMapping(value = "/app/admin/add-users", method = RequestMethod.GET)
public String addUsers(Model model, HttpServletRequest request)
{
List<DbUserDetails> usersList = new ArrayList<>();
ListWrapper userListWrapper = new ListWrapper();
userListWrapper.setList(usersList);
DbUserDetails user;
for(int i=0; i<3;i++)
{
user = new DbUserDetails();
user.setGender("MALE"); //Initialization of Radio button/ Checkboxes/ Dropdowns
usersList.add(user);
}
model.addAttribute("userListWrapper", userListWrapper);
model.addAttribute("roleList", roleList);
return "add-users";
}
#RequestMapping(value = "/app/admin/add-users", method = RequestMethod.POST)
public String saveUsers(#ModelAttribute("userListWrapper") ListWrapper userListWrapper, Model model, HttpServletRequest request)
{
List<DbUserDetails> usersList = userListWrapper.getList();
Iterator<DbUserDetails> itr = usersList.iterator();
while(itr.hasNext())
{
if(itr.next().getFirstName() == null)
{
itr.remove();
}
}
userListWrapper.getList().forEach(user -> {
System.out.println(user.getFirstName());
});
return "add-users";
}
//POJO
#Entity
#Table(name = "userdetails")
#XmlRootElement(name = "user")
public class DbUserDetails implements Serializable
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String firstName;
private String userName;
private String email;
private String gender;
//setters and getters
}
//list wrapper
public class ListWrapper
{
private List<DbUserDetails> list;
//setters and getters
}
In JSP
<form:form method="post" action="${pageContext.request.contextPath}/app/admin/add-users" modelAttribute="userListWrapper">
<table class="table table-bordered">
<thead>
<tr>
<th><spring:message code="app.userform.firstname.label"/></th>
<th><spring:message code="app.userform.email.label"/></th>
<th><spring:message code="app.userform.username.label"/></th>
<th><spring:message code="app.userform.gender.label"/></th>
</tr>
</thead>
<tbody id="tbodyContainer">
<c:forEach items="${userListWrapper.list}" var="user" varStatus="loop">
<tr>
<td><form:input path="list[${loop.index}].firstName" /></td>
<td><form:input path="list[${loop.index}].email" /></td>
<td><form:input path="list[${loop.index}].userName" /></td>
<td>
<span>
<form:radiobutton path="list[${loop.index}].gender" value="MALE" /><spring:message code="app.userform.gender.male.label"/>
</span>
<span>
<form:radiobutton path="list[${loop.index}].gender" value="FEMALE" /><spring:message code="app.userform.gender.female.label"/>
</span>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<div class="offset-11 col-md-1">
<button type="submit" class="btn btn-primary">SAVE ALL</button>
</div>
</form:form>
Javascript needs to be included in JSP
var currentIndex = 3; //equals to initialRow (Rows shown on page load)
function addRow()
{
var rowConstructed = constructRow(currentIndex++);
$("#tbodyContainer").append(rowConstructed);
}
function constructRow(index)
{
return '<tr>'+
'<td><input id="list'+ index +'.firstName" name="list['+ index +'].firstName" type="text" value=""/></td>'+
'<td><input id="list'+ index +'.email" name="list['+ index +'].email" type="text" value=""/></td>'+
'<td><input id="list'+ index +'.userName" name="list['+ index +'].userName" type="text" value=""/></td>'+
'<td>'+
'<span>'+
'<input id="list'+ index +'.gender1" name="list['+ index +'].gender" type="radio" value="MALE" checked="checked"/>Male'+
'</span>'+
'<span>'+
'<input id="list'+ index +'.gender'+ index +'" name="list['+ index +'].gender" type="radio" value="FEMALE"/>Female'+
'</span>'+
'</td>'+
'</tr>';
}

Categories