protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getMethod().equals("POST")) { // Handle POST request } }
if (request.getMethod().equals("GET")) { response.sendRedirect("/home"); } else { RequestDispatcher dispatcher = request.getRequestDispatcher("/error"); dispatcher.forward(request, response); }In this example, we are redirecting the user to the home page if the request method is GET, and forwarding to an error page for any other request method. The HttpServletRequest.getMethod() method is part of the javax.servlet.http package library.