I try to redirect my page to another using request.getRequestDispatcher("/index.jsp").forward(request, response); . But it dont work. Why? But when I change it to response.sendRedirect it work fine.
I think the problem might be because of not using relative url.
You can try like this
request.getRequestDispatcher("index.jsp").forward(request, response);
I think you do need the forward slash with the JSP filename.
This is just a small possibility (need more info) - but do you have an init() method in your servlet?
If you do, you must call super.init(servletConfig) as the first line of your init() method, or you might get a NullPointerException when you try to forward.
Related
I am having troubles of directing to another servlet in a servlet file. I have a servlet file called NewDreamServlet.java and I want to redirect it to MyDreamsServlet.java.
This is what I currently have in the NewDreamServlet.java for redirecting.
request.getRequestDispatcher("/MyDreamsServlet").forward(request, response);
When I call this it ends up going to a blank page,
http://localhost:8080/ps10-austint/NewDreamServlet
How exactly would I accomplish this? Please let me know if there is any misunderstanding.
Did you try: response.sendRedirect("/YourApp/MyDreamsServlet")
Please try response.sendRedirect("/MyDreamsServlet"). Also, please note that you might have to add an return statement. The following post discusses this in more details java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed
All these answers to your question are wrong.
1. if you like to use RD().forward, which is more used for with in application calls, all you need to do is go to your web.xml file and for the url part of your 2nd servlet give it any name you would like eg. /fireServletTwo....
Now come back to your 1st servlet and in the getRqstDispatcher braces, write("/fireServletTwo"); this will tell the xml file to look for a servlet mapping with that name and run that servlet.
2. if you would like to use send.Redirect(); which takes a URL and is used to mostly pass controls outside of the application to another domain, its simple.. DO NOT USE A SLASH /.... just write the name of your servlet2 inside "";
Hope that helps
This one works for me but it usually better to have the context path:
response.sendRedirect(request.getContextPath() + "/home.jsp");
Can anybody tell me how to get the current URL of CordovaWebView when using Phonegap (Cordova)?
I want to do something like this in Java when the URL changes to the one I want:
if(current_url_cordova_webview=="http://www.google.com"){
alert("Yes");
}else{
alert("No");
}
Many thanks!
I hope you mean JavaScript and not java. document.URL will get you the current URL in JS.
Thank you for the response. I managed to do it myself by creating a custom Webview and checking the url in onPageFinished.
First of all let me describe what I'm trying to do, which I'm guessing is pretty simple.
I have a website with users and want to restrict access to a view_profile.jsp page only to logged users. I have a filter mapped to:
<url-pattern>/auth/*</url-pattern>
which looks like this
try {
HttpSession session = ((HttpServletRequest)request).getSession();
UserBean user = (UserBean)session.getAttribute("currentUser");
if (user != null && user.isValid()){
System.out.println("Filter: context -> " + ((HttpServletRequest)request).getContextPath()); //returns ""
chain.doFilter(request, response);
}
else{
((HttpServletResponse)response).sendRedirect("/login.jsp"); //works fine
}
This filter is run when on the index.jsp page user will click on a link:
<a href="./auth/view_profile?profile=${sessionScope.currentUser.username}">
//yeah, he will 'view' himself - it's just an example
which is suppose to take the user to the servlet mapped to ViewProfileServlet mapped to:
<url-pattern>/auth/view_profile</url-pattern>
which looks like that:
try {
String username = (String) request.getParameter("profile");
// here is getting info from database and setting request attributes
// works fine
//response.sendRedirect("/view_profile.jsp");
System.out.println("ViewProfileServlet: In context -> " + getServletContext().getContextPath()); // returns ""
dis = getServletContext().getRequestDispatcher("/view_profile.jsp");
// i've tried request.getRequestDispatcher. no difference
System.out.println("ViewProfileServlet: forward to '/view_profile.jsp'");
dis.forward(request, response);
}
Which in turn should take the user to the /view_profile.jsp (in the root context, not in /auth) and work, which it doesn't. What happens is the ViewProfileServlet runs and the view_profile.jsp shows, although it seems that the context is still /auth because all the links on view_profile.jsp point to i.e localhost:8080/auth/some-page.jsp. Also, css files are not being loaded, they're not even requested (at least according to firebug), and page source shows 404 Glassfish Error where css's suppose to be.
I would greatly appreciate any help, it's the first time i'm even doing something in jsp and i'm completely lost here.
A forward happens entirely at server-side. The browser doesn't know about it. When it sends a request to /auth/view_profile, and receives HTML from this response, he doesn't care if the HTML has been generated by a servlet, a JSP, both, or anything else. It reads the HTML and considers it comes from the path /auth/view_profile. All the relative path in the HTML are thus relative to /auth/view_profile.
It's far easier to use absolute paths to reference images, JS and CSS paths (and even other actions, most of the time). Just make sure to use the <c:url> tag to generate the URL, so that the context path of the web-app is prepended:
<script src="<c:url value='/js/myScript.js'/>" type="text/javascript"/>
^-- the slash here makes the path absolute.
In the Java Servlet, how to include original paramters after response ?
Servlet
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String cmd = request.getParameter("cmd");
System.out.println("service , cmd="+cmd);
request.setAttribute("name", "John"+System.currentTimeMillis());
RequestDispatcher rd = request.getRequestDispatcher("process.jsp");
rd.include(request, response);
}
JSP
main ${name}<br>
cmd ${cmd}
If I want to include all paramters, like "cmd", to a new jsp page, how to do it ?
based on No.1, if I want to add NEW attributes, like "name" to a new jsp page, how to do it ?
In the above codes, use include or forward, the results are same. why ?
Thanks
If I want to include all paramters, like "cmd", to a new jsp page, how to do it ?
All request parameters are in EL available by the ${param} map.
${param.cmd}
You don't need to prepare anything in the servlet.
based on No.1, if I want to add NEW attributes, like "name" to a new jsp page, how to do it ?
You already did it by request.setAttribute("name", name) and ${name}.
In the above codes, use include or forward, the results are same. why ?
Not exactly. If you use include(), the delegatee would not be able to control the response headers. You should be using forward() in this case. See also the javadoc. You should use include() only if you want to append something before and after instead of fully delegating the request/response.
See also:
Our Servlets wiki page
How do I execute multiple servlets in sequence?
It's the same request, you don't need to do anything at all.
A forward means you can't have committed any response (no output to client). Include doesn't allow any response status code or header changes.
See the docs for forward/include.
you can access all the request params using the request.getParameterMap() another question which can help you method, this returns a map of all params (key-value pair) which you can iterate and set the attribute.
request.setAttribute("name", "John"+System.currentTimeMillis());
What you've done here does add a new attribute called name (provided another entry doesn't exist with the key as name).
The result of include and forward are the same as
you are not adding any specific content to the response
when you forward a request, you are forwarding the control to handle the response to another component (in your case process.jsp)
when you include a jsp in your request, you are executing the included component and have the option of adding something extra to the stream (which you aren't doing).
thats why both the actions show you the same result.
I am calling a servlet from an action class by using forward. It is then going to the servlet but it is not showing the output.
Actually I have create a PDF file which I need to show it on runtime. If I run that servlet only on server then it is showing the PDF file I want to.
But if I forward it from the action class it is not not showing anything.
I have given a simple condiiton on the action class like this:
if(id.equals("SGSY"))
{
forward = mapping.findForward("SGSY");
}
else
{
forward = mapping.findForward("fail");
}
After this it is going to servlet but not actually showing the output. I don't understand why. Am I doing something wrong?
Try response.sendRedirect 1st instead of forward mapping,if it works it means there must be problem with your path