I am trying out basic login using JSP and Servlets and don’t understand how forwardslashes are used to indicate the path.
login.JSP is located in LoginApp/WebContent/login.jsp
LoginServlet.java is located in LoginApp/src/org/koushik/javabrains/LoginServlet.java
I have the following code in my login.jsp file –
<form action="login" method="post">
<br>User ID input type="text" name="userId" />
<br>Password <input type="password" name="password" />
<br><input type="submit" />
</form>
The corresponding servlet code is
@WebServlet("/login") // <-- forwardslash here
public class LoginServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String userId, password;
userId = request.getParameter("userId");
password = request.getParameter("password");
// more code here
}
}
If we see the form action, there is no forwardslash before “login”, whereas if we see the servlet annotation, there is a forwardslash before “login”. Why this difference?
In
The
/loginis a url pattern that is relative applications to the contextPathe.g. if your application had a context path of
webappthen a request tohttp://localhost:8080/webapp/loginwould load theLoginServletIn your jsp the form action
Is relative to the jsp page itself, and not the contextPath.
However because your jsp is located in the webroot folder (the top level folder where your jsp’s and WEB-INF folder live)
http://localhost:8080/webapp/login.jspthen the
action="login"attribute in the formwill resolve to the location
http://localhost:8080/webapp/loginwhen the form is submitted and will call the
LoginServletIf you move the jsp into a subfolder (e.g. folder1) then
action=loginwill not call the login servletas the jsp will now be located at
http://localhost:8080/webapp/subfolder/login.jspand so
action=loginwill now resolve to
http://localhost:8080/webapp/subfolder/loginand the servlet will not be found (remember the login servlet is relative to the context root, thats what the / means in
@WebServlet("/login"))changing the form action to
would work.
To avoid having to work this out in webpage forms
most people will change the form action to look like this
So that where ever the jsp is located the el expression
${pageContext.request.contextPath}/loginwill resolve to same location as the servlet defined with url pattern /login
see What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL? for more info an the el expression
Hope this helps