How to correctly bind checkbox to the object list in thymeleaf? - spring

My domain model consist of an Employee and Certificate. One Employee can reference/have many certificates (one-to-many relationship). The full list of certificates could be get from the certificateService.
To assign some special certificate to the employee I used th:checkbox element from thymeleaf as follow:
<form action="#" th:action="#{/employee/add}" th:object="${employee}" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" th:field="*{name}"></td>
</tr>
<tr>
<td>Certificate</td>
<td>
<th:block th:each="certificate , stat : ${certificates}">
<input type="checkbox" th:field="*{certificates}" name="certificates" th:value="${certificate.id]}"/>
<label th:text="${certificate.name}" ></label>
</th:block>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Add"/></td>
</tr>
</table>
</form>
Now when I'm trying to submit the HTML form I always get following error:
400 - The request sent by the client was syntactically incorrect.
My question is: How to correctly bind checkbox elements to the object list with thymeleaf?
Controller
#RequestMapping(value = "/add" , method = RequestMethod.GET)
public String add(Model model) {
model.addAttribute("employee",new Employee());
model.addAttribute("certificates",certificateService.getList());
return "add";
}
#RequestMapping(value = "/add" , method = RequestMethod.POST)
public String addSave(#ModelAttribute("employee")Employee employee) {
System.out.println(employee);
return "list";
}
Employee Entity
#Entity
#Table(name = "employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
private int id;
#Column(name = "Name")
private String name;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "emp_cert",
joinColumns = {#JoinColumn(name = "employee_id")},
inverseJoinColumns = {#JoinColumn(name = "certificate_id")})
private List<Certificate> certificates;
public Employee() {
if (certificates == null)
certificates = new ArrayList<>();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Certificate> getCertificates() {
return certificates;
}
public void setCertificates(List<Certificate> certificates) {
this.certificates = certificates;
}
#Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "certificates size = " + certificates.size() + " ]";
}
}
Certificate Entity
#Entity
#Table(name = "certificate")
public class Certificate {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "Id")
private int id;
#Column(name = "name")
private String name;
#ManyToMany(mappedBy = "certificates")
private List<Employee> employees;
public Certificate() {
if (employees == null)
employees = new ArrayList<>();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Certificate other = (Certificate) obj;
if (id != other.id)
return false;
return true;
}
}

I used a custom solution to solve this issue, i implemented it by sending an array of certificates id to controller and received it as requestParam . The require changes are defined below .
View
<tr>
<td>Certificate</td>
<td>
<th:block th:each="certificate : ${certificates}">
<input type="checkbox" name="cers" th:value="${certificate.id}"/>
<label th:text="${certificate.name}"></label>
</th:block>
</td>
</tr>
Controller
#RequestMapping(value = "/add" , method = RequestMethod.POST)
public String addSave(
#ModelAttribute("employee")Employee employee ,
#RequestParam(value = "cers" , required = false) int[] cers ,
BindingResult bindingResult , Model model) {
if(cers != null) {
Certificate certificate = null ;
for (int i = 0; i < cers.length; i++) {
if(certificateService.isFound(cers[i])) {
certificate = new Certificate();
certificate.setId(cers[i]);
employee.getCertificates().add(certificate);
}
}
for (int i = 0; i < employee.getCertificates().size(); i++) {
System.out.println(employee.getCertificates().get(i));
}
}

Can you check you Html Template syntax and change below line:
<input type="checkbox" th:field="*{certificates}" name="certificates" th:value="${certificate.id]}"/>
to:
<input type="checkbox" th:field="*{certificates}" name="certificates" th:value="${certificate.id}"/>

Related

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:";
}

Spring JPA - Dropdown list (Filled with data from another table)

I've a problem to insert data to table from my form.
So, I have a two table with relation ManyToOne.
TORDER and TSYSTEM.
I want to insert data to TORDER table via form in my .jsp page. Data for one field is from TSYSTEM table - System Name.
I was able to fill the dropdown list with data from the mentioned table but I have an error message when submitting the form and trying to insert data to TORDER Table.
Do you have any idea why could be wrong here?
My Order model class:
#Entity
#Table(name="TORDER")
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ORDER_ID")
private int orderId;
#ManyToOne(cascade = CascadeType.ALL, targetEntity=System.class)
#JoinColumn(name = "SYSTEM_ID", referencedColumnName = "SYSTEM_ID")
private int sysId;
#ManyToOne(cascade = CascadeType.ALL, targetEntity=System.class)
#JoinColumn(name = "SYSTEM_NAME", referencedColumnName = "SYSTEM_NAME")
private String systemName;
#Column(name="ORDER_DATE")
private String orderDate;
#Column(name="STATUS")
private String status;
#Column(name="COMMENT")
private String comment;
#Column(name="APPROVED_BY_MANAGER")
private String managerApproval;
#Column(name="APPROVED_BY_ADMIN")
private String adminApproval;
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public int getSystemId() {
return sysId;
}
public void setSystemId(int sysId) {
this.sysId = sysId;
}
public String getSystemName() {
return systemName;
}
public void setSystemName(String systemName) {
this.systemName = systemName;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getManagerApproval() {
return managerApproval;
}
public void setManagerApproval(String managerApproval) {
this.managerApproval = managerApproval;
}
public String getAdminApproval() {
return adminApproval;
}
public void setAdminApproval(String adminApproval) {
this.adminApproval = adminApproval;
}
}
System model:
#Entity
#Table(name="TSYSTEM")
public class System implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="SYSTEM_ID")
private int sysId;
#Column(name="SYSTEM_NAME")
private String systemName;
#Column(name="DESCRIPTION")
private String description;
#Column(name="GROUP_NAME")
private String groupName;
public int getSysId() {
return sysId;
}
public void setSysId(int sysId) {
this.sysId = sysId;
}
public String getSystemName() {
return systemName;
}
public void setSystemName(String systemName) {
this.systemName = systemName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
}
Controller methods:
#RequestMapping(value="/addOrder", method=RequestMethod.GET)
public ModelAndView addOrder() {
ModelAndView model = new ModelAndView();
Order order = new Order();
model.addObject("orderForm", order);
List<System> systemList = systemService.getAllSystemsName();
model.addObject("systemList", systemList);
model.setViewName("order_form");
return model;
}
#RequestMapping(value="/saveOrder", method=RequestMethod.POST)
public ModelAndView save(#ModelAttribute("orderForm") Order order) {
orderService.saveOrUpdate(order);
return new ModelAndView("redirect:/employee/orderList");
}
Repository methods to get all system names from TSYSTEM Table:
public interface SystemRepository extends CrudRepository<System, Integer> {
#Query("select a.systemName from System a")
public List<System> getAllSystemsName();
}
and finally my .jsp form:
<form:form modelAttribute="orderForm" method="post" action="${saveURL }" cssClass="form" >
<form:hidden path="orderId"/>
<table>
<tr>
<td>System Name</td>
<td><form:select path="systemName">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${systemList}" />
</form:select>
</td>
<td><form:errors path="systemName" cssClass="error" /></td>
</tr>
<tr>
<td><label>Komentarz</label></td>
<td><form:textarea path="comment" cssClass="form-control" id="comment"
title="Dodaj komentarz do zamówienia" /></td>
</tr>
<tr>
<td><label>Data zamówienia</label></td>
<td><form:input type="text" path="orderDate" cssClass="form-control"
id="orderDate" pattern="{2,}" title="Data zamówienia" required="required"/>
</td>
</tr>
<tr>
<td><button type="reset" class="btn btn-primary">Wyczyść dane</button>
</td>
<td><button type="submit" class="btn btn-primary">Zamów dostęp</button>
</td>
</tr>
</table>
</form:form>
and after form submit action i received and error:
2018-11-13 17:32:32.846 ERROR 7416 --- [nio-8090-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: Error accessing field [private int com.project.model.System.sysId] by reflection for persistent property [com.project.model.System#sysId] : 0; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int com.project.model.System.sysId] by reflection for persistent property [com.project.model.System#sysId] : 0] with root cause
java.lang.IllegalArgumentException: Can not set int field com.project.model.System.sysId to java.lang.Integer
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) ~[na:1.8.0_161]
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171) ~[na:1.8.0_161]
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58) ~[na:1.8.0_161]
at sun.reflect.UnsafeIntegerFieldAccessorImpl.getInt(UnsafeIntegerFieldAccessorImpl.java:56) ~[na:1.8.0_161]
at java.lang.reflect.Field.getInt(Field.java:574) ~[na:1.8.0_161]
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:62) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
Please post SYSTEM model. I think you need change System model with field sysId to Integer type. Because you set repository with model sysId is Integer.

Springboot and thymealf loop

hope you can help with this simple noob problem. I creating a Multiple choice question using springboot and thymeleaf.I am getting this error and hope you can help me write the controller method.
Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor' (learning:23)
Neither BindingResult nor plain target object for bean name 'options[0]' available as request attribute
<form method="post" th:action="#{/list}" >
<table>
<tr th:each="option, rowStat : *{a}">
<td><input type="radio" th:field="*{options[__${rowStat.index}__].ansA}" th:value="A"/></td>
<td><input type="radio" th:field="*{options[__${rowStat.index}__].ansB}" th:value="B"/></td>
</tr>
</table>
<input type="submit" value="ok"/>
</form>
Model object
#Entity
public class LearningStyle {
private int Qid;
private String question;
private String ansA;
private String ansB;
public LearningStyle(int qid, String question, String ansA, String ansB) {
Qid = qid;
this.question = question;
this.ansA = ansA;
this.ansB = ansB;
}
public LearningStyle(){}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "Qid", nullable = false, updatable = false)
public int getQid() {
return Qid;
}
public void setQid(int qid) {
Qid = qid;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnsA() {
return ansA;
}
public void setAnsA(String ansA) {
this.ansA = ansA;
}
public String getAnsB() {
return ansB;
}
public void setAnsB(String ansB) {
this.ansB = ansB;
}
}
Controller
public class LearningStyleController {
#Autowired
LearningStyleService learningstyleservice;
#RequestMapping("/list")
public String learningstyle(Model model) {
List<LearningStyle> a= learningstyleservice.findAll();
model.addAttribute("a",a);
return "learning";
}
#RequestMapping(value = "/list", method = RequestMethod.POST)
public String learn(#ModelAttribute("a") LearningStyle learningStyle, Model model) {
//code to get list of object
return "home";
}

Null value returned from jsp form:options to controller

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:

Error with NullPointerExcetion Native Method Accessor, Can give me a solution

i browse "http://localhost:8080/subject/form" for fill information in Subjectform.jsp, after will direct "http://localhost:8080/subject/add" for insert subject object in table subject. But it not insert subject object and encouter following error:
null<br/>
edu.java.spring.controller.SubjectController.addSubject(SubjectController.java:5
0)<br/>
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)<br/>
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)<br
/>
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.jav
a:43)<br/>
java.lang.reflect.Method.invoke(Method.java:497)<br/>
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHa
ndlerMethod.java:215)<br/>
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(I
nvocableHandlerMethod.java:132)<br/>
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMet
hod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)<br/>
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapt
er.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)<br/>
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapt
er.handleInternal(RequestMappingHandlerAdapter.java:689)<br/>
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(A
bstractHandlerMethodAdapter.java:83)<br/>
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.j
ava:938)<br/>
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.ja
va:870)<br/>
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet
.java:961)<br/>
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:86
3)<br/>
javax.servlet.http.HttpServlet.service(HttpServlet.java:707)<br/>
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:8
37)<br/>
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)<br/>
org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:801)<br/>
org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:587)<br/>
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)<br
/>
org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)<br/>
org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223
)<br/>
org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:112
6)<br/>
org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)<br/>
org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
<br/>
org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1060
)<br/>
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)<br
/>
org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerC
ollection.java:215)<br/>
org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java
:110)<br/>
org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:113)<
br/>
org.eclipse.jetty.server.Server.handle(Server.java:509)<br/>
org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:288)<br/>
org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:240)<br/>
org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:539)<br/>
org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:620)
<br/>
org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:540)<
br/>
java.lang.Thread.run(Thread.java:745)<br/>
Here file SubjectController.class
#Controller
public class SubjectController {
#Autowired
public StudentDAO studentDao;
public SubjectDao subjectDao;
#RequestMapping(value = "subject/form",method = RequestMethod.GET)
public ModelAndView subjectForm (){
ModelAndView model = new ModelAndView("SubjectForm", "subject", new Subject());
List<Student> students = studentDao.listStudents();
Map<Integer,String> map = new HashMap<Integer,String>();
for(int i=0;i<students.size();i++){
map.put(students.get(i).getId(), students.get(i).getName());
}
model.getModelMap().put("studentList",map);
return model;
}
#RequestMapping(value="subject/add",method = RequestMethod.POST)
public void addSubject(#Valid #ModelAttribute("subject")Subject subject){
// ModelAndView model = new ModelAndView("redirect:/subject/list");
subjectDao.insert(subject);
// return model;
}
Here file SubjectHibernateDaoImpl.class
public class SubjectHibernateDaoImpl implements SubjectDao {
#Autowired
public LocalSessionFactoryBean sessionFactory;
#Override
public void insert(Subject subject){
Session session = sessionFactory.getObject().openSession();
try {
session.save(subject);
session.flush();
} finally {
// TODO: handle finally clause
session.close();
}
}
public List<Subject> listSubject() {
// TODO Auto-generated method stub
Session session = sessionFactory.getObject().openSession();
Query query = session.createQuery("from Subject");
try {
return query.list();
} finally {
// TODO: handle finally clause
session.close();
}
}
Here file Subject.class
#Entity
#Table(name = "subject",uniqueConstraints={#UniqueConstraint(columnNames="id")})
public class Subject {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "title", nullable = false, length = 200)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name = "student", nullable = false)
public int getStudent() {
return student;
}
public void setStudent(int student) {
this.student = student;
}
#Column(name = "score", nullable = false)
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int id;
public String title;
public int student;
public int score;
}
Here file Subject.jsp
<html>
<head>
<title>Add New Subject Information</title>
</head>
<body>
<h2>Please Input Subject Information</h2>
<form:form method="POST" modelAttribute="subject" action="add">
<table>
<tr>
<td><form:label path="student">Student</form:label></td>
<td><form:input path="student" type = "number"/></td>
</tr>
<tr>
<td><form:label path="title">Title</form:label></td>
<td><form:input path="title"/></td>
</tr>
<tr>
<td><form:label path="score">Score</form:label></td>
<td><form:input path="score" type = "number"/></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Submit"/></td>
</table>
</form:form>
</body>
</html>
Looks like you forgot to add the #Autowired annotation. It's present for the studentDao but not for the subjectDao, resulting in that object not being initialized.

Resources