I am very new to JAVA Servlets so pardon me if the question sounds silly. Basically, I have simple static HTML page having a form with input fields accepting values from a user. When a user enters values and click submit button values are sent to JAVA servlet where it does validation for values. If validation is failed I want servlets to send the old values which are correctly entered in addition to an error message for the invalid field and this will be displayed in static HTML page. How can I accomplish this with static HTML page and Java servlet?
I understand and totally agree that JSP would make my life easier in such case. However, if I have to use only HTML static page and JAVA servlet what are the options available?
You can include Javascript in the static web page that is called by the submit button onclick event and makes an AJAX call to the servlet. The servlet should respond with JSON or XML containing the validation results/error message. The form fields and/or error message text can be updated in the response handler Javascript function.
There are several examples on StackOverflow including this one. Scroll down to "Ajaxifying an existing form".
Related
I have a search.jsp page that has some html content and a form. When the form is submitted, there is a servlet handle the form data and forward the results to the search.jsp page. However, the url in the browser after processing the form is changed to the servlet name:
http://localhost:8080/MyProject/SearchServlet
not the search.jsp page:
http://localhost:8080/MyProject/Search.jsp
How I can change the url to the search.jsp? In other words, I just want to refresh the search.jsp page to display the results in the same page. How I can do that?
You cannot do that by forwarding the request: you need to "tell" the browser to generate a new http request by using the response.sendRedirect() method.
Now the question is why do you want the url bar to display the name of the Jsp?
Hiding the real destination path is a desired feature when forwarding requests: users do not need to know the server side redirects (that's how they are also called) happening in your web app.
Think about it: to carry out its tasks a servlet potentially can forward the request a number of times before getting to the final destination: you don't want the url bar to change each and every single time.
Give a fancier name to your servlet like: "Search" rather than "SearchServlet" so that users will know they are on the search page of your web application and not in the "SearchServlet" page.
In addition to that, if you visit any professional website, you will hardly ever see the .jsp or .html or .php extension on the address bar. While that is not a requirement or specification and you are free to do so, I believe the first approach is best practice (it looks even better to me honestly). There is even a folder WEB-INF whose purpose is to hide your .jsp pages from direct access via url bar.
What I like doing is having a servlet as the landing-welcome page of the web app, that will be responsible to forward and redirect requests based on the user input and the inner working of the application.
Now back to your final request (pun intended)
"In other words, I just want to refresh the search.jsp page to display the results in the same page. How I can do that?"
What I would do is:
redirect the user to the "Search" servlet from the welcome/home servlet.
In the doGet method of the Search servlet I would forward the request to the search.jsp page (you could set attributes before forwarding if you need to).
In the search.jsp I would set the action attribute of the form to "Search" (the name of the servlet) and the method to POST.
In the doPost method of the Search servlet you would implement whatever logic you wish to implement and finally forward the request to the search.jsp
After hitting the search button (and even after the submit button is clicked) what the user will see on the address bar is simply
http://localhost:8080/MyProject/Search
Hope that makes sense.
Are you using the same search.jsp for searching and well as showing the result? It is possible to use the same jsp to perform both the functions but it's easier and desirable to make another jsp which will only show the results.
If you are not able to see the results on search.jsp then make sure that you are setting the proper response in the Servlet class before forwarding it to the jsp and also whether you are reading the response sent by the Servlet class properly in the jsp.
If you want, the page to not refresh at all, then go for AJAX.
Hi I have jsp page That is having some text fields,I will fill that text fields and I will submit that form to server side.If any error comes in the server side I will redirect to the same page with error message Now I want that text field to remain as it is but in my case it is clearing.How to make the text field as same.
The two options available to you are:
Don't reload the page. Instead submit the data via AJAX or validate it by javascript. That way you don't ever have to touch the data in the form. Make sure your javascript highlights the fields that have errors in some way.
The endpoint that you're POSTing your data to needs to be able to recognise that the data is invalid and include that data when returning the user to the same page. I'm not familiar with jsp, but generally you'd do that by including variables in your template for your form that could contain the data, and passing empty strings on the first load of the page. If the page is then shown to the user again after a failed form validation, pass back the POST data that you received in your form request.
There are two option, you can dispatch the request/response to the same page instead of redirect, but you need to add an attribute and recover it in the JSP, or you can add the attribute in the session , recover the value to de text field and remove it using (if you are using JSTL)
Hi all I've got some jsp pages and im using struts2 to handle my forms.
After submitting a form by user, the url shown in address bar becomes somthing.action, so when the user refreshes the page, the forms gets submitted again. How can I handle this? after submission of a form.
If the goal is to prevent duplicate submission of forms then use token interceptor http://struts.apache.org/2.x/docs/token-interceptor.html or tokenSession interceptor http://struts.apache.org/2.x/docs/token-session-interceptor.html.
If you simple want to refresh the page after submit without submitting again then redirect to action where you only show results not form. Use redirectAction result for that.
+1 to both the other answers.
Post/Redirect/Get is the classic Pattern for every web technology.
Token Interceptor is another way to go, when you are using Struts2;
There is a third way to go, if you don't care about retro-compatibility with old browsers, or browsers with Javascript disabled: HTML5's window.history.pushState.
Just reset the url to the original one after the page is loaded, and pressing F5 will get the original page, instead of re-submitting the request.
$(document).ready(function() {
window.history.pushState("","", "myOriginalUrlWithNoParams");
});
POST REDIRECT GET
This pattern needs to be followed to prevent re-submission of form on refresh. This means, after submitting a POST request, POST should send a REDIRECT response to fetch the destination page using GET. With this pattern, if the user refreshes the page, only the GET request happens again, so the same page is fetched without updating anything in server.
This is a common design pattern recommended for web. Google would provide a lot of resources about this.
Can I send an entire HTML page with an AJAX response? If so, how to render that HTML page and what are the pros and cons doing that. The reason why I am asking this question is I found out that if we use response.sendRedirect("index.html") as a reply to an AJAX request in servlet we get the indx.html as AJAX response XML.
Your question doesn't make much sense and I can't quite tell what you're asking - the response to an ajax request will be whatever the server sends back. It could be plain text, XML, HTML, a fragment of an HTML/XML document etc. What you can do with depends on your script. If you're using a library like jQuery, what happens on the client side and what you can do with the response can also depend on how the library interprets the response (Is it a script? It it HTML/XML or JSON?).
if we use response.sendRedirect("index.html") as a reply to ajax request in servlet we get the indx.html as ajax response xml. Can some one pls explain this
An ajax request will behave much like a 'regular' HTTP request. So when you send back a redirect from your server (HTTPServletResponse#sendRedirect), the browser follows the redirect just like it would for any other request. If your ajax request was to a resource that required HTTP BASIC authentication, you'd see a prompt to login, just like you would if you visited the URL directly in a new browser window.
If you want to send HTML as a response, because you want to update divs, tables or other elements, but still want to use the same css or javascript files then it can make sense.
What you can do is to just send it as plain/text back to the javascript function, it can then take that and put it into the inner html element that you want to replace, but, don't do this if you want to replace the entire page, then doing what you want is pointless.
When you make the http request for your ajax call, it has its own response stream, and so when you redirect you are just telling the browser to have that http request go to index.html, as #no.good.at.coding mentioned.
If I get your question, you just want to know whether you could return whole entire HTML with AJAX and know the pro and cons.
The short answer to your question is yes, you could return the entire HTML page with your AJAX response as AJAX is just an http request to the server.
Why would you want to get the entire HTML? That's confusing to me and that is the part that I am not clear about. If you want to want to render the entire HTML (including tags like html, body, etc?), you might as well open it as a new page instead of calling it via Ajax.
If you are saying that you only want to get fragments of HTML to populate a placeholder in your page via AJAX then this is an acceptable practice. jQuery even provides load() function (http://api.jquery.com/load/) to make that task easy for you to use (check the section Loading Page Fragments).
Using this method, you could populate the placeholder using the HTML Fragments that is dictated by your server logic (i.e when the login fails or succeed) including the one via server redirect in your question.
so i am using java servlets to response to a request from a jsp page. and i want to change the html components name on that jsp page, like i change the buttons value or hide a label.i am wondering if there is any way to access jsp page's HTML components like button, text, ... in a servlet ?
i want to return the response in the same page that i have got the requests from. can i just simply write button1.name = "john" or text1.value = "ross geller" ?
Short answer is "no", longer answer is:
Firstly, you have to understand that HTTP and servlets is not an event-driven GUI like a desktop client, it's a lifecycle oriented, request/response paradigm. What this means is that the client (browser) makes a request for a page. The server (servlet) then responds with the HTML for that page. Once the servlet has sent the HTML to the browser, there is nothing that can be done on the server to change it, unless the browser makes a new request.
In this very basic paradigm, the lifecycle might look something like this:
A request is made by posting a form (browser) -> request is received (servlet) -> servlet does some processing based on request parameters -> HTML is generated (either by the servlet or by forwarding to a JSP page) -> HTML is sent back to the browser -> browser renders the page from the HTML
This is a very basic example, there are many variations on this based on which framework you use but they all boil down to something along these lines.
So, in your case, you have a page with, presumably, a form on it that has a button. You want to post that form and then return the same page but with some other label on the button. In the lifecycle abovem you would extract the parameters posted on the form from the request (paramters=all fields on the form). Then, in the HTML generation, you would use those request parameter values when building the HTML. I would advice you to search the web for some tutorials on servlet technology and look at some examples you might find and this will become clearer.