Sending info from Servlet to JSP - java

What I want to do:
I have a form with a lot of fields(nick, email, name, surname, etc.) but the user has to fill Nick and Email first in order to be able to fill the other fields(this is because we want to check that the nick and mail aren't in use by another client before he can introduce the rest of his information(name, surname, etc.)).
So, the user introduces Nick and Email and then he must press a button named "Validate", if the values are available(successful validation) then the rest of the fields are enabled and the user can continue filling the form, otherwise the fields stay disabled and an error is showed to the user.
The form will be located in a JSP, it will be submitted to a Servlet, once in the servlet I must validate the information that is in the form(i have a .JAR file included in this servlet, the validation consists in calling a function from that library, the function returns a boolean) and then I must return back to the same JSP the boolean that will represent the result of the validate function.
Now in the JSP I must enable(or not, depending on the value of the boolean) the rest of the TextFields.
I'm not sure if this is right but i was trying to submit with the button and at the same time run a javascript(onclick) that will use this boolean value that the servlet sends back to the JSP after making the validation. The javascript consists on an IF sentence that evaluates the boolean and if it's true then it enables all the fields on the JSP.
Problems so far:
I was able to send the Nick and Email from the JSP to the Servlet and to make the validation of the values, now i have the boolean but i have no idea on how to send it from the Servlet to the same JSP and use it in the onclick event of the same button I used to submit the info. I don't even know if it's possible to do this...
I'd be grateful if someone could give me a hand with this, i'm newbie in Java programming so i would appreciate simple explanations if possible.
Also, if there is a better way of doing what i want please share it, and if there are any doubts ask and i will try to explain it better.

There is no need for JavaScript at all.
In your servlet you can store the validation result into the request context:
req.setAttribute('checkResult', checkResult);
where req is of type HttpServletRequest and checkResult is a Boolean.
Then you can forward to your JSP:
RequestDispatcher dispatcher = req.getRequestDispatcher("/your.jsp");
dispatcher.forward(req, resp);
In your JSP you can set your form elements as read only depending on the attribute checkResult which you have put into the request context:
<textarea name="text" cols="50" rows="10"
<%= request.getAttribute("checkResult") != null && request.getAttribute("checkResult") ? "" : "readonly" %>
>...</textarea>
So if the check is not valid then the <textarea> element will contain the readonly attribute. Otherwise readonly is not present.

As Roy mentioned AJAX is best suited for your problem. You can use DWR! , it makes normal java classes available as AJAX services, just call the method on them and get the result. So easy.

I think AJAX is more suitable for your application, which will not require to submit the whole form and you can send back the validation flag as plain responseText or well-formatted responseXML. Also you can use a lot of good javascript library such as jQuery that helps you send an AJAX request quickly and simply.

Related

How to maintain the contents in the text field after redircting to same page jsp.

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)

How to hide the form parameters from url after submitting a form

After submitting a form, calling an action and redirecting to show the jsp, the final url of the browser will show the action with the submit parameters as follows. Is it possible to hide the parameters ?
http://localhost:8080/myproject/login?username=aaa&password=123
Use "redirect" result type to send the redirect to the browser. The parameters should still be in your session/action context.
The comment by #sanbhat is right - use a POST request so that the parameters do not appear in the URL. Using browser dev tools or similar it's still possible to inspect the request and it's post data, there's nothing you can do about that.
In the final redirect to the result JSP, (which presumably shows what the user wrote on the form), then the fields can be populated by saving the results in session scope, so no need to have request parameters on the redirect URL.
i guess you are making a GET call here..
in the submit action make sure you specify method="post" so that password wont appear as parameter
You are using get method. Change it to post method. Example is:
form method="post" name="form name" action="Your action page"
use post method in the form , default is get so u always see the parameters in the url.
<form action="some.jsp" method="post">

How do I make use of an already existing, external servlet?

We have a form with 2 input fields.
These allow a user to type in destinations to plan a flight.
We want to use an external servlet that allows us to use autocompletion on the fields
(e.g. type "LO" and it gets the matches for that - London Heathrow would be at the top)
The servlet can be found at a URL like this: http://www.companyname.com/servlet/ac.json?n=12&q=LO
with "n" being the amount of results it should return, and "q" being the query.
How do I call that servlet from my HTML form, everytime the input field changes?
The servlet is on a different domain than my page, and I have absolutely no other access than calling it with the URL I posted.
The response from the servlet will always be a JSON string like this:
[{"type":"airport","city":"Cape Town","airport":"International","iata":"CPT","country":"South Africa","locationId":"airport_CPT"},
{"type":"city","city":"Chicago, IL","airport":"All Airports","iata":"CHI","country":"United States","locationId":"US_city_CHI"},
{"type":"airport","city":"Victoria","airport":"CA","iata":"YYJ","country":"Canada","locationId":"airport_YYJ"}]
How do I call that servlet from my HTML form, everytime the input field changes?
I strongly belive ,you need AJAX for this.If you use a normal servlet and use a form to submit each time the page will reload.
And coming to same servlet part,
You can specify the method names in AJAX request
You can try with JSP page in place of Servlet. You can call it very easily and it will complete your purpose also. Otherwise AJAX is best for this type of problem.

Spring MVC hiding url parameters on GET

I have a page that does a redirect to another page however a parameter is passed in the redirect. In the Controller there is a url mapping that matches the url with a GET method. The get method takes the parameter and sets values on the display. The url looks like this:
http://localhost:1234/appName/pageName.htm?recNo=123
However it is very easy for the user to change the parameter value from 123 to any value and then refresh the page. Once the recNo the user enters is valid and the page is refreshed the data will be displayed. I want to allow the user to only be able to view the record for the recNo that was passed. I do not want the user to be able to modify the parameter in the url.
What is the best approach to handling this in Spring MVC? The method must be a GET aftr the page is redirected.
If you're request must be GET.. it means it must be stateless. It should not rely on what the user did in the last request, which also means that all the information required for the GET request to be executed properly should be contained within the GET request.
With that in mind, the only way to pass information in the URL is by making it a part of the URI, or as a URL parameter.
So either /app/product/123 or /app/product?id=123
This exposes the URL to possible security vulnerability where the user can manipulate the id in the url,
There are two solutions:
Implement a more robust system in the backend to check that the id referenced in the GET url is associated / allowed for the user who is trying to access the URL. Basically be more explicit and deliberate about asserting your security constraints. This method will fail if your users are unauthenticated users. (No login needed).
The second solution is to expose an encrypted and encoded version of the id in the url. You should use a two way encryption though. So when the POST request completes, it encrypts and encodes the id and appends it to the subsequent GET request. When the GET request is received you decode and decrypt the url parameter to get the real id and show appropriate content. This method basically implies that it would be very difficult for a user to manipulate an ecrypted parameter such that it could be decrypted to produce a valid number. I often use AES encryption and Base 64 encoding.
Hope this helps.
if you are redirecting to page in the same application you can store this info in session use #SessionAtrribute
Assumption: If it is not mandatory to use "get" method.
I think, you can hide the parameters in URL by using "post" method , instead of "get" method.
In HTML form, you can add method="post" . Below is the example:
<form action="hello" method="post">
<input type="text" name="name" /> <br>
<input type="submit" title="Submit">
</form>

jsp to servlet communication with parameters from URL, not a form

I'm using netbeans to create a web application that allows a cell phone user to scan a QR code and retrieve a journal's previous/next title information. The take home point is that there's no form that the user will input data into. The QR code will contain the search string at the end of the URL and I want the search to start on page load and output a page with the search results. For now (due to simplicity), my model is simply parsing an XML file of a small sample of MARC records. Oh, to top it off...I'm brand new to programming in java and using netbeans. I have no clue about what javabeans are, or any of the more advance techniques. So, with that background explanation here's my question.
I have created a java class (main method) that parses my xml and retrieves the results correctly. I have an index.jsp with my html in it. Within the index.jsp, I have no problem using get to get the title information from my URL. But I have no clue how I would get those parameters to a servlet that contains my java code. If I manage to get the search string to the servlet, then I have no idea how to send that data back to the index.jsp to display in the browser.
So far every example I've seen has assumed you're getting form data, but I need parameters found, processed and returned on page load...IOW, with no user input.
Thanks for any advice.
Ceci
Just put the necessary preprocessing code in doGet() method of the servlet:
String foo = request.getParameter("foo");
// ...
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
And call the URL of the servlet instead of the JSP one e.g. http://example.com/page?foo=bar instead of http://example.com/page.jsp?foo=bar in combination with a servlet mapping on an URL pattern of /page/*.
You can get the url parameter in servlet using request.getParameter("paramName");
and you can pass the attribute to page from servlet using forwarding request from servlet to jsp.
See Also
Servlet wiki page
Bear in mind that your JSP page will compile internally to a servlet. So you can retrieve the string and print it back in the same JSP. For instance assuming you get the string in a parameter called param you would have something like this in your JSP:
<%
String param = request.getParameter( "param" );
out.println( "String passed in was " + param );
%>
One last thing, you mentioned the main method -- that only gets executed for stand alone applications -- whereas you're talking web/JSP :O

Categories