Pages

Sunday, December 25, 2011

Struts2 json plugin - Action class public method names with "get" prefix.

I recently figured out this, what I am going to explain you, and it can make a huge impact for an application. I am using struts 2 JSON plugin for an AJAX invocations to action class methods and to send a JSON response. Struts 2 JSON plugin serializes all the bean properties when sending a JSON response to the browser. Sometime, you may not know that, While serialization process, it invokes all the public method which are having “get” prefix in their method names. If we really don’t know about this, it can make a significant impact to our application’s performance and generates exceptions which are hard to figure out. I will explain how this can impact for an application. Look into the following two methods which are defined in ‘DepartmentAction’ class. Those tow method returns JSON response to the browser.

public String getAllEmployees() throws Exception {
    List<Employee> employees = departmentService.getDepartmentEmployees();
    setEmployees(employees);
    return JSON;
}
public String getActiveDepartmentsByLocationId() throws Exception { 
    List<Department> departmetns = departmentService.getActiveDepartmentsByLocationId(locationId);
    setDepartments(departmetns); 
    return JSON;
} 
Normally, When you want to get the list of departments for a given location id, you will invoke the method ‘getActiveDepartmentsByLocationId’ method with an AJAX request. When the function returns the JSON response, it serializes action class bean properties which causes to invoke "getAllEmployees" method also. That means, it invoke the relevant service method from “getAllEmployees” method also. But you only need to get the list of departments for a given location id. Can you guess the impact for the application?

If you put a break point in “getAllEmployees” method while invoking “getActiveDepartmentsByLocationId” method, You will understand this behavior. Normally, developers are used to give “get” prefix for action class methods. If you use struts2 JSON plugin, make sure not to use “get” prefix for public method names which are resulting JSON response. You can use “find” prefix instead.

0 comments:

Post a Comment

Share

Widgets