2

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!

Kanhu Bhol
  • 450
  • 3
  • 20
roland luo
  • 1,561
  • 4
  • 19
  • 24

3 Answers3

3

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");
    }   
}
Masudul
  • 21,823
  • 5
  • 43
  • 58
0

You no need to return any thing from the doGet method , infact you can not as it's void.

So what you need to do is get the PrintWriter object from the response and write data to it and that will available in the success function .

Sabir Khan
  • 9,826
  • 7
  • 45
  • 98
Krushna
  • 5,059
  • 5
  • 32
  • 49
0

You might notice that the doGet() method has two parameters: HttpServletRequest and HttpServletResponse.

You use HttpServletRequest to get information about the request - any parameters, the calling client IP, the URL etc.

http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html

You use HttpServletResponse to populate the response. HttpServletResponse has a number of methods allowing you to set response headers and data.

http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html

NickJ
  • 9,380
  • 9
  • 51
  • 74