Null value returned from jsp form:options to controller - spring

The value returned by the JSP page for the path constituency is NULL. I have opted for a drop down list to display all the possible constituencies that can be selected. I have elaborated on the problem below.
Here is the Person Class:
#Entity
#Table(name="person")
public class person{
#Id
#Column(name = "NIC")
private Integer NIC;
#Column(name= "firstname")
private String fname;
#Column(name= "lastname")
private String lname;
#ManyToOne
#JoinColumn(name= "constituency_id")
private constituency constituency;
#OneToOne
#JoinColumn(name="NIC")
private login log;
public person(){
this.NIC = 1234;
this.fname = "Undefined";
this.lname = "Undefined";
}
public person(String fname, String lname, Integer NIC) {
this.fname = fname;
this.lname = lname;
this.NIC = NIC;
}
public Integer getNIC() {
return this.NIC;
}
public void setNIC(Integer NIC) {
this.NIC = NIC;
}
public String getfname() {
System.out.println(this.fname);
return this.fname;
}
public void setfname(String name) {
this.fname = name;
}
public String getlname() {
return this.lname;
}
public void setlname(String lname) {
this.lname = lname;
}
public constituency getConstituency() {
return this.constituency;
}
public void setConstituency(constituency id) {
this.constituency = id;
}
public login getlogin() {
return this.log;
}
public void setlogin(login log) {
this.log = log;
}
#Override
public String toString() {
return this.lname + " : " + this.fname;
}
}
Here is the Constituency Class:
#Entity
#Table(name="constituency")
public class constituency {
#Column(name="address")
private String address;
#Column(name="name")
private String name;
#Id
#Column(name="constituency_id")
private Integer constituency_id;
#Column(name="noofvoters")
private Integer voters;
#OneToMany(mappedBy="constituency", cascade = {CascadeType.ALL})
private Set <person> persons;
public constituency(){
this.constituency_id = 0;
this.name = "Undefined";
this.address = "Undefined";
this.voters = 0;
}
public constituency(String name, String address, Integer voters, Integer id) {
this.name = name;
this.address = address;
this.voters = voters;
this.constituency_id = id;
}
public String getname() {
System.out.println(this.name);
return this.name;
}
public void setname(String name) {
this.name = name;
}
public String getaddress() {
System.out.println(this.address);
return this.address;
}
public void setaddress(String name) {
this.address = name;
}
public Integer getvoters() {
return this.voters;
}
public void setvoters(Integer voters) {
this.voters = voters;
}
public Integer getconstituency_id() {
return this.constituency_id;
}
public void setconstituency_id(Integer id) {
this.constituency_id = id;
}
#Override
public String toString() {
return this.name;
}
}
Here is the portion of the controller responsible for handling the operation:
#RequestMapping(value="/Add", method=RequestMethod.GET)
public String add(Model model){
List <constituency> constit = constituencyDAO.details();
model.addAttribute("message", "Add a person for voting");
model.addAttribute("per", new person());
model.addAttribute("constituency", constit);
return "Add";
}
#RequestMapping(value="/Add", method=RequestMethod.POST)
public ModelAndView addperson(#ModelAttribute("per") person per, BindingResult bind){
System.out.println("In controller");
System.out.println(per.getfname()+" First-name");
System.out.println(per.getConstituency()+" constituency");
return hello();
}
Finally, this is the portion of the JSP page with the form:select tag:
<div class = "form-group">
<label for = "element1" class="control-label col-xs-2">Constituency ID</label>
<div class="col-xs-10">
<form:select path="constituency" name="constituency">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${constituency}" itemValue="constituency_id" itemLabel="name" />
</form:select>
<p>Constituency ID</p>
</div>
</div>
Now, the problem is that even though the JSP page is able to successfully display the constituency attribute in the form:options, when the "per" model attribute is retrieved in the controller, the value for constituency and only constituency is NULL.
Below is the output in Eclipse.
The Form:
The output in the RequestMethod.POST:

Related

Spring validating a object before returning it in a function not working

I have a service, that gets an xml/json string, tries to read it as an pojo, then returns it. Then, I want to show the result in thymeleaf. I did that successfully, but - in the model I have validation annotations, but if I submit invalid information it accepts the value, although I validated the method. Here is my code:
Controller:
#Controller
public class ConvertController implements WebMvcConfigurer {
#Autowired
PrintJSON printJSON;
#Autowired
PrintXML printXML;
#Autowired
ReadJSON readJSON;
#Autowired
ReadXML readXML;
#GetMapping("/read")
public String showReadForm() {
return "read";
}
#PostMapping("/read")
public String read(#RequestParam(value = "convertFrom") String
convertFrom, String text, Model model){
if("json".equals(convertFrom)){
Book newBook = readJSON.read(text);
model.addAttribute("result", newBook);
return "converted";
}else if("xml".equals(convertFrom)){
Book newBook = readXML.read(text);
model.addAttribute("result", newBook);
return "converted";
}
return "read";
}
#GetMapping("/print")
public String showPrintForm(Book book){
return "convert";
}
#PostMapping("/print")
public String convert(#RequestParam(value = "convertTo") String
convertTo, #Valid Book book, Errors errors, Model model) {
if(errors.hasErrors()){
return "convert";
}
if("json".equals(convertTo)){
model.addAttribute("result", printJSON.getJSON(book));
return "converted";
}
if("xml".equals(convertTo)){
model.addAttribute("result", printXML.getXML(book));
return "converted";
}
return "convert";
}}
Service
public class ReadXML {
#Autowired
#Qualifier("XmlMapper")
XmlMapper xmlMapper;
#Valid
public Book read(String xml){
try{
#Valid Book book = xmlMapper.readValue(xml, Book.class);
return book;
}
catch(JsonProcessingException e){
e.printStackTrace();
return new Book();
}
}
}
Model
public class Book {
#NotEmpty
private String title;
private String description;
private Date publishDate;
private int ISBN;
private List<#Valid Author> authors;
#Override
public String toString(){
String bookString = String.format("Title: %s\nDescription: %s\nPublish Date: %s\nISBN: %s\nAuthor", title, description, publishDate, ISBN);
for(Author a : authors){
bookString += a.toString();
}
return bookString;
}
public String getTitle() {
return title;
}
public void setTitle(String title){
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description){
this.description = description;
}
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(String newPublishDate) throws ParseException {
Date publishDate = new SimpleDateFormat(Constants.dateFormat).parse(newPublishDate);
this.publishDate = publishDate;
}
public int getISBN() {
return ISBN;
}
public void setISBN(int ISBN){
this.ISBN = ISBN;
}
public void addAuthor(Author author) {
authors.add(author);
}
public List<Author> getAuthors(){
return authors;
}
}
Where is my problem???
Thank you!

Bidirectional OneToMany-ManyToOne Relationship referencing unsaved transient instance (Spring MVC - Thymeleaf)

new here. I'm new to Spring and Thymeleaf, I'm trying to learn by following a video and I don't know why I get the following exception (org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : org.launchcode.codingevents.models.Event.eventCategory -> org.launchcode.codingevents.models.EventCategory) when I try to creat an Event giving it an EventCategory in the Thymeleaf form. I tried cascading from one side, then from the other and then from both, but it didn't work.
I'll be immensely grateful with whoever helps me out.
Here's my code.
#MappedSuperclass
public abstract class AbstractEntity {
#Id
#GeneratedValue
private int id;
public int getId() {
return id;
}
#Override
public int hashCode() {
return Objects.hash(id);
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
AbstractEntity entity = (AbstractEntity) obj;
return this.id == entity.id;
}
#Entity
public class Event extends AbstractEntity {
#NotBlank(message = "Name is required")
#Size(min = 3, max = 50, message = "Name must be between 3 and 50 characters")
private String name;
#Size(max = 500, message = "Description too long!")
private String description;
#NotBlank(message = "Email is required")
#Email(message = "Invalid email. Try again")
private String contactEmail;
#ManyToOne
#NotNull(message = "Category is required")
private EventCategory eventCategory;
public Event() {
}
public Event(String name, String description, String contactEmail, EventCategory eventCategory) {
this.name = name;
this.description = description;
this.contactEmail = contactEmail;
this.eventCategory = eventCategory;
}
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 String getContactEmail() {
return contactEmail;
}
public void setContactEmail(String contactEmail) {
this.contactEmail = contactEmail;
}
public EventCategory getEventCategory() {
return eventCategory;
}
public void setEventCategory(EventCategory eventCategory) {
this.eventCategory = eventCategory;
}
#Override
public String toString() {
return name;
}
#Entity
public class EventCategory extends AbstractEntity implements Serializable {
#Size(min = 3, message = "Name must be at least 3 characters long")
private String name;
#OneToMany(mappedBy = "eventCategory")
private final List<Event> events = new ArrayList<>();
public EventCategory() {
}
public EventCategory(#Size(min = 3, message = "Name must be at least 3 characters long") String name) {
this.name = name;
}
public List<Event> getEvents() {
return events;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
#Controller
#RequestMapping("events")
public class EventController {
#Autowired
private EventRepository eventRepository;
#Autowired
private EventCategoryRepository eventCategoryRepository;
#GetMapping
public String displayAllEvents(#RequestParam(required = false) Integer categoryId, Model model) {
if (categoryId == null) {
model.addAttribute("title", "All Events");
model.addAttribute("events", eventRepository.findAll());
} else {
Optional<EventCategory> result = eventCategoryRepository.findById(categoryId);
if (!result.isPresent()) {
model.addAttribute("title", "Invalid Category Id: " + categoryId);
} else {
EventCategory category = result.get();
model.addAttribute("title", "Events in Category: " + category.getName());
model.addAttribute("events", category.getEvents());
}
}
return "events/index";
}
// Lives at /events/create
#GetMapping("create")
public String displayCreateEventForm(Model model) {
model.addAttribute("title", "Create Event");
model.addAttribute(new Event());
model.addAttribute("categories", eventCategoryRepository.findAll());
return "events/create";
}
// lives at /events/create
#PostMapping("create")
public String processCreateEventForm(#Valid #ModelAttribute("newEvent") Event newEvent, Errors errors, Model model) {
if (errors.hasErrors()) {
model.addAttribute("title", "Create Event");
return "events/create";
}
model.addAttribute("events", eventRepository.findAll());
eventRepository.save(newEvent);
return "redirect:";
}
// lives at /events/delete
#GetMapping("delete")
public String displayDeleteEventForm(Model model) {
model.addAttribute("title", "Delete Events");
model.addAttribute("events", eventRepository.findAll());
return "events/delete";
}
// lives at /events/delete
#PostMapping("delete")
public String processDeleteEventForm(#RequestParam(required = false) int[] eventIds) {
if (eventIds != null) {
for (int id : eventIds) {
eventRepository.deleteById(id);
}
}
return "redirect:";
}
}
Create Event
<nav th:replace="fragments :: navigation"></nav>
<form method="post" th:action="#{/events/create}" th:object="${event}">
<div class="form-group">
<label>Name
<input class="form-control" th:field="${event.name}">
</label>
<p class="error" th:errors="${event.name}"></p>
</div>
<div class="form-group">
<label>Description
<input class="form-control" th:field="${event.description}">
</label>
<p class="error" th:errors="${event.description}"></p>
</div>
<div class="form-group">
<label>Contact Email
<input class="form-control" th:field="${event.contactEmail}">
</label>
<p class="error" th:errors="${event.contactEmail}"></p>
</div>
<div class="form-group">
<label>Category
<select th:field="${event.eventCategory}">
<option th:each="eventCategory : ${categories}" th:value="${eventCategory.id}"
th:text="${eventCategory.name}">
</option>
</select>
<p class="error" th:errors="${event.eventCategory}"></p>
</label>
</div>
<div th:replace="fragments :: create-button"></div>
</form>
As per your code you are only trying to save Event entity and ignoring EventCategory.
You need to set Event to EventCategory as well as EventCategory to Event and make the cascade save.
First add cascade property in Event entity as below.
#ManyToOne(cascade = CascadeType.ALL)
#NotNull(message = "Category is required")
private EventCategory eventCategory;
Then in the Controller make the following changes.
#PostMapping("create")
public String processCreateEventForm(#Valid #ModelAttribute("newEvent") Event newEvent, Errors errors, Model model) {
if (errors.hasErrors()) {
model.addAttribute("title", "Create Event");
return "events/create";
}
model.addAttribute("events", eventRepository.findAll());
EventCategory eventCategory = newEvent.getEventCategory();
eventCategory.setEvent(newEvent);
eventRepository.save(newEvent);
return "redirect:";
}

org.springframework.beans.NotReadablePropertyException

In my web app, I want to build a registration form within which I wish to list all properties of a user's contact information that can be edited and saved. However, when I run my code, I get following error.
Any help will be greatly appreciated as I am new and learning as I go.
2019-01-03 17:09:58.705 ERROR 12223 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [An exception occurred processing JSP page /WEB-INF/views/enrollment/view.jsp at line 382
org.springframework.beans.NotReadablePropertyException: Invalid property 'contact' of bean class [com.intelo.model.Enrollment]: Bean property 'contact' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
Here is my view.jsp
<form:form id="editRegistration" action="/enrollment/action" modelAttribute="enrollment" method="post" enctype="multipart/form-data">
<input type="hidden" name="enrollmentId" value="${enrollment.id}">
...
<c:forEach items="${contacts}" var="contact">
<div class="form-group col-md-6">
<label class="control-label">First Name</label>
<form:input class="form-control" path="contact.firstName" disabled="${allowedActions.edit? 'false' : 'true'}"/>
</div>
</c:forEach>
Here is my EnrollmentControleller:
#GetMapping("/enrollment/view")
public String viewEnrollment(#ModelAttribute("enrollment") Enrollment enrollment, Model model,
#ModelAttribute("user") Member user)
{
StateManager stateManager = StateManager.getStateManager(enrollment);
model.addAttribute("hasActions", stateManager.allowedActions(user).size() > 0);
model.addAttribute("allowedActions", stateManager.allowedActionMap(user));
model.addAttribute("isAdministrator", stateManager.getRoleInContext(user).hasAdministratorPrivilege());
model.addAttribute("pageTitle", "View Enrollment");
RegistrationDetails registrationDetails = enrollment.getRegistrationDetails();
model.addAttribute("studentInformation", registrationDetails.getStudentInformation());
model.addAttribute("healthInformation", registrationDetails.getHealthInformation());
model.addAttribute("emergencyContact", registrationDetails.getEmergencyContact());
model.addAttribute("familyInformation", registrationDetails.getFamilyInformation());
model.addAttribute("schoolHistory", registrationDetails.getSchoolHistory());
model.addAttribute("contacts", registrationDetails.getContacts());
model.addAttribute("siblings", registrationDetails.getSiblings());
model.addAttribute("preferredSite", registrationDetails.getPreferredSite());
return "enrollment/view";
}
Enrollment class:
#Entity
#Table(name="enrollments")
#OnDelete(action = OnDeleteAction.CASCADE)
public class Enrollment extends ModelObject {
#JsonProperty("firstName")
private String firstName = "";
#JsonProperty("middleName")
private String middleName = "";
#JsonProperty("lastName")
private String lastName = "";
#JsonProperty("birthDate")
#DateTimeFormat(pattern="MM/dd/uuuu")
private LocalDate birthDate = LocalDate.now();
#JsonProperty("studentGrade")
private String studentGrade = null;
#JsonProperty("registrationDate")
#JsonDeserialize(using = LocalDateDeserializer.class)
#JsonSerialize(using = LocalDateSerializer.class)
#DateTimeFormat(pattern="MM/dd/uuuu")
private LocalDate registrationDate = LocalDate.now();
#JsonIgnore
#OneToOne(fetch=FetchType.LAZY, mappedBy="enrollment", cascade={CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE}, orphanRemoval=true)
#OnDelete(action = OnDeleteAction.CASCADE)
RegistrationDetails registrationDetails = null;
#JsonIgnore
#ManyToOne
#JoinColumn(name = "programId")
private Program program = null;
#JsonIgnore
#OrderBy("date")
#OneToMany (mappedBy = "enrollment", cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE})
#OnDelete(action = OnDeleteAction.CASCADE)
private List<AttendanceRecord> attendanceRecords = new ArrayList<AttendanceRecord>();
public Enrollment() {
super();
setType(this.getClass().getCanonicalName());
setState(State.DRAFT);
setRegistrationDetails(new RegistrationDetails());
}
public String getStudentGrade() {
return studentGrade;
}
public void setStudentGrade(String studentGrade) {
this.studentGrade = studentGrade;
}
public List<AttendanceRecord> getAttendance() {
return attendanceRecords;
}
public void addAttendanceRecord(AttendanceRecord attendanceRecord) {
attendanceRecords.add(attendanceRecord);
attendanceRecord.setEnrollment(this);
}
public void removeAttendanceRecord(AttendanceRecord attendanceRecord) {
attendanceRecords.remove(attendanceRecord);
attendanceRecord.setEnrollment(null);
}
public LocalDate getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(LocalDate registrationDate) {
this.registrationDate = registrationDate;
}
public Program getProgram() {
return program;
}
public void setProgram(Program program) {
this.program = program;
setParent(program);
}
#Override
public ParentContext getParentContext() {
return program;
}
public RegistrationDetails getRegistrationDetails() {
return registrationDetails;
}
public void setRegistrationDetails(RegistrationDetails registrationDetails) {
if (this.registrationDetails != null)
registrationDetails.setEnrollment(null);
this.registrationDetails = registrationDetails;
registrationDetails.setEnrollment(this);
}
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 getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
}
Here is my Contact class
#Embeddable
public class Contact {
String firstName = "";
String lastName = "";
String email = "";
String homePhone = "";
String dayPhone = "";
String cellPhone = "";
String relationship = "";
#Embedded
#AttributeOverrides({
#AttributeOverride(name="street", column=#Column(name="contact_street")),
#AttributeOverride(name="apartment", column=#Column(name="contact_apartment")),
#AttributeOverride(name="city", column=#Column(name="contact_city")),
#AttributeOverride(name="state", column=#Column(name="contact_state")),
#AttributeOverride(name="zipCode", column=#Column(name="contact_zipcode")),
#AttributeOverride(name="country", column=#Column(name="contact_country"))
})
Address address = new Address();
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHomePhone() {
return homePhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
public String getDayPhone() {
return dayPhone;
}
public void setDayPhone(String dayPhone) {
this.dayPhone = dayPhone;
}
public String getCellPhone() {
return cellPhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
public String getRelationship() {
return relationship;
}
public void setRelationship(String relationship) {
this.relationship = relationship;
}
public Address getAddress() {
return address;
}
}

ManyToMany select query is correct and the query is viewed in console. But I cant put values into jsp

I added many to many relationship to importers and agents table..data save successfully and middle table created...but i cannot retrieve data to my jsp ...How can i retrieve agents table data to my jsp.
My model is
package lk.slsi.domain;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "importers")
public class Importer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "importer_id")
private long importerId;
#NotEmpty
#Column(unique = true, nullable = false)
private String importerBrc;
private String importerVatNumber;
private String importerName;
private String importerAddress1;
private String importerAddress2;
private String importerAddress3;
private String importerCityName;
private String officePhoneNumber;
private String mobilePhoneNumber;
#Email
private String email;
#Email
private String optemail1;
#Email
private String optemail2;
public String getOptemail1() {
return optemail1;
}
public void setOptemail1(String optemail1) {
this.optemail1 = optemail1;
}
public String getOptemail2() {
return optemail2;
}
public void setOptemail2(String optemail2) {
this.optemail2 = optemail2;
}
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name = "importer_agents",
joinColumns = {#JoinColumn(name = "importerId")},
inverseJoinColumns = {#JoinColumn(name = "agentId")})
private List<Agent> agentList;
public String getImporterBrc() {
return importerBrc;
}
public void setImporterBrc(String importerBrc) {
this.importerBrc = importerBrc;
}
public String getImporterVatNumber() {
return importerVatNumber;
}
public void setImporterVatNumber(String importerVatNumber) {
this.importerVatNumber = importerVatNumber;
}
public String getImporterName() {
return importerName;
}
public void setImporterName(String importerName) {
this.importerName = importerName;
}
public String getImporterAddress1() {
return importerAddress1;
}
public void setImporterAddress1(String importerAddress1) {
this.importerAddress1 = importerAddress1;
}
public String getImporterAddress2() {
return importerAddress2;
}
public void setImporterAddress2(String importerAddress2) {
this.importerAddress2 = importerAddress2;
}
public String getImporterAddress3() {
return importerAddress3;
}
public void setImporterAddress3(String importerAddress3) {
this.importerAddress3 = importerAddress3;
}
public String getImporterCityName() {
return importerCityName;
}
public void setImporterCityName(String importerCityName) {
this.importerCityName = importerCityName;
}
public String getOfficePhoneNumber() {
return officePhoneNumber;
}
public void setOfficePhoneNumber(String officePhoneNumber) {
this.officePhoneNumber = officePhoneNumber;
}
public String getMobilePhoneNumber() {
return mobilePhoneNumber;
}
public void setMobilePhoneNumber(String mobilePhoneNumber) {
this.mobilePhoneNumber = mobilePhoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getImporterId() {
return importerId;
}
public void setImporterId(long importerId) {
this.importerId = importerId;
}
public List<Agent> getAgentList() {
return agentList;
}
public void setAgentList(List<Agent> agentList) {
this.agentList = agentList;
}
}
my agent table model is
package lk.slsi.domain;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
#Entity
#Table(name = "agents")
public class Agent {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "agent_id")
private long agentId;
#NotEmpty
#Column(unique = true, nullable = false)
private String nic;
private String vatNumber;
private String name;
private String agentAddress1;
private String agentAddress2;
private String agentAddress3;
private String agentCityName;
private String officePhoneNumber;
private String mobilePhoneNumber;
#Email
private String email;
public long getAgentId() {
return agentId;
}
public void setAgentId(long agentId) {
this.agentId = agentId;
}
public String getNic() {
return nic;
}
public void setNic(String nic) {
this.nic = nic;
}
public String getVatNumber() {
return vatNumber;
}
public void setVatNumber(String vatNumber) {
this.vatNumber = vatNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAgentAddress1() {
return agentAddress1;
}
public void setAgentAddress1(String agentAddress1) {
this.agentAddress1 = agentAddress1;
}
public String getAgentAddress2() {
return agentAddress2;
}
public void setAgentAddress2(String agentAddress2) {
this.agentAddress2 = agentAddress2;
}
public String getAgentAddress3() {
return agentAddress3;
}
public void setAgentAddress3(String agentAddress3) {
this.agentAddress3 = agentAddress3;
}
public String getAgentCityName() {
return agentCityName;
}
public void setAgentCityName(String agentCityName) {
this.agentCityName = agentCityName;
}
public String getOfficePhoneNumber() {
return officePhoneNumber;
}
public void setOfficePhoneNumber(String officePhoneNumber) {
this.officePhoneNumber = officePhoneNumber;
}
public String getMobilePhoneNumber() {
return mobilePhoneNumber;
}
public void setMobilePhoneNumber(String mobilePhoneNumber) {
this.mobilePhoneNumber = mobilePhoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
my repository is
package lk.slsi.repository;
import java.util.List;
import lk.slsi.domain.Importer;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
/**
* Created by ignotus on 2/8/2017.
*/
public interface ImporterRepository extends CrudRepository<Importer,Long> {
#Override
Importer save(Importer importer);
#Override
Importer findOne(Long importerId);
#Override
List<Importer> findAll();
#Override
void delete(Long aLong);
#Override
void delete(Importer importer);
#Override
void delete(Iterable<? extends Importer> iterable);
#Query("select u from Importer u where u.importerVatNumber = :importerVatNumber")
Importer getImporterByimporterVatNumber(#Param("importerVatNumber") String importerVatNumber);
#Query("select u from Importer u inner join u.agentList where u.importerId = :importerId")
List<Importer> findAgents(#Param("importerId") long importerId);
#Query("select u from Importer u where u.importerId = :importerId")
Importer getImporterByimporterID(#Param("importerId") long importerId);
}
my services is
public List<Importer> getAllIAgents(long importerId) {
return importerRepository.findAgents(importerId);
}
My controller is
#RequestMapping(path = "/viewImporter", method = RequestMethod.POST)
public String updateImporterAll(#RequestParam("importerId") long importerId, Model model) {
slsiLogger.info("Updating user with Id [{}]", importerId);
System.out.println("Importer id is " + importerId);
model.addAttribute("importerDetails", importerServices.getImporterByimporterID(importerId));
model.addAttribute("Agentsdetail", importerServices.getAllIAgents(importerId));
return "importerEdit";
}
Jsp is
<th width="15%">Registered Agents</th>
<c:forEach items="${Agentsdetail}" var="Agent">
<tr>
<td>${Agent.agentList.vatNumber}</td>
</tr>
/c:forEach>
</thead>
The query shows in netbeans console like this
Hibernate: select importer0_.importer_id as importer1_2_, importer0_.email as email2_2_, importer0_.importer_address1 as importer3_2_, importer0_.importer_address2 as importer4_2_, importer0_.importer_address3 as importer5_2_, importer0_.importer_brc as importer6_2_, importer0_.importer_city_name as importer7_2_, importer0_.importer_name as importer8_2_, importer0_.importer_vat_number as importer9_2_, importer0_.mobile_phone_number as mobile_10_2_, importer0_.office_phone_number as office_11_2_, importer0_.optemail1 as optemai12_2_, importer0_.optemail2 as optemai13_2_ from importers importer0_ inner join importer_agents agentlist1_ on importer0_.importer_id=agentlist1_.importer_id inner join agents agent2_ on agentlist1_.agent_id=agent2_.agent_id where importer0_.importer_id=?
How can i insert agent table values to my jsp.Please help me

javax.el.PropertyNotFoundException: Property 'UserName' not found

I have written a program to display some details entered in one form in another.Like I have a UserRegisteration.jsp where I am entering few details and UserAccount.jsp which has to display some of the entered details.I have created a model object UserDetails which has all the details of a particular code.
When I am running the project I am getting the propertynotfound exception.I have checked everything and couldn't find the reason behind it.I have the getters and setters methods in my model class.And using auto-binding feature using #modelattribute.Kindly let me know if I missed any code.
UserDetails.java
package com.bindu.myBankcontroller;
import java.util.ArrayList;
public class UserDetails {
private String UserName;
private String FirstName;
private String LastName;
private String EmailId;
private ArrayList<String> AccountType;
private ArrayList<String> gender;
private Long AccountNo;
private int age;
private String password;
Address address;
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getEmailId() {
return EmailId;
}
public void setEmailId(String emailId) {
EmailId = emailId;
}
public ArrayList<String> getAccountType() {
return AccountType;
}
public void setAccountType(ArrayList<String> accountType) {
AccountType = accountType;
}
public ArrayList<String> getGender() {
return gender;
}
public void setGender(ArrayList<String> gender) {
this.gender = gender;
}
public Long getAccountNo() {
return AccountNo;
}
public void setAccountNo(Long accountNo) {
AccountNo = accountNo;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Controller class,UserAccountController.java
package com.bindu.myBankcontroller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.web.servlet.ModelAndView;
import com.bindu.myBankcontroller.UserDetails;
#Controller
public class UserAccountController {
#ModelAttribute
public void addingCommonObjects(Model model1) {
model1.addAttribute("headerMessage", "MyBank, India");
}
#RequestMapping(value="/LoginForm.html", method = RequestMethod.GET)
public ModelAndView getAdmissionForm() {
ModelAndView model1 = new ModelAndView("LoginForm");
return model1;
}
#RequestMapping(value="/userRegistration.html", method = RequestMethod.GET)
public ModelAndView submitRegistrationForm() {
ModelAndView model1 = new ModelAndView("UserRegistration");
return model1;
}
#RequestMapping(value="/UserAccount.html", method = RequestMethod.POST)
public ModelAndView userAccountForm(#ModelAttribute("user") UserDetails user) {
System.out.println("User name:"+user.getUserName());
ModelAndView model1 = new ModelAndView("UserAccount");
return model1;
}
}
UserAccount.jsp
<html>
<body>
<h1>${headerMessage}</h1>
<h3>Congratulations!! you have successfully registered</h3>
<h2>Details submitted by you:: </h2>
<table>
<tr>
<td>User Name :</td>
<td>${user.UserName}</td>
</tr>
<tr>
<td>First Name :</td>
<td>${user.FirstName}</td>
</tr>
<tr>
<td>Last Name :</td>
<td>${user.LastName}</td>
</tr>
</table>
</body>
</html>
None of the related posts helped me in resolving this issue, so I have posted this one.
The problem is cause by the way you are accessing your property in jsp,
${user.UserName}
should instead be
${user.userName}
Same for the other expressions, you should lower case the first letter.
Behind the scenes the UserDetails is introspected and a map of properties is created, but the keys are based on your getter/setter methods, so lowercased (userName, firstName, lastName). In your JSP EL you're passing the key, and it is not matching any property on account of case difference
Your instance variables do not respect the java naming principles. Java variables should start with lower letter and use camel case capitalization.
Ex: userName, firstName, lastName,
and the corresponding getters would be getUserName(), getFirstName(), getLastName().
If you have the instance variable defined like this the jsp accessors will be obtained by stripping the get (or is, if the method returns a boolean) suffix and lower the first letter of the remaining method name: ${user.userName}, ${user.firstName}, ${user.lastName}.

Resources