I have a jsp page with a form that when it’s submitted goes to a Servlet that inserts the form data into the database.
When the data is inserted into the database, I’m trying to get the browser back to my jsp page and show a javascript alert saying that the data was inserted successfully, my code is the following:
RequestDispatcher rd;
if(dao.insertClient(client)) {
rd = getServletContext().getRequestDispatcher("/pages/clients.jsp");
rd.include(request, response);
out.print(
"<script type=\"text/javascript\">"
+ "alert("Client inserted successfully!");"+
"</script>"
);
}
This code is doing exactly what I want, but this method getRequestDispatcher() redirects the page to the servlet itself, and the URL is like http://localhost:8080/Servlet, this way I can’t access any intern link of the page, since the links to the other pages obviously are outside of the servlet context, and the glassfish returns the 404 error.
Instead of using getRequestDispatcher(), I’ve tried using the response.sendRedirect(), this way I can insert the data into the database and access the intern links, but the javascript alert isn’t shown.
Somebody has a suggestion on how I can redirect the page to the clients.jsp and display the javascript alert?
Thanks!
you can try another approach :
Set parameter from servlet like this :
RequestDispatcher rd;
if(dao.insertClient(client)) {
rd = getServletContext().getRequestDispatcher("/pages/clients.jsp");
request.setAttribute("isSuccess", "success");
rd.include(request, response);
}
access the parameter in jsp to check whether to show alert or not.
<%
String result = request.getParameter("isSucess");
if("success".equals(result)){
%>
<script type="text/javascript" >
alert("Client inserted successfully!");
</script>
<%
}
%>
Related
i have multiple web pages jsp and i use for the resubmit in refresh response.sendredirect("blabla.jsp") but one page work good , another page wen i press submit it go to a blank page and the row added to database, any solution for this problem ? thank you
`
<% String UC1 = "INIT";
if (request.getParameter("add_spec") != null) {
UC1 = "ADD_SPEC";
}
if (UC1.equals("INIT")) {
List<Speciality> specs = SpecialityController.INSTANCE.findAll();
%>
<%#include file="./WEB-INF/Add_Spec.jspf" %>
<%#include file="./WEB-INF/view_all_specs.jspf" %>
<%}
if (UC1.equals("ADD_SPEC")) {
String spec = request.getParameter("speciality");
SpecialityController.INSTANCE.create(new Speciality(spec));
List<Speciality> specs = SpecialityController.INSTANCE.findAll();
response.sendRedirect("main_admin.jsp");
%>
<%#include file="./WEB-INF/Add_Spec.jspf" %>
<%#include file="./WEB-INF/view_all_specs.jspf" %>
<% }
%>
`
You can use the Post/Redirect/Get pattern.
When a web form is submitted to a server through an HTTP POST request,
a web user that attempts to refresh the server response in certain
user agents can cause the contents of the original POST request to be
resubmitted, possibly causing undesired results, such as a duplicate
web purchase.
To avoid this problem, many web developers use the PRG
pattern - instead of returning a web page directly, the POST operation returns a redirection command.
In other words, when you submit the data, you should redirect to the page on which you can view (get) the data you've just added.
That way, refreshing will not resubmit the data.
Alternatively, you could use a CSRF/XSRF-like token.
Though this example is in PHP, you should understand the gist of it.
Update
Even better, you can check out this example for CSRF https://services.teammentor.net/article/00000000-0000-0000-0000-000000040a2e
I want to perform an action on a JSP if redirected from a specific servlet only else do nothing.Is it possible?
In my JSP there are different errors defined. This JSP calls a servlet (with contentType as application/pdf) which opens in a new tab and searches for a PDF for 25 seconds and then if PDF is not found redirects to same JSP which shows the error message "File not found". I want to show the error if called from servlet only else do nothing.
JSP Code:
<%}else if(hPP!=null && hPP.get("errorcode")!=null && hPP.get("errorcode").toString().equalsIgnoreCase("Issue")){%>
<c:if test="${cameFromServlet}">
<div class="SplInputField">
<label class="FontBlod">Download fail</label>
</div>
</c:if>
servlet code
if (content == null) {
request.setAttribute("cameFromServlet", true);
String redirectJspUrl = request.getParameter("homeRedirect");
String strReceiptPage =
redirectJspUrl.substring(0, redirectJspUrl.lastIndexOf("/")) +
"/GetQReceiptPage";
response.sendRedirect(strReceiptPage);
}
Add an attribute to the request in the servlet like this
httpservletRequest.setAttribute("cameFromServlet", true)
then in your JSP check for it
<c:if test="${cameFromServlet}">
DO STUFF HERE
</c:if>
EDIT:
What you have done in your edit will not work, since you are doing a redirect. Which means the browser is sent a 302 response to tell it to issue another request against the new url. Do you have a specific requirement to change the url for the user? If so you will need to add the cameFromServlet attribute to the session instead - like this:
req.getSession().setAttribute("cameFromServlet", true);
Bare in mind though, that cameFromServlet attribute will remain on the session until you unset it so if there was another time that jsp page is shown you will run into problems unless you do something to unset it - either by introducing another servlet in the middle and moving it from the session to the request - thus simulating Springs flash map behaviour or unset it in the JSP after you have used it - like this:
<c:remove var="cameFromServlet" scope="session" />
If you do not need the URL to change for the user, you can change your servlet code to make use of a request dispatcher (what I thought you were doing)
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/yourjsp.jsp");
requestDispatcher.forward(req, resp);
I am working on java servlet project
I have index.jsp page that take input from user and send it withe post method to readXml servlet page that process the input then return the result to index.jsp
I wont to return to specific id in index.jsp
I used this code for foreword response to index.jsp
request.setAttribute("message", span );
request.setAttribute("Sent", input );
request.getRequestDispatcher("/indexjsp.jsp#color").forward(request, response);
request.getRequestDispatcher("/indexjsp.jsp#color").forward(request, response);
when I use this code I get resource error
and when I remove #color it will return the response to index.jsp but not with id I wont.
are there any way to return to specific id from servlet?
DO it something like this
instead of using #color try ?id=color.
Populate this parameter in the hidden input tag on 'index.jsp'. Now you have your tag id on client side. you can do what you want using javascript after onload event triggers.
I know I am doing something stupid and wrong but I can't figure it out. Please help.
I am using Apache Tomcat Servlet 7 with JQuery.
On my web page, when I click on a button, a Jquery GET call is made to my servlet URL. The servlet, after receiving the data (in JSON format), processes the data and creates some result parameters. Then the servlet passes those parameters to a JSP file to load the JSP page. So in summary, when the user clicks on a button, processing happens on the servlet and the result JSP page is loaded.
The problem is, when I make a Jquery GET call from the button, no result page is loaded. Instead when I do console.log(request), I see the entire html content of the rendered JSP page.
Here's my code on the web application when the button is clicked:
var request;
if (request) {
request.abort();
}
request = $.ajax({
cache: false,
type: 'GET',
url:'http://<MyServerAddress>:8080/<App>/<Servlet>',
data: {
'queryType' : 'clickButton',
'data' : JSON.stringify(buttonPageInfo)
},
});
request.done(function (response, textStatus, jqXHR){
console.log("Response: " + JSON.stringify(response));
// shows the entire html content of the processed JSP page that I want to load
});
Here's the code on the server side:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
processData(request, response);
}
protected void processData(request, response) {
/* Do some processing on the data and come up with results */
RequestDispatcher rd = getServletContext().getRequestDispatcher("/myJSPPage.jsp");
rd.forward(request, response);
}
Right after rd.forward(request, response), I expect my web page forward to myJSPPage.jsp to show the result, but nothing happens. Instead console.log("Response: " + JSON.stringify(response)); shows the entire HTML content of the JSP page with the results I am expecting.
What am I doing wrong?
You are getting HTML because you are forwarding to a JSP.
Just remove the RequestDispatcher stuff and make sure that you have flushed the response data.
Just call windows.open() if you want to do a normal page call. No need to use ajax for that.
I have a Servlet which accept username and password and authenticates it.
After it is done, I want to display an HTML page.
It is a big HTML page so I read that using writer.println() was not a good idea.
How do I display the new page?
I tried using sendRedirect but that, for some reason, displayed the same page (login page) again.
Please help.
Create a JSP page contains your HTML, then use requestDispatcher to forward the request.
for Example:
if you created a JSP page named MyJSP, then in login Servlet use:
request.getRequestDispatcher("MyJSP.jsp").forward(request, response);
you can use this lines of code
create an html whatever the name you like i had created LoggedIn.html and
use this code in your servlet
ServletContext context= getServletContext();
RequestDispatcher rd= context.getRequestDispatcher("/LoggedIn.html");
rd.forward(request, response);