Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an object from front-end to Struts 2

I am trying to send value of a field to Struts2 back-end through JavaScript but it returns NullpointerException.

<input type="hidden" id="employee.payslip.id" name="employee.payslip.id" value="5"/>
....

Once form is submitted the request will be sent to the following JavaScript method to be sent to back-end.

 function payslipPayment(){

     var formValues = $('#myform').serialize();
     ....
     xmlhttp.open("get","../payslip/pay?"+formValues,false);
     xmlhttp.send();

 }

the request will be created and sent as following

http://localhost/payslip/pay/employee.payslip.id=5&employee.payslip.year=2013&....

But in back-end when I try to show the value it returns NullPointerException.

Java:

public class payslip {

 private Employee employee;

 public String pay{
    System.out.println("Id:"+employee.payslip.id):
    System.out.println("Year:"+employee.payslip.year;
    ...
 }

 getter and setter 

}

Classes:

public class Employee {
   private Payslip payslip;
   ....
   getter and setter
}

public class Payslip{
  private long id;
  ...
  getter and setter
}
like image 543
J888 Avatar asked Oct 31 '13 01:10

J888


People also ask

How Struts 2 Works?

In struts 2 the FilterDispatcher is the Front Controller. Based on the request url and it's mapping in the struts. xml the appropriate action class to be executed is decided. Before the Action class is executed the request is passed through the interceptors.


2 Answers

Null pointer exception means employee or payslip is not initialized. If youre using struts2 then using param interceptor and model driven approach should solve your issue.

like image 178
Code2Interface Avatar answered Sep 28 '22 23:09

Code2Interface


  • You need to convert your form to json (like here) and send to the back end
  • Then - in java you need to deserialize the json to a java object (for example, with Jackson)
like image 37
Alexey Grigorev Avatar answered Sep 28 '22 23:09

Alexey Grigorev