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>
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 yourdoGet()
asBut, there's an even better way. Split your
LoginServlet
logic intodoGet()
anddoPost()
such that the GET requests receive a login form likeNotice 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, usesendRedirect()
to send the user back toLoginServlet
. 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.