0

I would like to get a HTTPServletResponse of an Action on a jsp page, but i don't know how...

My ajax call on the jsp:

jQuery.ajax({
url : 'actionURL',
type: "POST",
data : {input: "example"},
dataType: "html",
success: function(response) {
alert(response);
if (response == 1) {
jQuery("#message").html("done!");
}
}
});

My Action class:

public class MyAction implements ServletResponseAware {

public final String execute() throws IOException {

        String return_code = "1";

        try {

            something...

        } catch (Exception e) {
            return_code = "0";
        }

        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(return_code);

        return "success";
    }
}

How can i access only the return_code variable on jsp? Because now in the script alerts the whole page HTML code as response... Thanks!

user3519240
  • 1
  • 1
  • 1

1 Answers1

2
  1. Your variable must be at class-level, with a Getter;
  2. It should be camelCase (returnCode instead of return_code), and potentially an Integer since it's containing a number;
  3. Don't write anything in the response, Struts will do it for you; this is an action, not a servlet;
  4. Never swallow exceptions;

    public class MyAction implements ServletResponseAware {
    
        private Integer returnCode;
    
        public Integer getReturnCode(){
            return returnCode;
        }
    
        public final String execute() throws IOException {    
            try {
                /* do something... */
                returnCode = 1;
            } catch (Exception e) {
                e.printStackTrace();
                returnCode = 0;
            }    
            return "success";
        }
    }
    
  5. In struts.xml, map your "success" result to a JSP containing only the printed out value:

    <%@ page contentType="text/html; charset=UTF-8"%>
    <%@ taglib prefix="s" uri="struts-tags.tld"%>    
    <s:property value="returnCode" />
    

    Then the returned JSP will be a single value. But this is bad practice, and can easily lead to mistakes (extra whitespaces, for example). Then change your approach and...

  6. Use Struts2 JSON plugin setting returnCode as root object (remember to change your dataType from html to json)

Community
  • 1
  • 1
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
  • Thanks a lot! Sorry, this was only a snippet from my code...I modified my ajax script to this: ...dataType: "json",... And the struts.xml: returnCode But now it throws Caused by: java.lang.IllegalArgumentException: application/json;charset=UTF-8 not valid compared to [text/html] – user3519240 Apr 10 '14 at 14:21
  • Please add this code and the full exception stacktrace to your question, so we'll be able to help you. BTW, it's good that you've gone the JSON way. – Andrea Ligios Apr 10 '14 at 14:56