inserting only unique values on click of submit button - java

The scenario is such that i am accepting a unicode string from user on webpage and on click of the submit button the control moves to the next page where the complete logic of processing the string is written using a bean class at the same time i m inserting the string into the database by giving call to function of DAO class from inside bean class so as to maintain the log.
the problem is that when user refreshes the result page the bean class is getting called again and again and hence the same string is getting inserted into the database by the same user several times.
what should i do such that string inserted by the same user gets inserted into database only when user presses the submit button not while refreshing the result page.
or should i maintain the cookies with string as values from the user and check it when page gets loaded.
i am trying to maintain cookies at client side for the string that was previously entered by the user and check it accordingly
private void fnSetCookieValues(HttpServletRequest request,
HttpServletResponse response) {
Cookie[] cookies=request.getCookies();
for (int i = 0; i < cookies.length; i++) {
System.out.println("" + cookies.length + "Name" + cookies[i].getName());
if(cookies[i].getName().equals("DNString")) {
System.out.println("Inside if:: " + cookies[i].getValue() +
"" + cookies.length);
cookies[i].setValue(request.getParameter("txtString"));
} else {
Cookie ck = new Cookie("DNString", ";");
response.addCookie(ck);
}
}
}
This piece of code is written in servlet which gets called on submit button click
but each processing of this servlet displays 1NameJSESSIONID it is not showing the cookie DNString
Can anybody figure out the mistake i am doing?

you are looking into a way to prevent double-submits?
There are a couple of approaches, depending on your security needs and the frameworks you are using:
Java Script
Tokens
Synchronization
Google around a bit. There are many many solutions out there.
Thanks,
M

It is not good approach to check whether data is already entered or not.
So, One of the easy solution to this problem is to use HTTP redirect after the form submission from your servlet.Let say to success.jsp. Hence the form is not submitted again.
You can also reset your form once you get response.
For More check here

Related

How to prevent duplicate entries when page is refreshed

In my web page after a chain of actions the client sees the details of the reservation. The method used to populate the data to be displayed in these details also stores the reservation in the database:
#RequestMapping(params = { "complete" }, method = RequestMethod.POST, produces = "text/html")
public String completeReservation(Model uiModel, HttpServletRequest httpServletRequest, ...) {
// ...
reservation.persist();
// ...
uiModel.addAttribute(...);
uiModel.addAttribute(...);
// ...
return "reservations/success";
}
The success page is the one that displays the details.
However, if I refresh the page another reservation entry is stored and I don't want this to happen.
Any suggestions on how I should approach this problem?
Commonly this is solved by making two actions - one that's doing the business (stores a reservation) and second one that shows the result to the user.
After successfull storing of reservation in the first action, redirect to the second one. From user point of view it will be one action and if he hits the reload button, only view action is performed again.

How to design properly the logic of getting data from DB in the case of pagination (JAVA)?

Ok, I am building an app in client and it needs to take data from DB. The app won't take all data from DB all at once but based on the pagination.
It has a simple textbox for user to enter text and a Button to search data.
Requirements:
-If the system already downloaded the data from a certain pageNo, then it won't call to server again.
-Each time it successfully called to server it needs to remember the pageNo, so that next time when user searching for that exact term it
will search for pageNo=pageNo+1 cos we searched for pageNo
already.
So here is what i did:
private HashMap<String, Integer> wordPageNoHashMap=new HashMap<String, Integer>();
button.addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
int pageNo=0;
if(wordPageNoHashMap.containsKey(word)){
pageNo=wordPageNoHashMap.get(word); //note: page no only increase if found result
}
else{
pageNo=1;
wordPageNoHashMap.put(word, pageNo);
}
callToDB(word,pageNo);
}
});
public void resultFromDB(ServerResult result){
int pageNo=result.getPageNo();
String word=result.getWord();
List<String> textResult=result.getResult();
if(textResult!=null && textResult.size()>0){
pageNo++;
wordPageNoHashMap.put(word, pageNo);
//show data here
}
else{
//show err here
}
}
I putting pageNo++ at the result not at the time we call.
Am i designning it ok?
or
Can u do a better design?
Assuming my understanding is correct, for a search query I will retrieve a reasonable number of records from the DB (say 500) and store it in something like a PagedListHolder and set the per page data to whatever number you want(say 20).
Now I have two options, when the user clicks next I will simply call the nextPage() and retrieve the data set. (This might be applicable for infinite loading)
Or if the user is clicks on a particular page number (conventional pagination), I will pass on the page number to the setPage() method and retrieve the elements from that page.
I have used the PagedlistHolder example to make it easy for you to understand. You may use any similiar Class if available, or you can write one.
I think this achieves your objective of not hitting the DB for the same set of data.
Let me know if it helped.

Trigger javascript from android app

I'm pretty new to android development. One of my buttons in the app, sends the user to a webpage, where the user can login into specific system.
The webpage has text boxes for username and password. Once you click on the Login button (in the webpage) it triggers a javascript to login into the system.
The code triggered is: onclick="updateAction('TourAccLogin');document.main_form.submit();
The webpage form to login:
My question is:
I have the username and password in the app, I want to know if I can somehow manipulate this form, the sign in automatically without user interference? Meaning, I will fill the username and password, I "click" the login button. So the user will be directed to the system right away, without having to put in the username and password.
This technique has worked for me. In my case, I'm loading a hidden field named in mElementId with a string value stored in someData, then firing its onchange event, which didn't fire on its own. I included it to show how you can stack javascript commands in a single injection. I'm sure a variant of this would work for you.
I also escaped any single quotes to prevent a javascript error. You may need to escape any other special characters, including semicolon. In my case it wasn't necessary because the data had already been cleansed.
// Copy data to element
mWebView.loadUrl("javascript:(function() { " +
"document.getElementById('" + mElementId + "').value = '" +
someData.replace("'", "\'") + "'; " +
"document.getElementById('" + mElementId + "').onchange();" +
"})()");
You say that it is your system, so you know what is running behind the scenes to process the login. I'm not mocking, just verifying. I'm assuming you've created a view of some sort where you have the username/password prior to doing this. I'm questioning this because you ask if there is a way of manipulating the form...
That being said, send the data as you normally would to the script that processes the login. If you're using a GET then http://some.domain.com/somescript?username=mumble&password=foo. If you're using a POST then create the post args and send it. Either way, you can process the results in a webview, which would allow your existing interface to pick up where it should.
Of course, if you're using a hash for the password or salting the password, you will need to do all that prior to sending it.

Download Pandora source with Java?

I'm trying to download www.pandora.com/profile/stations/olin_d_kirkland HTML with Java to match what I get when I select 'view page source' from the context menu of the webpage in Chrome.
Now, I know how to download webpage HTML source code with Java. I have done it with downloads.nl and tested it on other sites. However, Pandora is being a mystery. My ultimate goal is to parse the 'Stations' from a Pandora account.
Specifically, I would like to grab the Station names from a site such as www.pandora.com/profile/stations/olin_d_kirkland
I have attempted using the selenium library and the built in URL getter in Java, but I only get ~4700 lines of code when I should be getting 5300. Not to mention that there is no personalized data in the code, which is what I'm looking for.
I figured it was that I wasn't grabbing the JavaScript or letting the JavaScript execute first, but even though I waited for it to load in my code, I would only always get the same result.
If at all possible, I should have a method called 'grabPageSource()' that returns a String. It should return the source code when called upon.
public class PandoraStationFinder {
public static void main(String[] args) throws IOException, InterruptedException {
String s = grabPageSource();
String[] lines = s.split("\n\r");
String t;
ArrayList stations = new ArrayList();
for (int i = 0; i < lines.length; i++) {
t = lines[i].trim();
Pattern p = Pattern.compile("[\\w\\s]+");
Matcher m = p.matcher(t);
if (m.matches() ? true : false) {
Station someStation = new Station(t);
stations.add(someStation);
// System.out.println("I found a match on line " + i + ".");
// System.out.println(t);
}
}
}
public static String grabPageSource() throws IOException {
String fullTxt = "";
// Get HTML from www.pandora.com/profile/stations/olin_d_kirkland
return fullTxt;
}
}
It is irrelevant how it's done, but I'd like, in the final product, to grab a comprehensive list of ALL songs that have been liked by a user on Pandora.
The Pandora pages are heavily constructed using ajax, so many scrapers struggle. In the case you've shown above, looking at the list of stations, the page actually puts through a secondary request to:
http://www.pandora.com/content/stations?startIndex=0&webname=olin_d_kirkland
If you run your request, but point it to that URL rather than the main site, I think you will have a lot more luck with your scraping.
Similarly, to access the "likes", you want this URL:
http://www.pandora.com/content/tracklikes?likeStartIndex=0&thumbStartIndex=0&webname=olin_d_kirkland
This will pull back the liked tracks in groups of 5, but you can page through the results by increasing the 'thumbStartIndex' parameter.
Not an answer exactly, but hopefully this will get you moving in the correct direction:
Whenever I get into this sort of thing, I always fall back on an HTTP monitoring tool. I use firefox, and I really like the Live HTTP Headers extension. Check out what the headers are that are going back and forth, then tailor your http requests accordingly. As an absolute lowest level test, grab the header from a successful request, then send it to port 80 using telnet and see what comes back.

Java not whole object returned?

I am developing JSF but the problem is in the java I believe. Ok so I have a table with requests, when I press the id of the request that is sent to the reviewRequest page with:
<h:inputHidden id="id" value="#{requestClass.requestID}" />
Now that's working because I load the request details on next page (by taking ID and retrieving object from database). now when I modify the object from reviewRequest and accept, it says it is stored successfully. I then view the same page again from table I click the request id and there it goes bang nullpointerexception. When it is loading the object this time, it pass the id to retrieve method then it only returns the change but not the whole object details like name, contacts, etc. only that the user of type x submitted modification y. retrieve method from DB works for sure because all over the app it is working correctly. Any idea? some of the code below for illustration:
public void callIsValidUser(){
boolean holder = isValidUser();
if(holder == true){
rsvIns = loadDetails();
}else{
try{
FacesContext.getCurrentInstance().getExternalContext().dispatch("pending.xhtml");
}catch(IOException ioe){
System.err.print(ioe);
}
}
}
the method above works the first time but not after modification. in isValid():
public boolean isValidUser(){
boolean valid = false;
try{
rsvLocal = oracleRsv.retrieveReservation(id);
String reqDivHead = rsvLocal.rdhUser.getUserID();
//rsvLocal.rdhUser.getUserResponse();
String supervisor = rsvLocal.sUser.getUserID();
String divHead = rsvLocal.dhUser.getUserID();
String currentUser = System.getProperty("user.name");
.....
now when I inspect the rsvLocal in netbeans debug mode, i see that rdhUser.response holds the modification I entered but all rest is null. How can this happen? how can some data be retrieved from object?
Thanks,
Most likely you did not load the data at the very beginning. Then JSF created an empty bean and sets the values from the form. Now everything not mentioned in the form (and of course every empty field of the form) contains null. This half-baked bean is now stored in the DB overwriting the complete row. If you now load the row again you will see what you call "my modifications" but what is the complete content of the DB. Your old data is lost.
The key point is: JSF and the DB-Layers do not deal with "modifications" of individual fields - they handle complete entities.

Categories

Resources