How to configure Post method for servlet in web.xml

3.5k Views Asked by At

I have a servlet as a welcome file in web.xml. When the requesting comes to the application it is invoking directly get method. Is there any way I can make it call the post method in the servlet? Right below is the code. Could you please help me.

<welcome-file-list>
    <welcome-file>LoginServlet</welcome-file>
  </welcome-file-list>
   <servlet>
    <description>
        </description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.eeft.login.LoginServlet</servlet-class>
  </servlet>
   <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>
        /LoginServlet</url-pattern>
  </servlet-mapping>
1

There are 1 best solutions below

0
On BEST ANSWER

This is not possible because of the fundamental differences between an HTTP GET and POST request. A POST request is accompanied with <form> data as a result of a user submitting it first. While a welcome file caters to GET requests that come to the root / of your website which in all practical cases result from a user simply typing the address in the browser's address bar. There's no data to POST and hence a welcome file request is always a GET one.

Now, if the reason behind your question is that you just want to reuse your doPost() logic then as @Avinash suggested above, you can simply call it from your doGet() as

public void doGet(HttpServletRequest request, HttpServletResponse response)
                                      throws ServletException, IOException {
    doPost(request, response);
}

But, there's an even better way. Split your LoginServlet logic into doGet() and doPost() such that the GET requests receive a login form like

<form method="post" action="LoginServlet">
  Username: <input type="text" name="user" /><br />
  Password: <input type="password" name="pass" /><br />
  <input type="submit" value="Login" />
</form>

Notice how the form submits to itself. When it does the POST request would get handled by your doPost() method as before. Validate the user credentials and redirect the user accordingly. If the authentication fails, use sendRedirect() to send the user back to LoginServlet. Since, this would be a GET request, the user will see the login form again.

The login page should ideally come from a JSP but since I guess you've just started with Servlets, I didn't want to complicate things for you. Look into MVC pattern once you get comfortable with Servlets.