简体   繁体   English

从servlet到ajax获取数据?

[英]Getting data from servlet to ajax?

Jsp / servlets seems to be much more tedious than I'd have expected it. Jsp / servlet似乎比我预期的要乏味得多。 I'm trying to call a servlet function through ajax and actually have it feed some data back to my front end , which is a jsp file. 我试图通过ajax调用servlet函数,实际上让它将一些数据反馈回我的前端,这是一个jsp文件。

This code returns my response as null. 这段代码返回我的响应为null。

This is part of my servlet. 这是我的servlet的一部分。 I'm trying(desperately as is fairly obvious from the code) to have it send something - anything back to ajax. 我正在尝试(非常希望从代码中明显看出)让它发送一些东西-任何东西都回到ajax。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String action = (String) request.getParameter("action");
if (action.equalsIgnoreCase("selectedhotel"))
    {

        response.setContentType("text/plain");  
        response.setCharacterEncoding("UTF-8"); 
        System.out.println("test");
        String attribute = (String) request.getParameter("hotel_id");
        System.out.println(attribute);
        List<Room> aRooms;
        aRooms = model.getRoomByHotel(Integer.valueOf(attribute));
        request.setAttribute("aRooms", aRooms);
        request.setAttribute("list", list);
        PrintWriter outPrintWriter = response.getWriter();
        outPrintWriter.write("ASDSADA");
            outPrintWriter.println("test");
    }   

And the ajax from my JSP: 还有我的JSP中的ajax:

$(function(){
$("#hotelSelector li").click(function(){        
    var hid = $(this).attr('id');

    $.ajax({ type: "GET",   
         url: "AppController?action=selectedhotel&hotel_id=1",   
         success : function(text)
         {
            alert(text);
             // This will show the values. Change "alert" for $('div#mydiv').html(value) or so
         }
    });
});
});</script>

Riiight...so , please fix ? Riiight ...所以,请解决?

As mentioned, you really need to start small and work your way up. 如前所述,您确实需要从小处着手并逐步提高。 Get a simple "hello world" ajax response working and then tackle the more complex responses. 获得一个简单的“ hello world” ajax响应,然后处理更复杂的响应。 For the more complex data response, I would recommend looking into json (see gson ) to serialize the java objects in order to send back in the response writer. 对于更复杂的数据响应,我建议您调查json(请参阅gson )以序列化Java对象,以便在响应编写器中发回。

First thing you should consider is using the jQuery post and get wrappers to make your life easier. 您应该考虑的第一件事是使用jQuery post并获取包装器,以使您的生活更轻松。

For example, your html would be like the following: 例如,您的html如下所示:

<h1>Hello: <span style="color:red" id="showMyName"></span></h1>
<form method="post" action="AjaxServlet" id="myForm">
    <input type="text" name="myName" />            
</form>
<button id="ajaxSubmit" type="submit">SEND</button>
<script type="text/javascript">
     $(document).ready(function() {
        $('#ajaxSubmit').on('click', function() {
        // To simplify things, wrap what you can in a form and serialize                      
        // it to send to the server.
            var myForm = $('#myForm');
            $.get(myForm.attr('action'), myForm.serialize(), function(data) {
                $('#showMyName').text(data);
            });
        });
    });
</script>

On the servlet side, you should start with a plain-jane servlet and once you are sure it is working, begin adding additional scope. 在servlet方面,您应该从一个普通的servlet开始,并且一旦确定它可以正常工作,就开始添加其他作用域。 The base servlet should be somthing like this: 基本的servlet应该是这样的:

// For this example, get and post will use the same base procedures.
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
}

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 response here.*/
        out.println(request.getParameter("myName"));
    } finally {
        out.close();
    }
}

One way to send a complex response is to shove all your data in a collection of some sort and use gson or some other JsonObjectMapper to convert it to a string. 发送复杂响应的一种方法是将所有数据放入某种类型的集合中,然后使用gson或其他JsonObjectMapper将其转换为字符串。 You can then put this String in the response writer and send it back to be parsed out by jQuery. 然后,您可以将此String放入响应编写器中,并将其发送回去,以供jQuery解析。

EDIT: 编辑:

I forgot to mention that you need to make sure your servlet is being recognized by the your servlet container as well. 我忘了提到您需要确保servlet容器也可以识别您的servlet。 If you haven't added the descriptor to the web.xml, it should have an entry like the following: 如果尚未将描述符添加到web.xml,则它应具有如下条目:

<servlet>
    <servlet-name>AjaxServlet</servlet-name>
    <servlet-class>org.test.AjaxServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>AjaxServlet</servlet-name>
    <url-pattern>/AjaxServlet</url-pattern>
</servlet-mapping>

xmlhttp.responseText is used in javascript to get the response from a servlet. xmlhttp.responseText在javascript中用于从Servlet获取响应。 how you are getting response in jquery. 您如何在jquery中获得响应。 i think problem is in retrieving the response 我认为问题出在响应中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM