aspose file tools*
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes to support both get and post methods in one servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "to support both get and post methods in one servlet" Watch "to support both get and post methods in one servlet" New topic
Author

to support both get and post methods in one servlet

thomas jacob
Ranch Hand

Joined: May 19, 2005
Posts: 91
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

Joined: Feb 05, 2003
Posts: 4727

1) You didn't write a doGet method.
2) The doPost should do nothing but call doGet.


A good workman is known by his tools.
Karthikeyan Varadarajan
Ranch Hand

Joined: Jul 04, 2002
Posts: 98
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


~With Smile<br />VK
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: to support both get and post methods in one servlet