简体   繁体   中英

JAVA: Servlet doing something different depending on used method doGet/doPost

I'm quite a newbie when it comes to servlets and I would like somebody to help me a little bit.

I need to write a simple method calling println with an different information depending on used doPost or doGet , for example:

if (doPost was used) {
    out.println("The doPost method was used);
}

else if (doGet was used) {
    out.println("The doGet method was used);
}
else
{
    out.println("Neither doPost nor doGet was used");
}

Can somebody help me? :)

Thanks in advance!

An example of simple servlet that it would do something similar that you want:

public class ServletDemo1 extends HttpServlet{

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException{
        // do something with GET petitions  
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException{
        // do something with POST petitions 
    }

}

This code do something different depending what type of petition GET or POST is coming. Or you could use the service method:

protected void service(HttpServletRequest req, HttpServletResponse resp) {...}

and filter depending of the request method value ( request.getMethod() ). You could manage more than GET or POST (like PUT, DELETE...)

A servlet typically has two methods which you define named doGet(...) and doPost(...). On the client side, when you make a request to the servlet on the server side, you generally specify which method you want to send your request information to. For instance, if you are working on a Java Server Page that involves JQuery you would make an Ajax call like this:

$.ajax({
      type: "GET",
      url: "/ChatEngine/ChatServlet/users/list?roomId=" + roomID, 
      contentType: "application/json; charset=utf-8",
      cache: false,
      dataType: "json",
      success: process,
      error: function(err) {
      alert('Get User List Error:' + err.responseText + '  Status: ' + err.status); 
      }
    }); 

Notice the type attribute is set to "GET". It could just as easily be set to POST. When the servlet on the server side receives the request, it will know which method to send the request data to, either doGet(...) or doPost(...). In the servlet, in each method doGet(...) and doPost(...) you can write your println statement signifying which one was executed. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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