Jqgrid controller adjustments for search - java

I have been combing through the wiki for the jqgrid and i can't seem to figure out how to change the logic in my controller for the jqgrid to search.
I assume the search will use the same URL specified in the jqgrid. Here is the action logic called by my jqgrid. I am using spring 3.0 and its a java controller.
#RequestMapping(value = "studentjsondata", method = RequestMethod.GET)
public #ResponseBody String studentjsondata(HttpServletRequest httpServletRequest) {
Format formatter = new SimpleDateFormat("MMMM dd, yyyy");
String column = "id";
if(httpServletRequest.getParameter("sidx") != null){
column = httpServletRequest.getParameter("sidx");
}
String orderType = "DESC";
if(httpServletRequest.getParameter("sord") != null){
orderType = httpServletRequest.getParameter("sord").toUpperCase();
}
int page = 1;
if(Integer.parseInt(httpServletRequest.getParameter("page")) >= 1){
page = Integer.parseInt(httpServletRequest.getParameter("page"));
}
int limitAmount = 10;
int limitStart = limitAmount*page - limitAmount;
List<Person> students = Person.findStudentPeopleOrderByColumn(true, column, orderType, limitStart, limitAmount).getResultList();
long countStudents = Student.countStudents();
double tally = Math.ceil(countStudents/10.0d);
int totalPages = (int)tally;
long records = countStudents;
StringBuilder sb = new StringBuilder();
sb.append("{\"page\":\"").append(page).append("\", \"records\":\"").append(records).append("\", \"total\":\"").append(totalPages).append("\", \"rows\":[");
boolean first = true;
for (Person s: students) {
sb.append(first ? "" : ",");
if (first) {
first = false;
}
sb.append(String.format("{\"id\":\"%s\", \"cell\":[\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\"]}",s.getId(), s.getId(), s.getFirstName(), s.getLastName(), formatter.format(s.getDateOfBirth().getTime()), s.getGender(), s.getMaritalStatus()));
}
sb.append("]}");
return sb.toString();
}
and here is my navGrid decleration
$("#studentGrid").jqGrid('navGrid', "#pager", {edit:false,add:false,del:false,search:true},{ },{ },{ },
{
sopt:['eq', 'ne', 'lt', 'gt', 'cn', 'bw', 'ew'],
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true
}
);
Here is my colModel and colNames
colNames:['id','First Name', 'Last Name', 'Date Of Birth', 'Gender', 'Marital Status'],
colModel:[
{name:'id',index:'id', width:15},
{name:'firstName',index:'firstName', width:30, formoptions:{elmprefix:'(*) '}, editable:true, edittype: 'text', editrules:{required:true}},
{name:'lastName',index:'lastName', width:30, formoptions:{elmprefix:'(*) '}, editable:true, edittype: 'text',editrules:{required:true}},
{name:'dateOfBirth',index:'dateOfBirth', width:30, formoptions:{elmprefix:'(*) '},editrules:{required:true}, editable:true, edittype: 'text',
editoptions: {
dataInit: function(element) {
$(element).datepicker({dateFormat: 'MM dd, yy'})
}
}
},
{name:'gender',index:'gender', width:30, formoptions:{elmprefix:'(*) '}, editable:true, editrules:{required:true}, edittype: 'select',
editoptions:{value:{}}
},
{name:'maritalStatus',index:'maritalStatus', width:30, formoptions:{elmprefix:'(*) '}, editable:true, editrules:{required:true}, edittype: 'select',
editoptions:{value:{}}
}
]
As it is, by default the search uses trhe searchGrid method. In the post array the _search: true and filters: {"groupOp":"AND","rules":[{"field":"firstName","op":"eq","data":"Anil"}]} are present.
The searchField, searchOper and searchString are all empty but present in th epost array.
What do I have to do to get the search working?
Do I have to parse the json into Java using the json parser and the filters array, then change my query by adding a where clause and use the values form the Json object?
Does the jqgrid query its own data object insted of going back to the server and launch a new query ?
I am not too sure what I have to do, please offer some form of guidance.

I am not use Spring myself, but the post seems to me contain the information which you need.
In general if you use Advance Searching dialog (multipleSearch: true) or Toolbar Searching with stringResult: true the jqGrid send to the server additional parameter filters which format described here. The one parameter filters can contain information about multiple filters. So you have to covert JSON string to an object and analyse the object to construct some kine of WHERE part of the SELECT statement. The exact implementation is depend from the technology which you use to assess to the database.

Related

how to added dynamic query params using string in Angular 7?

Currently I have multiple dropdown field in screen. when selected dropdown value pass in the query param so I want to create dynamic query param added. my code is below
// this is one of the dropdown value
if (this.SearchText) {
query += 'q:' + SearchText + ',';
}
// this is the second one of dropdown value
if (this.MakeId) {
makename = this.SpaceToDash(this.MakesList.find(x => x.Id === +this.MakeId).Name);
navigateUrl += '/' + makename;
query += 'merk:' + this.MakeId + ',merkname:' + makename + ',';
}
this.router.navigate([ navigateUrl ], { queryParams: { query } });
So if "MakeId" is not dropdown value then should not added in "queryParams" so how can I do it. Above solution is not working it.
Apply solution for Dynamically create query Params in Angular 2 but it is not fit in my requirement. So can you help me anyone in it?
QueryParams should take an Object not a string ,
so you can do it by this way
let query = {};
// this is one of the dropdown value
if (this.SearchText) {
query['q'] = SearchText;
}
// this is the second one of dropdown value
if (this.MakeId) {
makename = this.SpaceToDash(this.MakesList.find(x => x.Id === +this.MakeId).Name);
navigateUrl += '/' + makename;
query['merk'] = this.MakeId;
query['makename'] = makename;
}
this.router.navigate([ navigateUrl ], { queryParams: query });

Angular1 : not able to pass the param to the back end

I am working with angular1 on java-spring MVC framework. I have a backend java service as :
#RequestMapping( value = "/layout/guess/{id}/{maxColumns}/{origin}", method = RequestMethod.POST )
public ResponseEntity<?> guessLayout( #PathVariable( "id" ) long id,
#PathVariable( "maxColumns" ) int maxColumns,
#RequestParam( value = "delimeter", required = true) String delimiter,
#PathVariable( "luckyOrigin" ) String origin )
{
try
{
//do something with delimiter
}
}
Now from frontend javascript controller/service I am calling the above service as (inside a function):
return $http.post( 'submenu/layout/guess/' + id + '/' + maxColumns + "/" + origin,
delimiter)
.then(
function( response )
{
return response.data;
},
function( errResponse )
{
console.error( 'Error while guessFieldLayout' );
return $q.reject( errResponse );
}
);
And always getting an error as :
Required String parameter 'delimeter' is not present
I can not use the "delimiter" as part of the URL. Any insight on what I am doing wrong?

cause of error - Jsoup.isValid

I have the following code which works but I just want to know if it is possible in Jsoup to pinpoint the exact cause of error.
The following returns true (as expected)
private void validateProtocol() {
String html = "<p><a href='https://example.com/'>Link</a></p>";
Whitelist whiteList = Whitelist.basic();
whiteList.addProtocols("a","href","tel");
whiteList.removeProtocols("a","href","ftp");
boolean safe = Jsoup.isValid(html, whiteList);
System.out.println(safe);
}
When I change the above string to it returns false(as expected)
String html = "<p><a href='ftp://example.com/'>Link</a></p>";
Now when I have the following code, there are two errors one is an invalid protocol and one is the onfocus() link.
private void validateProtocol() {
String html = "<p><a href='ftp://example.com/' onfocus='invalidLink()'>Link</a></p>";
Whitelist whiteList = Whitelist.basic();
whiteList.addProtocols("a","href","tel", "device");
whiteList.removeProtocols("a","href","ftp");
boolean safe = Jsoup.isValid(html, whiteList);
System.out.println(safe);
}
The result is false but is there any way to figure out which part of the URL is false?
for example - wrong protocol or wrong method..?
You want to create a custom whitelist with reporting feature.
MyReportEnabledWhitelist.java
public class MyReportEnabledWhitelist extends Whitelist {
private Set<String> alreadyCheckedAttributeSignatures = new HashSet<>();
#Override
protected boolean isSafeTag(String tag) {
boolean isSafe = super.isSafeTag(tag);
if (!isSafe) {
say("Disallowed tag: " + tag);
}
return isSafe;
}
#Override
protected boolean isSafeAttribute(String tagName, Element el, Attribute attr) {
boolean isSafe = super.isSafeAttribute(tagName, el, attr);
String signature = el.hashCode() + "-" + attr.hashCode();
if (alreadyCheckedAttributeSignatures.contains(signature) == false) {
alreadyCheckedAttributeSignatures.add(signature);
if (!isSafe) {
say("Wrong attribute: " + attr.getKey() + " (" + attr.html() + ") in " + el.outerHtml());
}
}
return isSafe;
}
}
SAMPLE CODE
String html = "<p><a href='ftp://example.com/' onfocus='invalidLink()'>Link</a></p><a href='ftp://example2.com/'>Link 2</a>";
// * Custom whitelist
Whitelist myReportEnabledWhitelist = new MyReportEnabledWhitelist()
// ** Basic whitelist (from Jsoup)
.addTags("a", "b", "blockquote", "br", "cite", "code", "dd", "dl", "dt", "em", "i", "li", "ol", "p", "pre", "q", "small", "span",
"strike", "strong", "sub", "sup", "u", "ul") //
.addAttributes("a", "href") //
.addAttributes("blockquote", "cite") //
.addAttributes("q", "cite") //
.addProtocols("a", "href", "ftp", "http", "https", "mailto") //
.addProtocols("blockquote", "cite", "http", "https") //
.addProtocols("cite", "cite", "http", "https") //
.addEnforcedAttribute("a", "rel", "nofollow") //
// ** Customizations
.addTags("body") //
.addProtocols("a", "href", "tel", "device") //
.removeProtocols("a", "href", "ftp");
boolean safeCustom = Jsoup.isValid(html, myReportEnabledWhitelist);
System.out.println(safeCustom);
OUTPUT
Wrong attribute: href (href="ftp://example.com/") in Link
Wrong attribute: onfocus (onfocus="invalidLink()") in Link
Wrong attribute: href (href="ftp://example2.com/") in Link 2
false

Retrieve data from a form using jquery

I'm trying to get information from a form and passing it to mysql. Here is my method:
var form = [];
$("input").each(function(){
var id = $(this).attr("name");
var value = $(this).val();
alert(id);
var item = {};
item ["name"] = id;
item ["value"] = value;
form.push(item);
});
return JSON.stringify(form);
The problem is when i try to get the checked and unchecked values from the radio buttons. The query string that I want to pass to mysql outputs like this:
insert into contatos (nome, rua, sexo, sexo, ncasa, civil, civil, civil, bairro, aniversario, cidade, rg, cpf, usuario, telefone, senha, email, confirmasenha) values ('', '', 'M', 'F', '', 'S', 'C', 'D', '', '', '', '', '', '', '', '', '', '')
The fields "sexo" and "civil" are repeating. How do I make the input to read the radio buttons only 1 time?
It is because you are iterating over each text field and if you have 3 radio button you are pushing all 3 values to array so I took 2 radio fields sexo and civil outside loop so It will be pushed only 1 time and not be repeated.
$("input").each(function(){
if(id!='sexo' || id!='civil'){
var id = $(this).attr("name");
var value = $(this).val();
var item = {};
item ["name"] = id;
item ["value"] = value;
form.push(item);
}
});
var value1 =$('input:radio[name=sexo]:checked').val();
var value2 =$('input:radio[name=civil]:checked').val();
var item = {};
item ["name"] = "sexo";
item ["value"] = value1;
form.push(item);
var item = {};
item ["name"] = "civil";
item ["value"] = value2;
form.push(item);
return JSON.stringify(form);
If you call serializeArray on a jQuery form element you'll get an array of objects, similar to the one you are creating, and will avoid duplicates:
$('form').serializeArray();
will return:
[
{
name: "firstfield",
value: "1"
},
{
name: "secondfield",
value: "2"
}
]

jQuery Select2 and Struts 2 JSON plugin

I'm trying to populate with Struts2 JSON and Select2 a select. Server is returning a JSON like this:
{"orphanets":[{"idDiagOrphanet":11509,"nomDiagOrphanet":"FACOMATOSIS CESIOFLAMMEA"},{"idDiagOrphanet":21782,"nomDiagOrphanet":"AUTOINFLAMMATION"}]}
How can I format/parse the result to make it work? I know it expects id and text fields, but cant get it working:
$("#selCodOrphanet").select2({
quietMillis: 300,
placeholder: "Buscar diag. Orphanet...",
minimumInputLength: 4,
ajax: {
url: '../json/getOrphanets',
dataType: 'json',
data: function (term, page) {
return {
term: term
};
},
results: function (data, page) {
return { results: data.orphanets };
},
id: function(item) {
return item.idDiagOrphanet;
},
formatResult: function(item) {
return "<div class='select2-user-result'>" + item.nomDiagOrphanet + "</div>";
}
}
});
I tried a bit searching but didn't found id: function(item) {
Anyways, here's a quick-fix
Consider the response as a normal string
replace idDiagOrphanet with id and nomDiagOrphanet with text and then return this string instead of return { results: data.orphanets };
Here's another way :
Modifying a JSON object by creating a New Field using existing Elements
var ornts= data.orphanets;
var new_obj ;
for(var i=0; i<data.orphanets.length; i++){
var person = persons[i];
new_obj.push({
id: ornts.idDiagOrphanet,
text: ornts.nomDiagOrphanet,
});
}
return new_obj;
Try
$("#selCodOrphanet").select2({
placeholder: "Buscar diag. Orphanet...",
minimumInputLength: 4,
ajax: {
url: '<s:url namespace="/json" action="getOrphanets"/>',
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term
};
},
results: function (data, page) {
return { results: data.orphanets };
},
id: function(item) {
return item.idDiagOrphanet;
},
formatResult: function(item) {
return "<div class='select2-user-result'>" + item.nomDiagOrphanet + "</div>";
}
escapeMarkup: function (m) { return m; }
}
});
Added the qualified URL mapping to getOrphanets action with namespace /json. Corresponding configuration should be made. Don't escape markup since you are displaying HTML in results.

Categories

Resources