Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Servlet handling multiple post requests

I have one Servlet name EditEvent and one JSP which contains two forms. One for adding new event, The other one is for removing an event.

Is it considered as good practice to be using two separate servlets to handle one JSP? If not, how would you handle two post requests from one servlet? i.e The Add event and remove event request.

cheers

like image 379
Raju Kumar Avatar asked Mar 17 '12 03:03

Raju Kumar


2 Answers

For handling multiple requests by same servlet you have to make a contract to have a request parameter like 'ACTION'. Then in your forms add this as hidden field with values like 'ADD' and 'REMOVE'. So, in doPost() you can check this parameter value and can invoke respective handling methods in same servlet.

class YourServlet extends HttpServlet{

      public void doPost(HttpReq req, HttpResp resp){
               String action = reg.getParameter('ACTION');
               if('ADD'.equals(action)){
                   addEvent();
               }
               if('REMOVE'.equals(action)){
                   removeEvent()
               } else {
                   defaultAction();
               }
      }

}
like image 180
Pokuri Avatar answered Jan 24 '23 15:01

Pokuri


It's all your choice. It depends all on the current and future functional requirements. A simple alternative is to just introduce one or two if blocks in the servlet wherein you check which button is been pressed:

if (request.getParameter("add") != null) {
    // Perform add.
}
else if (request.getParameter("remove") != null) {
    // Perform remove.
}

assuming that the buttons look like this:

<input type="submit" name="add" value="Add" />
<input type="submit" name="remove" value="Remove" />

A complex alternative is to step over to a normal MVC framework where you just have to specify specific action methods. For example, JSF:

<h:commandButton value="Add" action="#{bean.add}" />
<h:commandButton value="Remove" action="#{bean.remove}" />
like image 41
BalusC Avatar answered Jan 24 '23 15:01

BalusC