Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

to support both get and post methods in one servlet

 
thomas jacob
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Head first servlet and Jsp book states in page 118 chapter 4 that if you want to support both GET and POST in one single servlet, then developers can put logic in doPost(), then delegate to a doGet() if the request doesn't need to post things.

public void doPost(....)
throws....{
doGet(request, response);
}

I tried to create a servlet which supports both GET and POST HTTP methods but it doesn't work. A get request is send from the form to this servlet

public class BeerSelect extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException{
doGet(request, response);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Beer Selection Advice<br>");
String c = request.getParameter("color");
out.println("<br>Got beer color " + c);
BeerExpert be = new BeerExpert();
List result = be.getBrands(c);
request.setAttribute("styles", result);

RequestDispatcher view = request.getRequestDispatcher("result.jsp");
view.forward(request, response);



}

Tell me what am I doing wrong

Regards
Thomas
 
Marc Peabody
pie sneak
Sheriff
Posts: 4727
Mac Ruby VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) You didn't write a doGet method.
2) The doPost should do nothing but call doGet.
 
Karthikeyan Varadarajan
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Modify your code like this,

public class BeerSelect extends HttpServlet{

// doPost method which will support POST
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException {

// Just Delicate it the call to doGet;
doGet(request, response);

}


// doGet method which will support GET
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Beer Selection Advice<br>");
String c = request.getParameter("color");
out.println("<br>Got beer color " + c);
BeerExpert be = new BeerExpert();
List result = be.getBrands(c);
request.setAttribute("styles", result);

RequestDispatcher view = request.getRequestDispatcher("result.jsp");
view.forward(request, response);

}

}

Hope it helps
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic