1

i'm using the below code for getting the json using struts2-hibernate, In the method getZone i used HttpServletResponse response= (HttpServletResponse) ActionContext.getContext().get(StrutsStatics.HTTP_RESPONSE); for returning the json. The code works fine, but i'm a bit confused and would like to know whether there is any other in struts2 in which we can achieve the same job, like using some other struts2 in-built method for HttpServletResponse.

Can anyone please tell me some solution for this

public void getZone() {
HttpServletResponse response= (HttpServletResponse) ActionContext.getContext().get(StrutsStatics.HTTP_RESPONSE);
try {
JSONObject zoneAreas = Hibernateclass.getZone(Id, organId);
response.getWriter().write(zoneAreas.toString());
} catch (IOException e) {
e.printStackTrace();
}
}

2 Answers2

1

In Struts2, you can use the following two ways to get the HttpServletResponse Object

1) Access HttpServletResponse via ServletActionContext

public String execute() {
        HttpServletResponse response = ServletActionContext.getResponse();

        return "SUCCESS";
    }

2) Access HttpServletResponse by implementing the ServletResponseAware interface and override the setServletResponse() method.

public class LoginAction implements ServletResponseAware{

    HttpServletResponse response;

    //business logic
    public String execute() {
        Locale locale = getServletResponse().getLocale();
        return "SUCCESS";
    }

    public void setServletResponse(HttpServletResponse response) {
        this.response = response;
    }
    public HttpServletResponse getServletResponse() {
        return this.response;
    }   
}

In Struts 2 documentation, it is recommended to use ServletResponseAware

Keerthivasan
  • 12,760
  • 2
  • 32
  • 53
  • In the first one, you access the HttpServletResponse from ServletActionContext , whereas in using ServletResponseAware, you have marked this class as a subscriber so the response is set during interception of response. One more thing, Unit testing will be difficult in using ServletResponseAware – Keerthivasan Oct 18 '13 at 05:09
  • hey do have any idea regarding this question http://stackoverflow.com/questions/19361833/struts2-hibernate3-jasper-report-5-0-getting-blank-report............for so many days i'm searching for a solution to that –  Oct 18 '13 at 05:11
  • Just answered your question, This is just my view. hope this helps. – Keerthivasan Oct 18 '13 at 05:49
0

You could implement the ServletResponseAware interface in your action class. This will make the framework give you the response.

Dev Blanked
  • 8,555
  • 3
  • 26
  • 32