java - Call Javascript function in Servlet, after a submit Button has been pressed -


i have got question. know how execute javascript in servlet, having problem when want execute right after did redirect user side. here code, shows problem. using submit button on html side.

printwriter out = response.getwriter();   response.setcontenttype("text/html");   out.println("<script type=\"text/javascript\">");   out.println("alert('the session did time out, please reconnect');");   out.println("logout();"); out.println("</script>");     request.getrequestdispatcher("/login.jsp").forward(request, response); 

what happens is, redirected login page, not see alert. when delete forwarding line , there written

printwriter out = response.getwriter();   response.setcontenttype("text/html");   out.println("<script type=\"text/javascript\">");   out.println("alert('the session did time out, please reconnect');");   out.println("logout();"); out.println("</script>");  // redirect missing 

so getting alert message, getting redirected blank page, because there no redirect @ all.

so trying create alert, tells user in alert. right after it, want redirect him loginpage, want call 'logout' function wrote.

but neither getting alert nor logout function called. based on this question should work

what happens is, redirected login page,  not see alert. 

take @ javadoc requestdispatcher#forward().

forward should called before response has been committed client (before response body output has been flushed). if response has been committed, method throws illegalstateexception. uncommitted output in response buffer automatically cleared before forward.

so when forward() , current response not committed client , hence html , javascript code don't run. forward means current servlet not handling request, forwarded code should handle instead , hence don't see written in out.println() inside current servlet part of final response. tjis forwarding request , done in server side itself, not redirection initiated browser . redirect need use httpservletresponse#sendredirect.

so getting alert message, getting redirected blank page

you not getting redirected page , examine closely have written response :

out.println("<script type=\"text/javascript\">");   out.println("alert('the session did time out, please reconnect');");   out.println("logout();"); out.println("</script>");  

in case, browser fed html code :

<html>     <script type="text/javascript">    alert('the session did time out, please reconnect');    logout(); </script>  

this code show alert , call logout() function if any. , displays html page doesn't have visual content in current form.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -