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.
Related
I'm trying to implement a basic web application from the values that we are getting from web-service, it will include two datatables, each of them need to be populated in server-side.
For example, web-service have a structure like this ( Let's say these are books)
Firstly i am getting the string GUID value for the objects that i want to get an information, after that i am sending a request with the parameter of this GUIDs to service to get information XML for these book objects that includes name, page and author of them.
But as an important information, my servlet needs to get these values dynamically as soon as the page of datatable is changed, if this datatable will include 30 book ( i will get the 30 guid firstly so i can clarify that ) after that, send one request for 10 of them to show them on first page of datatable, if user clicked on page two, server behind needs to send request for the other group of ten and returns me result to show on the table.
I tried to implement the structure below :
http://www.codeproject.com/Articles/359750/jQuery-DataTables-in-Java-Web-Applications#ServerSideProcessing
but it populates a table with the DataRepository ones with all of them, so with this point of view i can't use it dynamically as i totally requested.
The main need for this, XML return for many objects needs so long time.
So do you know any example link or tutorial such a need for this ?
Thank you for informations in advance!
#Hayra, thanks for providing the Code Project link to the JQuery-DataTable example, it is very helpful. This is something that I might implement soon.
What I understood from the example, the JQuery-DataTable keeps track for you specific parameters that will allow you to return the exact number of records. The specific parameters that you need are "iDisplayStart" and the iDisplayLength". The "iDisplayLength" is set when the user specifies 10 records per page and the iDisplayStart, will is set when the page number changes.
So look at the code in the Code Project example doGet Method, this section of the code returns only the subset of records back to your table.
JQueryDataTableParamModel param = DataTablesParamUtility.getParam(request);
if(companies.size()< param.iDisplayStart + param.iDisplayLength) {
companies = companies.subList(param.iDisplayStart, companies.size());
} else {
companies = companies.subList(param.iDisplayStart, param.iDisplayStart + param.iDisplayLength);
}
try {
JsonObject jsonResponse = new JsonObject();
jsonResponse.addProperty("sEcho", sEcho);
jsonResponse.addProperty("iTotalRecords", iTotalRecords);
jsonResponse.addProperty("iTotalDisplayRecords", iTotalDisplayRecords);
for(Company c : companies){
JsonArray row = new JsonArray();
row.add(new JsonPrimitive(c.getName()));
row.add(new JsonPrimitive(c.getAddress()));
row.add(new JsonPrimitive(c.getTown()));
data.add(row);
}
jsonResponse.add("aaData", data);
response.setContentType("application/Json");
response.getWriter().print(jsonResponse.toString());
} catch (JsonIOException e) {
e.printStackTrace();
response.setContentType("text/html");
response.getWriter().print(e.getMessage());
}
I hope this help
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.
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
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.
I am creating a web application using EJBs and servlets. I have a page which displays a list of all items in the database. I would like to provide an option for the user to click on one of these items and this opens the SHOW servlet which gathers info regarding the item onto the page. I do not want to create a page for every single item. Instead I would like to create ONE SHOW servlet which can be used for all items. I am not sure how to provide this option through clicking on the name of an item, and also how to send the parameters...since it depends on what item the user chose.
Can someone help me please?
Thank you
When you generate the product listing, you can just make the IDs of all the database items parameters in the link.
Product Foo
Then in the doGet() method of your ShowProduct servlet, you can call the HttpServletRequest.getParameterValues() method to get that parameter's values and do the lookup in your database.
e.g.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String[] params = request.getParameterValues("productID");
String productID = params[0];
...
}
Pass the unique ID of the item into the SHOW servlet. Then get that item's data from the DB and create your new page with that data.
Try having the show link point to your show servlet like this:
"/ShowServlet?itemID="+itemID