I'm using in my project the embebed jetty and came up with a few problems. I have these two pages:
índex.jsp
result.jsp
And these two servlets:
upload
search
In the índex.jsp there is a form to upload a file and the upload process in handle by the upload servlet but then I should return a message to the índex.jsp to tell if the upload was done.
request.setAttribute("message", "Upload Sucedded!");
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
rd.forward(request, response);
This will forward the message to the índex page but the url will be /upload and I would like to be the índex. So there is some other way of struct my files and maybe make my welcome file some servlet instead of the índex.jsp?
This has nothing to do with Jetty. That's default behavior of forwarding.
Ugly solution:
If you want to rewrite your URL, use a redirect instead and pass the parameter by session. After displaying the message, remove it from session.
Better solution:
Change the name of your upload servlet by IndexServlet. This servlet will handle GET and POST requests for your index.jsp page. In the end of the processing, you will forward to your JSP page. By doing this, you can directly post the form to your current page:
<form action="index.jsp" method="POST" enctype="multipart/form-data">
<!-- your fields ... -->
</form>
Then your servlet:
#WebServlet("index.jsp")
public class IndexServlet extends HttpServlet {
//using ... to avoid parameters and exceptions to be thrown
#Override
public void doGet(...) throws ... {
//this method should only forward to your view
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
//using ... to avoid parameters and exceptions to be thrown
#Override
public void doPost(...) throws ... {
//current implementation...
//in the end, forward to the same view
request.setAttribute("message", "Upload Sucedded!");
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
}
More info:
Difference between JSP forward and redirect
The simplest solution would be to change upload servlet to use redirect and use request parameter instead of attribute like this:
// upload servlet
response.sendRedirect("index.jsp?message=YourMessage");
Then in index.jsp use request.getParameter("message") or EL to display your message.
Related
Yes, I know that this is for sure duplicate question.
But... I have read all of answers for earlier asked questions, tried to fix everything... and my code still doesn't work.
In index.jsp:
<form action="/Login"method="post">
and
<input type="submit" value="LogIn">
In post method of servlet "/Login":
if (result == 1) {
RequestDispatcher view=request.getRequestDispatcher(url);
view.forward(request, response);
} else {
response.sendRedirect("index.jsp");
return;
}
I was trying with:
"http://localhost:8080/home.jsp",
"/home.jsp",
"home.jsp"
response.sendRedirect
trying to do with and without "return;".
And nothing.
This what I saw is only blank page and:
If doPost()
method: url is
"http://localhost:8080/Login".
If doGet()
method: url is the same as abovementioned plus parameters input into a form.
Could you help me?
If you want to redirect user to another page with a brand new request then using sendRedirect function, but you must send redirect to the servlet, servlet will process and return to you a page. You can not sendRedirect directly to the jsp page (you send redirect to a jsp page, it's like you right click on jsp page and run it on server). Please refer to this post to see the use of sendRedirect method.
In my Java web application I am using the HttpServletRequest getPathInfo() method to get the path sent by a request to the Servlet.
My Servlet: Controller contains the following the following code:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getPathInfo();
RequestDispatcher dispatcher = null;
if(action.equals("/viewDetails"))
{
dispatcher = this.getServletContext().getRequestDispatcher("/viewDetails.jspx");
}
}
Here I am checking the what the action of the request is so that I can direct the user to the appropriate view.
Now in my loginForm.jspx I have a login form like this:
<form method="POST" action="http://localhost:8080/do/viewDetails">
This proceeds to the controller with the action: /viewDetails that the controller recognizes.
In my web.xml I have mapped the /do pattern to link to the Controller servlet. So whenever the /do path is found, the request gets sent to the Controller which determines where to go (as seen in the processRequest method).
Now the problem I am having is that when I try to link to the controller the same way in a HTML a tag, it doesn't work, for example:
View all details
Is there a way I can perform the same action with a href as I did with <form action...?
EDIT:
Screenshot of the browser when I click the View All Details link:
I have a servlet which can get requests by multiple JSP's.
But when I use the RequestDispatcher in the servlet, I don't know how to forward to the JSP that sent the request.
req.getRequestDispatcher("page.jsp").forward(req, resp);
I know there is something like this in html: javascript:javascript:history.go(-1)
I just need something like this:
req.setAttribute("originalRequest", req.getRequestPage());
req.getRequestDispatcher(originalRequest).forward(req, resp);
That piece of code is probably very noob but it gives you the idea of what I need.
So: I need to forward to the page that sent the original request (basically reload the page), but because multiple jsp's use the servlet, I cannot simply forward to "page.jsp"
You can do following
Create a hidden parameter for every jsp named jspName and give value for respective JSPs. e.g. for JSP A, parameter name is jspName and value is a, for JSP B, parameter name is jspName and value is b
Read this hidden parameter in the servlet using following code.
String jspName = request.getParameter("jspName");
RequestDispatcher rd = request.getRequestDispatcher(jspName);
rd.forward(request, response);
When you are calling the servlet from JSP A, then it will have paramter japName=a, when servlet code is running, it will retrieve the value a from request.getParamter("jspName") and a getRequestDispatcher(jspName) will create the dispatcher for the same and rd.forward(request, response) will forward to the jsp.
I have not tried the following, but I hope this may help you to solve your problem.
req.setAttribute("originalRequest", req.getRequestPage());
req.getRequestDispatcher(req.getAttribute(originalRequest).toString()).forward(req, resp);
I have tried in this way, It's working for me...
In JSP
You need to set this in every JSP. For ex: index.jsp is my jsp name.
<% session.setAttribute("jspName","index.jsp"); %>
In Servlet
request.getRequestDispatcher(session.getAttribute("jspName").toString()).forward(req, res);
How can I send my response and request object from a jsp file to a servlet by code? I don't want to submit a form or so.
I tried it with:
response.setRedirect("my page"):
But then it says:
Exception in thread "main" org.apache.http.client.HttpResponseException: Moved Temporarily
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:68)
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:54)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:945)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:919)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:910)
at com.xx.xx.client.Client.sendPOSTRequest(Client.java:185)
at com.xx.xx.client.Client.main(Client.java:46)
As clarification: I have a client that sends a post request to a JSP file. This JSP file parses a file and puts the needed information into the session. I want to call a servlet from this jsp file to add something into the database. I think this error code is thrown by this line String responseBody = httpclient.execute(httppost, responseHandler);
You can just use <jsp:include> on a servlet URL.
<jsp:include page="/servletURL" />
The servlet doXxx() method will just be invoked with the current request/response. Note that the servlet cannot forward to another JSP afterwards. It has to write directly to the response, or to set some request/session attributes which the JSP can intercept on after the <jsp:include> line.
Note that this is bad design. You're abusing a JSP as a front controller. It should be the other way round. The servlet should act as a front controller and the JSP should act as a view. The client should send the request to the servlet URL directly instead of to some JSP file. The servlet should perform the business job and finally forward to a JSP to let it present the results in HTML. See also our servlets tag wiki page for some Hello World examples.
you can use the RequestDispatcher forward(ServletRequest request, ServletResponse response)
Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
You can do it like this:
ServletContext context= getServletContext();
RequestDispatcher rd= context.getRequestDispatcher("/YourServlet");
rd.forward(request, response);
UPDATE
Also note on your code that you have response.setRedirect instead of response.sendRedirect(...) but note that this method will not work as you want it to because it just asks the browser to make a new request to your servlet rather than forward your request and response object to that servlet . See RequestDispatcher.forward() vs HttpServletResponse.sendRedirect() for more info
I have two jsp file and one java file. My constraints is if jspfile1 call java then java file call the jspfile2. Is it possible?
How to achieve this?
If by "Java file" you mean a Servlet, you can use the RequestDispatcher:
request.getRequestDispatcher("/my.jsp").include(request, response);
request.getRequestDispatcher("/my.jsp").forward(request, response);
The normal way is using a Servlet. Just extend HttpServlet and map it in web.xml with a certain url-pattern. Then just have the HTML links or forms in your JSP to point to an URL which matches the servlet's url-pattern.
E.g. page1.jsp:
<form action="servletUrl">
<input type"submit">
</form>
or
click here
The <form> without method attribute (which defaults to method="get") and the <a> links will call servlet's doGet() method.
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Do your Java code thing here.
String message = "hello";
request.setAttribute("message", message); // Will be available in ${message}.
// And then forward the request to a JSP file.
request.getRequestDispatcher("page2.jsp").forward(request, response);
}
}
If you have a <form method="post">, you'll have to replace doGet by doPost method.
Map this servlet in web.xml as follows:
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<url-pattern>/servletUrl</url-pattern>
</servlet-mapping>
so that it's available by http://example.com/contextname/servletUrl. The <form> and <a> URL's have to point either relatively or absolutely to exact that URL to get the servlet invoked.
Now, this servlet example has set some "result" as request attribute with the name "message" and forwards the request to page2.jsp. To display the result in page2.jsp just do access ${message}:
<p>Servlet result was: ${message}</p>
Do a http web request.
jsp files get converted to a servlet. You cannot call them directly.
EDIT : typo fixed.