not able to bind property in spring form - java

I have class User and userRole, I need to bind UserRole object in User
i tried below code
UserRole.java
public class UserRoleBean {
private Integer role_id;
private String roleName;
private String roleDesc;
//getter setter
}
User.java
public class UserBean {
private Integer userId;
private String firstName;
private String lastName;
private Date dob;
private String emailAddr;
private String mobileNo;
private Integer balance;
private String password;
private UserRoleBean roleBean;
//getter and setter;
}
AddUser.jsp
<form:form method="POST" action="saveUser.html" modelAttribute="userBean">
<table>
<tr>
<td><form:label path="userId">User ID:</form:label></td>
<td><form:input path="userId" value="${user.userId}" readonly="true"/></td>
</tr>
<tr>
<td><form:label path="firstName">First Name:</form:label></td>
<td><form:input path="firstName" value="${user.firstName}"/></td>
</tr>
<tr>
<td><form:label path="lastName">Last Name :</form:label></td>
<td><form:input path="lastName" value="${user.lastName}"/></td>
</tr>
<tr>
<td><form:label path="emailAddr">Email Address :</form:label></td>
<td><form:input path="emailAddr" value="${user.emailAddr}" readonly="false"/></td>
</tr>
<tr>
<td><form:label path="dob">Date Of Birth:</form:label></td>
<td><form:input path="dob" /></td>
</tr>
<tr>
<td><form:label path="mobileNo">Mobile No :</form:label></td>
<td><form:input path="mobileNo" value="${user.mobileNo}"/></td>
</tr>
<tr>
<td><form:label path="password">Password:</form:label></td>
<td><form:password path="password" value="${user.password}"/></td>
</tr>
<tr>
<td><form:label path="balance">Balance:</form:label></td>
<td><form:input path="balance" value="${user.balance}"/></td>
</tr>
<tr>
<td><form:label path="roleBean">Select Role:</form:label></td>
<td>
<form:select path="roleBean">
<form:option value="0" label="Select" />
<form:options items="${forRoles}" itemValue="role_id" itemLabel="roleName" />
</form:select>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="${cap}"/></td>
</tr>
</table>
</form:form>
Other Property is bind but roleBean unable to bind, how to do this,
any help would be appreciated

You have to set each property of roleBean seperately like you were doing for User object.
While setting any property of roleBean use roleBean.role_id for Id, `roleBean.roleName' for 'roleName'.
Like your path for roleName is <form:select path="roleBean"> but it should be <form:select path="roleBean.roleName"> if its for roleName. Same goes for other attributes.

Related

How to remove multiple rows via checkbox

I am new to spring and I need to be able to delete the selected rows by checkbox. How can I delete multiple rows from the database? I am using Thymeleaf as view.
Here is my code:
HTML
<div class="col-md-12">
<table class="table" id="tableImport">
<thead>
<tr>
<th scope="col">Remove</th>
<th scope="col">Debt Age Rule</th>
<th scope="col">Reminder</th>
<th scope="col">Frequency</th>
<th scope="col">Reorder</th>
</tr>
</thead>
<tbody>
<tr th:each="configCampaign:${listConfigCampaigns}">
<td>
<input type="checkbox" name="my-checkbox">
</td>
<td th:text="${configCampaign.debtagerule}"></td>
<td th:text="${configCampaign.remindebttype}"></td>
<td th:text="'Every '+${configCampaign.every} + ' ' + ${configCampaign.unit}"></td>
<td></td>
</tr>
</tbody>
</table>
<div class="col-md-12" style="text-align: center">
<input class="btn btn-primary" type="button" value="- Remove Selected Action(s)"/>
</div>
</div>
This table shows me data from an arrayList in memory, nothing with a database, I need to remove those selected objects from the array. At the moment I have my controller like this
Entity
private int configid;
private String debtagerule;
private String remindebttype;
private int every;
private String unit;
private boolean selected;
//getters and setters
In addition to the above, this is the controller with which I am currently working
Controller
#GetMapping("/deleteConfigureCampaign")
public String deleteConfig(#ModelAttribute ConfigCampaign configCampaign, Model model) {
listConfigCampaigns.remove(configCampaign);
return "redirect:/configureCampaign";
}
In Spring Boot, You have to use JpaRepository<> for delete data from database and need to understand structure of Spring Boot project.
Here is sturcture of Spring Boot project:
Entity -> Repository -> Service -> Controller -> View.
Here down is code:
Entity
#Table(name = "config_master")
public class ConfigCampaign {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer configid;
private String debtagerule;
private String remindebttype;
private Integer every;
private String unit;
private boolean selected;
// Constructor, Getter and Setter
}
Repository
Use of #Modifying annotation: It is used to enhance the #Query annotation so that we can execute not only SELECT queries, but also INSERT, UPDATE, DELETE, and even DDL queries
#Repository
public interface ConfigRepo extends JpaRepository<ConfigCampaign, Integer>{
#Modifying
#Transactional
#Query(nativeQuery = true, value = "DELETE FROM config_master WHERE configid IN(?1)")
void delConfig(List<Integer> configId);
}
Service
#Service
public class PojoServiceImpl{
#Autowired
private ConfigRepo configRepo;
#Override
public void delConfig(Integer[] configId) {
configRepo.delConfig(Arrays.asList(configId));
}
}
Controller
// Show table of Config Campaign
#RequestMapping(value = "/showconfig", method = RequestMethod.GET)
public String getConfig(Model mdl)
{
List<ConfigCampaign> getConfig = pojoService.getAllConfig();
mdl.addAttribute("config", getConfig);
return "showConfigCampaign";
}
// Delete item from Config Campaign
#RequestMapping(value = "/delcampaign", method = RequestMethod.GET)
public String deleteConfig(#RequestParam("cid") Integer[] configId)
{
pojoService.delConfig(configId);
return "redirect:/showconfig";
}
showConfigCampaign
You have to add configData.configid in checkbox.
<form th:action="#{/delcampaign}" th:object="${sconfig}">
<div class="container">
<div class="row">
<div class="col-sm-12">
<table class="table" style="text-align: center">
<thead>
<tr>
<th scope="col">Remove</th>
<th scope="col">Debt Age Rule</th>
<th scope="col">Reminder</th>
<th scope="col">Frequency</th>
</tr>
</thead>
<tbody>
<tr th:each="configData: ${config}">
<td><input type="checkbox" name="cid" th:value="${configData.configid}"/></td>
<td th:text="${configData.debtagerule}"></td>
<td th:text="${configData.remindebttype}"></td>
<td th:text="${configData.every}"></td>
</tr>
</tbody>
</table>
<input type="submit" value="Delete Users" />
</div>
</div>
</div>
</form>

How to use c:foreach to list a list of object inside another class.

One of my Object have a list of another object in it. how can i use to get the list of superperson out. Any Idea or help would be appreciated. Thanks
<table id="contactTable" class="table table-hover" >
<tr>
<th width="10%">Date</th>
<th width="10%">Supers</th>
<th width="50">Location Seen</th>
<th width="20%"></th>
<th width="30%"></th>
</tr>
<tr>
<td>
Date: <c:out value="${sighting.date}"/>
</td>
<td>
Super Person: <c:out value="${sighting.superPerson.name}"/>
</td>
<td>
Location: <c:out value="${sighting.location.locationName}"/>
</td>
</table>
//class
public class Sighting {
private int sightingId;
private String sighting;
private String description;
#DateTimeFormat(iso = ISO.DATE)
private LocalDate date;
private Location location;
private List<SuperPerson> superPerson = new ArrayList<>();
you can use jstl forEach tag
here
https://beginnersbook.com/2013/11/jstl-cforeach-and-cfortokens-core-tags/

org.apache.jasper.JasperException: An exception occurred processing JSP page path

org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/admissionForm.jsp at line 33
Getting error on line 33. I'm new to Spring MVC and cannot figured out this error
:
30: <table>
31: <tr>
32: <td>Customer Name :</td>
33: <td><form:input path="studentName" /></td>
34: <td><form:errors path="studentName" cssClass="error" /></td>
35: </tr>
36: <tr>
Model Class
#Entity
public class Student {
#NotEmpty
private String studentName;
#Size(min=2,max=43)
private String major;
private Long studentMobile;
private Date studentDOB;
private ArrayList<String> studentSkills;
private Address studentAddress;
}
Controller
#RequestMapping(value = "/admissionForm", method = RequestMethod.GET)
public ModelAndView addmissionForm(){
ModelAndView mv = new ModelAndView("admissionForm");
return mv;
}
#RequestMapping(value = "/submitAdmissionForm" , method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(#Valid #ModelAttribute("student1") Student student1, BindingResult result){
if(result.hasErrors()){
ModelAndView model1 = new ModelAndView("admissionForm");
return model1;
}
ModelAndView mv = new ModelAndView("admissionSuccess");
return mv;
}
JSP
<h2> SignUp Form - JSR303 #Valid example</h2>
<form:form method="POST" modelAttribute="student1" action="/submitAdmissionForm">
<form:errors path="*" cssClass="errorblock" element="div" />
<table>
<tr>
<td>Customer Name :</td>
<td><form:input path="studentName" /></td>
<td><form:errors path="studentName" cssClass="error" /></td>
</tr>
<tr>
<td>Customer Age :</td>
<td><form:input path="major" /></td>
<td><form:errors path="major" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>

Binding nested objects in SPRING MVC

I am new to SPRING MVC. I am not getting all the details of employee which contains phone and address object as well. Actually, those object are not being binded with employee.
Follow the code:
//(Controller)
EmployeeController.java
#Controller
#RequestMapping(value = "/employee")
public class EmployeeController {
#Autowired
EmployeeService employeeService;
#RequestMapping("/employee")
public ModelAndView registerEmployeer(#ModelAttribute Employee employee) {
Map<String, Object> modelMap = new HashMap<>();
modelMap.put("employee", new Employee());
return new ModelAndView("employee", modelMap);
}
#RequestMapping("/add")
public String addemployee(#ModelAttribute Employee employee) {
employeeService.save(employee);
return "result";
}
#ModelAttribute("phoneTypeList")
public Map<String,String> populatePhoneTypeList()
{
return Phone.getPhoneTypes();
}
#ModelAttribute("addressTypeList")
public Map<String,String> populateAddressTypeList()
{
return Address.getAddressTypes();
}
}
//Form which takes employee details
employee.jsp
<h2>Employee Information</h2>
<form:form method="POST" action="employee/add"
modelAttribute="employee">
<table>
<tr>
<td><form:label path="ssn">SSN</form:label></td>
<td><form:input path="ssn" /></td>
</tr>
<tr>
<td><form:label path="firstname">First Name</form:label> </td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td><form:label path="lastname">Last Name</form:label></td>
<td><form:input path="lastname" /></td>
</tr>
<tr>
<td><form:label path="dob">Date of Birth</form:label></td>
<td><form:input path="dob" /></td>
</tr>
<tr>
<td><form:label path="emailid">Email</form:label></td>
<td><form:input path="emailid" /></td>
</tr>
<tr>
<td>Phone Type:</td>
<td><form:select path="phoneList[0].phonetype" multiple="false">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${phoneTypeList}" />
</form:select></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td><form:label path="phoneList[0].phoneno">Phone</form:label></td>
<td><form:input path="phoneList[0].phoneno" /></td>
</tr>
<tr>
<td>Address Type:</td>
<td><form:select path="addressList[0].addresstype"
multiple="false">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${addressTypeList}" />
</form:select></td>
<tr>
<td><form:label path="addressList[0].street">Street</form:label></td>
<td><form:input path="addressList[0].street" /></td>
</tr>
<tr>
<td><form:label path="addressList[0].city">City</form:label></td>
<td><form:input path="addressList[0].city" /></td>
</tr>
<tr>
<td><form:label path="addressList[0].state">State</form:label></td>
<td><form:input path="addressList[0].state" /></td>
</tr>
<tr>
<td><form:label path="addressList[0].zip">Zip</form:label></td>
<td><form:input path="addressList[0].zip" /></td>
</tr>
<tr>
<td><form:label path="addressList[0].country">Country</form:label></td>
<td><form:input path="addressList[0].country" /></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="Submit" /></td>
</tr>
</table>
</form:form>
//Result after submitting form
result.jsp
<h2>Submitted Employee Information</h2>
<table>
<tr>
<td>SSN</td>
<td>${employee.ssn}</td>
</tr>
<tr>
<td>First Name</td>
<td>${employee.firstname}</td>
</tr>
<tr>
<td>Last Name</td>
<td>${employee.lastname}</td>
</tr>
<tr>
<td>Date of Birth</td>
<td>${employee.dob}</td>
</tr>
<tr>
<td>Email</td>
<td>${employee.emailid}</td>
</tr>
<tr>
<td>Phone Type</td>
<td>${employee.phoneList[0].phonetype}</td>
</tr>
<tr>
<td>Phone</td>
<td>${phoneList[0].phoneno}</td>
</tr>
<tr>
<td>Address Type</td>
<td>${addressList.addressTypeList}</td>
</tr>
<tr>
<td>Street</td>
<td>${addressList.street}</td>
</tr>
<tr>
<td>City</td>
<td>${addressList.city}</td>
</tr>
<tr>
<td>State</td>
<td>${addressList.state}</td>
</tr>
<tr>
<td>Zip</td>
<td>${addressList.zip}</td>
</tr>
<tr>
<td>Country</td>
<td>${addressList.country}</td>
</tr>
</table>
//my employee bean looks like this
employee.java
public class Employee {
private List<Phone> phoneList = new ArrayList<Phone>();
private List<Address> addressList = new ArrayList<Address>();
private long ssn;
private String firstname;
private String lastname;
private String dob;
private String emailid;
public long getSsn() {
return ssn;
}
public void setSsn(long ssn) {
this.ssn = ssn;
}
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 getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public void addPhone(Phone ph) {
phoneList.add(ph);
}
public void addAddress(Address ad) {
addressList.add(ad);
}
public void setPhoneList(List<Phone> phoneList) {
this.phoneList = phoneList;
}
public List<Phone> getPhoneList() {
return phoneList;
}
public List<Address> getAddressList() {
return addressList;
}
public void setAddressList(List<Address> adList) {
this.addressList = adList;
}
}
I can get only those details of employee like ssn, first name, last name etc but not phone type, phone no, address details which are the field of another objects. My assumption is the binding is not working here. Any idea?
I had a similar problem, solved by removing this line:
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
before the #ElementCollection that was not copied.
You are missing "employee" as prefix & index in list elements when reading them.
<tr>
<td>Phone</td>
<td>${employee.phoneList[0].phoneno}</td>
</tr>
<tr>
<td>Address Type</td>
<td>${employee.addressList[0].addressTypeList}</td>
</tr>
<tr>
<td>Street</td>
<td>${employee.addressList[0].street}</td>
</tr>
<tr>
<td>City</td>
<td>${employee.addressList[0].city}</td>
</tr>
<tr>
<td>State</td>
<td>${employee.addressList[0].state}</td>
</tr>
<tr>
<td>Zip</td>
<td>${employee.addressList[0].zip}</td>
</tr>
<tr>
<td>Country</td>
<td>${employee.addressList[0].country}</td>
</tr>

#Valid (jsr 303) not working in Spring mvc 3.0

I'm trying to achieve the JSR 303 bean validation in Spring 3.0 by using a simple login use case. The problem is if I submit the form without any value the validation is not happening (i.e the BindingResult method hasErrors() always returning 'false' and printing I'm cool !. Following is the code snippet:
#Controller
public class AnnotatedController {
#RequestMapping(value = "login")
public String validateLogin(#Valid LoginForm loginForm, BindingResult result, HttpServletRequest request) {
if(result.hasErrors())
System.out.println("Got Errors !");
else
System.out.println("I'm cool !");
return "login";
}
}
The bean looks like this :
public class LoginForm {
#NotEmpty
private String userName;
#Size(min=2, max=3)
private String password;
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;
}
}
Finally the view:
<table>
<form:form action="login.htm" modelAttribute="loginForm">
<tr>
<td>User :</td>
<td><form:input path="userName" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:input path="password" /></td>
</tr>
<tr><td><input type="submit" value="Ok"> </tr>
</form:form>
</table>
What am I missing ?
Adding <mvc:annotation-driven/>in servlet context XML fixed the issue for me.
you are missing form error tag.use like
<table>
<form:form action="login.htm" commandName="logindetails">
<tr>
<td>User :</td>
<td><form:input path="userName" /></td>
<td><form:errors path="userName" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:input path="password" /></td>
<td><form:errors path="password" /></td>
</tr>
<tr><td><input type="submit" value="Ok"> </tr>
</form:form>
and also you have to maintain property file with error message.
NotEmpty.logindetails.userName = userName is required!
Range.logindetails.password= password value must be between 2 and 3
Example:
Click here

Categories