DataTables server-side pagination - java

I have working Spring REST app with client side pagination, default by DataTables and everything works. Now i need to change it to server-side pagination i have problem, because have no idea how to get information from DataTables what page number client want to see. I can't find anything usefull in DT manual.

When you say Datatable I assume you are talking about DataTables jQuery plugin.
To activate serverside pagination you need to pass
"serverSide": true,
like this:
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "/your_url"
});
Doing the above will activate your server-side pagination. But you need to do few changes on the server-side too. Let's see them step by step.
1. What happens when you mark serverSide as true
DataTables plugin adds custom parameters to the AJAX call with information like
order: asc
start: 20
length: 10
// and many more.
You can inspect this demo link and see the parameters passed in request when you click the next page button.
2. Similarly, DataTables plugin expects some fields in response in order to preserve pagination logic.
"draw": 3, // unique ID
"recordsTotal": 57, // total number of records
"recordsFiltered": 57 // total number of filtered records
You can inspect this demo link and see response data this time.
3. Now changes are on serverside in your API
You need to add these parameters as queryParam for GET and attr in POST call in your controller API:
order: asc
start: 20
length: 10
4. Service Layer Changes - DB query
In-Service Layer where you get details from a database.
You need to get the total number of records and in search query pass a LIMIT clause LIMIT 10, 10 in case of MySQL.
E.g.:
SELECT * FROM User LIMIT 20,10;
Use start and length to calculate the next set of records.
It can be trickier but if you understand and implement properly it's fun.
Read more in detail here which also contains code and live demo.

Please see the sample about DataTables server-side processing:
https://datatables.net/examples/server_side/simple.html
After change page, you can capture the request to server as following format:
https://.../server_processing.php?draw=3&columns...&order=0&dir=asc&start=20&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1534436781912
That means DataTable requests page number 3 (draw=3), order by first column ascending, ....
At server side (REST), you can get page number by (for example) request.getParameter("draw")

Related

Hiding information for a particular user

I am using RESTFUL webservices using Spring framework.Some information is displayed on the user interface using the data returned by webservices. There is a webservice, which gets the usernames and their roles from the database. For a particular user , I would like to have all the webservices display data in the form of ####,#### for first name,lastname ; ##/##/#### for date of birth etc. Since I am using JDBC to connect to the database, here's what I was thinking of doing:
Should I consider passing an additional parameter (maybe sending a value 0 or 1 ; 0 for all other users and 1 for user for which I want to hide the information) to each and every GET webservice so that when it comes to getting data from the database in the JDBC code part,I could check whether the flag is set to 1 or 0 and based on this, I could do something like this in the JDBC code :
// Code for a case when flag is set to `0`. Hence retrieving information from the database.
while(rs.next()) {
EmployeeList empList = new EmployeeList();
empList.setEmpId(empId);
empList.setEmployeeName(rs.getString("name"));
employeeList.add(empList);
}
// Code for a case when flag is set to `1`. Hence hiding information and not retrieving information from the database.
while(rs.next()) {
EmployeeList empList = new EmployeeList();
empList.setEmpId(empId);
empList.setEmployeeName("####,######");
employeeList.add(empList);
}
I am wondering, if this is an appropriate way to achieve my task or is there some other way around?
Edit:More clarifications on my requirements:
I am using jqxWidget in the UI to display the information I am getting from a RESTFUL webservice in JSON format. For example, let's consider this example and the screenshot for better understanding of my requirement:
1) Let's say I am getting all the information from the JSON response which I am populating in the jQXWidget as shown in the screenshot above.
2) In the above widget, I would like to hide say for example, First Name, Last Name and Quantity like the following:
First Name = XXXXX
Last Name = XXXXX
Quantity = ####
In my application, if a user clicks on a particular row , a new page is displayed with some additional information. After click, new sets of web services are called and those web services takes First Name, Last Name and Quantity as input parameters. My concern is that, if I somehow replace the First Name with XXXXX, Last Name with XXXXX and Quantity with #### using any approach, when a user clicks on any of the row of the widget, the next set of web services
are going to get XXXX and #### as input and eventually will fail. Please correct me if my understanding until this point is not correct.
Thanks
I am using Spring 4.2.5 version.
This depends on what sort of information hiding you want to achieve. Typically you shouldn't do this manually.
You can use, for example, role-based authorization. Exact details depends on the web-service framework you are using.
For spring MVC, you can use something similar to this:
Custom authorization in Spring MVC

Dynamodb AWS Java scan withLimit is not working

I am trying to use the DynamoDBScanExpression withLimit of 1 using Java aws-sdk version 1.11.140
Even if I use .withLimit(1) i.e.
List<DomainObject> result = mapper.scan(new DynamoDBScanExpression().withLimit(1));
returns me list of all entries i.e. 7. Am I doing something wrong?
P.S. I tried using cli for this query and
aws dynamodb scan --table-name auditlog --limit 1 --endpoint-url http://localhost:8000
returns me just 1 result.
DynamoDBMapper.scan will return a PaginatedScanList - Paginated results are loaded on demand when the user executes an operation that requires them. Some operations, such as size(), must fetch the entire list, but results are lazily fetched page by page when possible.
Hence, The limit parameter set on DynamoDBScanExpression is the maximum number of items to be fetched per page.
So in your case, a PaginatedList is returned and when you do PaginatedList.size it attempts to load all items from Dynamodb, under the hood the items were loaded 1 per page (each page is a fetch request to DynamoDb) till it get's to the end of the PaginatedList.
Since you're only interested in the first result, a good way to get that without fetching all the 7 items from Dynamo would be :
Iterator it = mapper.scan(DomainObject.class, new DynamoDBScanExpression().withLimit(1)).iterator();
if ( it.hasNext() ) {
DomainObject dob = (DomainObject) it.next();
}
With the above code, only the first item will fetched from dynamodb.
The take away is that : The limit parameter in DynamoDBQueryExpression is used in the pagination purpose only. It's a limit on the amount of items per page not a limit on the number of pages that can be requested.

How can I retrieve the string passed after ? in a URL in a JSP

I have a servlet that communicates with MySQL database and displays the information receive using a JSP (using offset and limit in MySQL). I want to implement pagination and buttons to sort the data. All of the required info for the SQL query is sent through the URL so it looks something like
http://localhost:8080/proj2/SearchMovieListServlet?txt_movie_genre=Biography&txt_order_by=title&txt_sql_order=ASC&txt_sql_limit=5&txt_pg=1
and what I want to accomplish is href a "next" and "previous" button and link it to the URL above, but with the txt_pg incremented/decremented by 1. How can I do this easily without rebuilding the URL?

Adding and Deleting row from table in JSP and update them in Spring MVC form's list

I am a bit new to Spring MVC, so need to your help on updating the form in spring mvc !!
I am working on Spring MVC based application. I have an "updateForm" and this form contains one list named listOfMyCustomObjects, i am using this list to iterate in jsp using JSTL, so i am able to view all the records present in the list.
Now the requirement is:
I have to provide the option to Add/Delete the records from the table, so i have coded for Adding/removing the records from table using javascript.(Just from view the records are getting added/deleted).
I have to update the Addition/Deletion of records in updateForm as well.
Note: Addition/Deletion of records is temporary on the screen, and finally there is a save button which will hit the controller.
So, Please guide me, how can i update the Added/Deleted record in my spring mvc updateForm, so that when 'SAVE' button is pressed, the request should have the correct listOfMyCustomObjects.
You have basically 2 ways of doing that :
the javascript way : keep in javascript a list of all deletions an insertions and send it to controller using Json, something like { 'del' : [ 'id1', 'id2', ...], 'add' : [ { 'key1' : 'val1', ...}, { 'key1' : 'val1', ...}, ...]}. The controller takes it and passes the 2 lists to the service layer which delete and insert lines in only single transaction.
the submit way : the controller receives a copy of what is displayed on screen and passes it to the service layer. The service layer deletes all lines not present (maybe through a full select of ids) and insert lines that have no id.
First way requires more work in client side, because you have to keep the history of what happened. Second requires mode work in server side because you have to find what lines have been deleted.
The sam ecan be achieved by 'clone()' method of Jquery.
1.) Create an empty Div -> row.
2.) Have a '+' button, and clone it using baove function.
3.) Reset the indexes of your list.
4.) For deleting the records if they are persisted, need to fire ajax call, if not persisted just delete from DOM.
Better solution can be to have a child jsp page included inside parent page. Here child will refer to list<object>, for every CRUD opertion just fire the ajax call, do all the manipulation and return the child page in reponse.
Refresh only this particular DIV contating chile JSP to display list. (Using JSTL)

jqgrid: change value of select

I am developing a web application using JSP & Servlet (IDE: Eclipse, Database: Oracle10). I am using jqGrid to display records in tabular format.
code snippet:
{name:'CITY',index:'CITY', width:70,editable:true,edittype:"select",editoptions: {dataUrl: 'ProfileServ?action=comboCity', dataEvents: [{ type: 'change', fn: function(e) {alert(this.value);city= this.value;}}],}},
{name:'PIN',index:'PIN', width:200,sortable:false,editable:true, edittype:"select",editoptions: {dataUrl: 'ProfileServ?action=comboPin'}},
I want to change values of PIN according to the value selected in CITY. I have used dataEvents and type: 'change' to get the selected value of CITY. I am successfully getting the selected value of CITY.
My question is that how should I update the values of PIN when value of CITY is changed?
Unfortunately there is no easy way to implement dependent selects. One have to update the whole <select> of dependent select manually inside of change callback (update selects of PIN in your case). The only which I can suggest you is examining the code of the demo from the answer. It is not exactly what you need because it don't use dataUrl, but it shows what should be done.

Categories