VB_
VB_

Reputation: 45692

doGet calls doPost OR vise versa

I've bring this example from a book:

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
  ServletOutputStream out = resp.getOutputStream();
  out.setContentType(“text/html”);
  out.println("<html><h1>Output to Browser</h1>");
  out.println("<body>Written as html from a Servlet<body></html>");
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
  doPost(req, resp); //call doPost() for flow control logic.
}

Questions:

  1. Why doPost can't call doGet?
  2. What does flow control mean?

Upvotes: 0

Views: 12996

Answers (4)

Vilson Armani
Vilson Armani

Reputation: 11

If you need the doGet calls doPost, then it is better to use the "service".

protected void service((HttpServletRequest req, HttpServletResponse resp) throws  ServletException, IOException { 
     //do something you need
} 

Upvotes: 1

Cl&#233;ment Duveau
Cl&#233;ment Duveau

Reputation: 439

I know it's old, but still...

About Q1, everybody gives a really interesting and exact answer but the truth is out there... Just take a look at this "minified" code, you will understand:

protected void doGet(HttpServletRequest req, HttpServletResponse resp){
  doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp){
  //
  //Do something
  //
  //Can I call doGet() ?
}

Yes it is an infinite loop if you do so: doPost call doGet that call doPost that call doGet...

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213261

You can call doGet() from doPost() and vice-versa. No issues. But, you should not do such things. Both the methods have different purpose.

Ideally, the pre-processing task has to be done in doGet() method. For example, suppose you want to validate where a user has logged in or not, before forwarding the request to the user home page, that you would do in doGet() method. While the post-processing task has to be done in doPost(). For example, when a user submits a form, then you would like to get the values that are in the form, and validate them. Such logic go in doPost() method.

You should not mix them. If they were the same, there wouldn't be need of both methods. For more details on those methods see our tag wiki.

Upvotes: 1

Kick
Kick

Reputation: 4923

The example mean all the request whether it is GET or POST it will be going to be handle by the single method.You can move the doPost code to doGet and call doGet method from doPost,thr will be no issue.

Upvotes: 2

Related Questions