Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning text/plain in struts 1.x

Is it possible to return a single value of type String instead of forwarding to action in struts 1.x.

I got few similar questions here, and here.

In struts documentation they mentioned,

Both Struts 1 and Struts 2 can return any type of response.

But in all discussions they explained for struts 2.

Can anybody help me how can i do in struts1.x?

Update: Paul Vargas suggestion resolved my issue.

like image 519
Rajesh Avatar asked Mar 22 '23 22:03

Rajesh


1 Answers

Since you have an instance of javax.servlet.http.HttpServletResponse, you can write the text directly. e.g.:

public class HelloWorldAction extends Action {

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print("We are send text plain");

        return null;
    }

}

With this way, you can send JSON, XML or binaries.

If you are combining traditional requests and Ajax (e.g., with jQuery.ajax ), may be you want to check for send an full HTML page or a fragment, JSON, and so on, with:

private final boolean isAjaxRequest(final HttpServletRequest request) {
    final String header = request.getHeader("X-Requested-With");
    return header != null && header.equalsIgnoreCase("XMLHttpRequest");
}
like image 164
Paul Vargas Avatar answered Apr 02 '23 12:04

Paul Vargas