how to return data to ajax from java Servlet
21,785
You can get the data from servlet by writing on response.getWriter().write("");
.
Here is a simple servlet example.
@WebServlet(name = "MyServlet", urlPatterns = {"/myservlet"})
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("Success Data");
}
}
Author by
roland luo
Updated on April 12, 2020Comments
-
roland luo about 4 years
i have my ajax function as follows:
$.ajax({ type: 'GET', url: "/myservlet", data: { objects: '2', dimension: '2', }, success: function( data ) { console.log(data); alert(data); }, error:function(data,status,er) { alert("error: "+data+" status: "+status+" er:"+er); } });
and i have my servlet to process the data sent to /myservlet. I read from the ajax tutorial which said the data in the success function is the data that ajax got from the server side. But i don't know how to set this data or return this data from doGet method in a Java servlet to the frontend. It seems doGet is a void method and cannot return any values, isn't it? I am a freshman in web development, thanks in advance!