jsp - When to use forwardslash and when not to use forwardslash? -


i trying out basic login using jsp , servlets , don't understand how forwardslashes used indicate path.

login.jsp located in loginapp/webcontent/login.jsp

loginservlet.java located in loginapp/src/org/koushik/javabrains/loginservlet.java

i have following code in 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

  @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 see form action, there no forwardslash before "login", whereas if see servlet annotation, there forwardslash before "login". why difference?

in

@webservlet("/login") 

the /login url pattern relative applications contextpath

e.g. if application had context path of webapp request to

http://localhost:8080/webapp/login load loginservlet

in jsp form action

is relative jsp page itself, , not contextpath.

however because jsp located in webroot folder (the top level folder jsp's , web-inf folder live)

http://localhost:8080/webapp/login.jsp

then action="login" attribute in form

will resolve location

http://localhost:8080/webapp/login

when form submitted , call loginservlet

if move jsp subfolder (e.g. folder1) action=login not call login servlet

as jsp located @

http://localhost:8080/webapp/subfolder/login.jsp , action=login

will resolve http://localhost:8080/webapp/subfolder/login

and servlet not found (remember login servlet relative context root, thats / means in @webservlet("/login"))

changing form action

<form action="../login" method="post"> 

would work.

to avoid having work out in webpage forms

most people change form action this

<form action="${pagecontext.request.contextpath}/login" method="post"> 

so ever jsp located el expression

${pagecontext.request.contextpath}/login

will resolve same location servlet defined url pattern /login

see what expression language ${pagecontext.request.contextpath} in jsp el? more info el expression

hope helps


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -