将自定义对象从servlet传递给Jquery

时间:2014-03-19 14:41:54

标签: java jquery ajax servlets

我有一个servlet,我的目标是从流程请求中返回一个客户对象,然后我可以在我的jquery中访问该对象。有谁知道我怎么能这样做?

 e.g. myObject.getMethod()

Servlet代码:

 Customer loginResult;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            //request.setAttribute("customerFirstName", loginResult.getFirstName()); //String Value
            //request.setAttribute("customerID", loginResult.getCustomerID()); //IntegerValue
            out.println(loginResult);

        } finally {
            out.close();
        }
    }

JSP CODE:

<script type="text/javascript">
$().ready(function() {
    $('#submit').click(function() {

        var dataf = 'email=' + $('#email').val()
                + '&password=' + $('#password').val();
        $.ajax({
            url: "http://localhost:8080/RetailerGui/loginServlet",
            type: "get",
            data: dataf,
            success: function(data) {
            alert(data);

            }
        });
        return false;
    });
});
</script>

有人可以帮我解决这个问题,谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

由于您希望使用Servlet处理ajax请求,因此最好的办法是将自定义对象的数据写入响应中。我发现实现这一目标的更简单方法是使用JSON。有许多库处理从对象到字符串的JSON转换,反之亦然,我建议使用Jackson。这就是你的代码应该是这样的。

Servlet代码:

import com.fasterxml.jackson.databind.ObjectMapper;

@WebServlet("/loginServlet") //assuming you're using Servlet 3.0
public class YourServlet extends HttpServlet {

    //Jackson class that handles JSON marshalling
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    //login operation should be handled in POST
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        Customer loginResult = ...; //process data and get the loginResult instance
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        //marshalling the data of your loginResult in JSON format
        String json = OBJECT_MAPPER.writeValueAsString(loginResult);
        response.getWriter().write(json);
    }
}

Javascript代码:

<script type="text/javascript">
$().ready(function() {
    $('#submit').click(function() {
        var dataf = 'email=' + $('#email').val()
                + '&password=' + $('#password').val();
        $.ajax({
            url: "http://localhost:8080/RetailerGui/loginServlet",
            type: "post", //login action MUST be post, NEVER a get
            data: dataf,
            success: function(data) {
                //shows the relevant data of your login result object in json format
                alert(data);
                //parsing your data into a JavaScript variable
                var loginResult = JSON && JSON.parse(data) || $.parseJSON(data);
                //now you can use the attributes of your loginResult easily in JavaScript
                //for example, assuming you have a name attribute in your Customer class
                alert(loginResult.name);
            }
        });
        return false;
    });
});
</script>

更多信息: