Jqgrid spring date binding exception - spring

OS: Windows Vista, Framework: Jqgrid (latest), Spring (latest), JQuery (latest)
I am using Jqgrid to post a form to Spring Controller to persist. When the Spring controller tries to auto bind the request parameters to domain object, it throws exception when trying to bind 'Date' data type. I am using JSon format for transfer data. The Jqgrid display the date correctly. The transfer string contains '&-quot;' characters before and after the date that causes the exception. I dont know how to remove the escape character from Jqgrid. I dont know how to intercept the string before Spring gets a chance to auto bind. Thanks for your help in advance.
public class JsonDateSerializer extends JsonSerializer<Date> {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
AtOverride
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String formattedDate = dateFormat.format(date);
gen.writeString(formattedDate);
}
}
My controller class has initBinder method.
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
Exception stack trace
nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "2010-12-01 11:10:00" from type 'java.lang.String' to type 'java.util.Date'; nested exception is java.lang.IllegalArgumentException]
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doBind(HandlerMethodInvoker.java:820)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:359)

I will try to set-up a tutorial on my blog if I get the time today.
My JSP file is just a simple JSP file with your typical JqGrid declaration:
<script type="text/javascript">
jq(function() {
// This is the grid
jq("#grid").jqGrid({
url:'/myapp/users',
datatype: 'json',
mtype: 'GET',
colNames:['Id','Username','First Name'],
colModel:[
{name:'id',index:'id', width:55,editable:false,editoptions:{readonly:true,size:10},hidden:true},
{name:'firstName',index:'firstName', width:100,editable:true, editrules:{required:true}, editoptions:{size:10}, editrules:{required:true}},
{name:'lastName',index:'lastName', width:80, align:"right",editable:true, editrules:{required:true}, editoptions:{size:10}, editrules:{required:true}}
],
postData: {
// Here you can post extra parameters
// For example using JQuery you can retrieve values of other css elements
},
rowNum:10,
rowList:[10,20,30],
height: 200,
autowidth: true,
rownumbers: true,
pager: '#pager',
sortname: 'id',
viewrecords: true,
sortorder: "asc",
caption:"Users",
emptyrecords: "Empty records",
loadonce: false,
loadComplete: function() {
// Here you can provide extra functions after the grid is loaded completely
// Like auto-height function
},
jsonReader : {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
cell: "cell",
id: "id"
}
});
// This is the pager
jq("#grid").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 }
);
// Custom Add button on the pager
jq("#grid").navButtonAdd('#pager',
{ caption:"Add",
buttonicon:"ui-icon-plus",
onClickButton: addRow,
position: "last",
title:"",
cursor: "pointer"
}
);
// Custom Edit button on the pager
jq("#grid").navButtonAdd('#pager',
{ caption:"Edit",
buttonicon:"ui-icon-pencil",
onClickButton: editRow,
position: "last",
title:"",
cursor: "pointer"
}
);
// Custom Delete button on the pager
jq("#grid").navButtonAdd('#pager',
{ caption:"Delete",
buttonicon:"ui-icon-trash",
onClickButton: deleteRow,
position: "last",
title:"",
cursor: "pointer"
}
);
// Toolbar Search
jq("#grid").jqGrid('filterToolbar',{stringResult: true,searchOnEnter : true, defaultSearch:"cn"});
});
Take note I'm using JQuery's noConflict method here. Since I have another Javascript framework that uses the $, I forced JQuery to use a different identifier for itself. I picked jq and here's the declaration:
<script type="text/javascript">
var jq = jQuery.noConflict();
</script>
The Javascript's above can be declared on the head section of your JSP. The critical part of the JqGrid declaration is the jsonReader and the datatype. Make sure the colModel name matches your model properties.

You could probably use StringTrimmerEditor's second constructor to delete those extra chars
StringTrimmerEditor(String charsToDelete, boolean emptyAsNull)
Based on the Spring docs:
charsToDelete - a set of characters to delete, in addition to trimming an input String. Useful for deleting unwanted line breaks. E.g. "\r\n\f" will delete all new lines and line feeds in a String.
I also use the latest version of JqGrid and Spring 3, but the way I handled the parameters seems to be simpler. Here's how I did it:
#Controller
#RequestMapping("/json")
public class JsonController {
#RequestMapping(method = RequestMethod.GET)
public #ResponseBody JsonResponse getAll(
#RequestParam("_search") String search,
#RequestParam(value="filters", required=false) String filters,
#RequestParam(value="datefrom", required=false) String datefrom,
#RequestParam(value="dateto", required=false) String dateto,
#RequestParam(value="page", required=false) String page,
#RequestParam(value="rows", required=false) String rows,
#RequestParam(value="sidx", required=false) String sidx,
#RequestParam(value="sord", required=false) String sord
) { ... }
All parameters are passed as normal Strings. The datefrom and dateto are custom parameters I passed from the JqGrid. The date comes from a JQuery's DatePicker and passed via JqGrid postData:
postData: {
datefrom: function() { return jq("#datepicker_from").datepicker("getDate"); },
dateto: function() { return jq("#datepicker_to").datepicker("getDate"); }
},
JsonResponse is a simple POJO that I used to map the search parameters passed by a JqGrid:
public class JsonResponse {
/**
* Current page of the query
*/
private String page;
/**
* Total pages for the query
*/
private String total;
/**
* Total number of records for the query
*/
private String records;
/**
* An array that contains the actual data
*/
private List<MyDTO> rows;
public JsonResponse() {
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getRecords() {
return records;
}
public void setRecords(String records) {
this.records = records;
}
public List<MyDTO> getRows() {
return rows;
}
public void setRows(List<MyDTO> rows) {
this.rows = rows;
}
}
MyDTO is a simple DTO object as well.
In my Spring applicationContext.xml, I just have to declare the following:
<mvc:annotation-driven/>
And added the Jackson jar for converting from JSON to POJO and vice versa
To convert the String date to a real Date, I used the great Joda library. But of course, you can use JDK's standard Date.

If you notice on my JSP, I added custom buttons. The onClickButton calls another Javascript function. For example on the Add button, I have the addRow function. Here's the function declaration:
function addRow() {
// Get the currently selected row
jq("#grid").jqGrid('editGridRow','new',
{ url: "/myapp/users/add",
editData: {
// Here you add extra post parameters
},
recreateForm: true,
beforeShowForm: function(form) {
// Here you can add, disable, hide elements from the popup form
},
closeAfterAdd: true,
reloadAfterSubmit:false,
afterSubmit : function(response, postdata)
{
// This is a callback function that will evaluate the response sent by your Controller
var result = eval('(' + response.responseText + ')');
var errors = "";
if (result.success == false) {
// Do whatever you like if not successful
} else {
// Do whatever you like if successful
}
// only used for adding new records
var new_id = null;
// Then this will be returned back to the popup form
return [result.success, errors, new_id];
}
});
}
Take note of the url:
url: "/myapp/users/add"
This is the mapping to your Controller that handles the add request

Now, for the Jackson serialization/deserialization, you'll be suprised how easy it is.
First, make sure you have the latest Jackson library in your classpath. Next, open your Spring xml config, and add the following:
<mvc:annotation-driven/>
That's it :)
Make sure you have the latest dependency jars. I use Spring 3.0.4. There's 3.0.5 already. Also, make sure you have the latest aspectjweaver.jar. If you wanna know what's inside that mvc-annotation-driven tag, just search the web and you'll see what it contains. Basically it automatically declares an HTTPMessageConverter for JSON, and uses Jackson by default.

For the Controller, here's the mapping to the /myapp/users/add request:
#Controller
#RequestMapping("/myapp/users")
public class UserController {
#RequestMapping(value = "/add", method = RequestMethod.POST)
public #ResponseBody JsonGenericResponse addAsJson(
#RequestParam("id") String id,
#RequestParam("firstName") String firstName,
#RequestParam("lastName") String lastName
) {
// Validate input
// Process data. Call a service, etc.
// Send back a response
// JsonGenericResponse is a custom POJO
// Jackson will automatically serialize/deserialize this POJO to a JSON
// The #ResponseBody annotation triggers this behavior
JsonGenericResponse response = new JsonGenericResponse();
response.setSuccess(false);
response.setMessage("Error in server");
return response;
}
}
Here's the JsonGenericResponse:
public class JsonGenericResponse {
private Boolean success;
private List<String> message;
public JsonGenericResponse() {
message = new ArrayList<String>();
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public List<String> getMessage() {
return message;
}
public void setMessage(String message) {
this.message.add(message);
}
}
It's just really a simple POJO.
In your JSP, to process the response, you use JavaScript in your JqGrid. The response will be sent back to whomever the caller (the add form in this case). Here's a sample JavaScript that will process the response:
if (result.success == false) {
for (var i = 0; i < result.message.length; i++) {
errors += result.message[i] + "<br/>";
}
} else {
jq("#dialog").text('Entry has been edited successfully');
jq("#dialog").dialog(
{ title: 'Success',
modal: true,
buttons: {"Ok": function() {
jq(this).dialog("close");}
}
});
}
return [result.success, errors, null];

Related

Highchart in Spring boot

I try to use hightchart in spring boot to plot a line graph. But I can't get line chart but only show blank result in my view.
This is my view side
$.ajax({
url:'${pageContext.request.contextPath}/hawker/linechartdata',
dataType: 'json'
success: function(result){
var month = JSON.parse(result).month;
var report = JSON.parse(result).report;
drawLineChart(month, report);
}
})
function drawLineChart(month,report){
document.addEventListener('DOMContentLoaded', function () {
var chart = Highcharts.chart('container', {
chart: {
type: 'line'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: month
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: report
}]
});
});
}
<!--Here to show the graph -->
<div id="container"></div>
My controller that use Json
#RequestMapping("/linechartdata")
#ResponseBody
public String getDataFromDb(#AuthenticationPrincipal UserDetails user) {
User currentuser = userRepository.findByUsername(user.getUsername());
Optional<Hawker> hawker = hawkerService.getHawkerByUserId(currentuser.getId());
//Get the report list
List<Report> reportList = reportService.findByHawId(hawker.get().getHaw_id());
JsonArray jsonMonth = new JsonArray();
JsonArray jsonReport = new JsonArray();
JsonObject json = new JsonObject();
reportList.forEach(report->{
jsonMonth.add(report.getMonth()+1);
jsonReport.add(report.getTotal_sales());
});
json.add("month", jsonMonth);
json.add("report", jsonReport);
return json.toString();
When I remove the ajax and add in the manual data, it do show the graph. Please help me, Thank you.
You don't need to manually create json in your controller code, spring boot will handle it for you. You should create a dto class in a form which is expected by your javascript.
Which is in your case:
public class LineChartDto {
private List<Integer> month; // you better call this "months" or "monthList"
private List<BigDeciamal> report; // why do you call this "report" while this is actually "sales"
// all args constructor, getters
}
And your controller method would be:
#RequestMapping("/linechartdata")
#ResponseBody // or use #RestController
public LineChartDto getSalesLineChartData(..) {
List<Report> reportList = ..
List<Integer> months = reportList.stream()
.map(report -> report.getMonth()+1)
.collect(Collectors.toList());
List<BigDecimal> sales = reportList.stream()
.map(Report::getTotal_sales) // better name this getTotalSales
.collect(Collectors.toList());
return new LineChartDto(months, sales);
}
Response will result in json object:
{
"month": [1, 2, ... ],
"report": [100, 200, ... ]
}
As for why you ajax doesn't work - the question is too broad. Start with Chrome Dev Tools Network to check what network communication is happening, check browser console for errors, add some console.log() or better debug your js.
This line document.addEventListener('DOMContentLoaded', function () looks suspicious to me. I don't think you need to addEventListener each time you call your chart.
Probably you should do this:
function drawLineChart(month,report){
Highcharts.chart('container', {
...

$.ajax to send data vis HttpPost in aspnet5 is not working

this is a followup question to the one here Using $.ajax to send data via HttpPost in aspnet5, is not working
I have made the changes requested in the comments and a few other changes such as using the Json package from Newtonsoft.
Basically I have a column, and when you click the header a couple of input tags appear dynamically, to change column name and submit it. I want to change it and show it right away using ajax. The code to do this is below, and sorry but the code is in coffee script. Also I am using ASPNET5 RC1 with MVC6.
SumbitColumnForm = () ->
$('.panel-heading').on 'click', 'input.ColumnTitleSumbit', (event) ->
event.preventDefault();
columnName = $('.NewColumnName').val().trim()
columnNumber = $(this).parent().parent().attr 'id'
$.ajax
url: '/Board/ChangeColumnName',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({ColumnName: columnName, ColumnNumber: columnNumber})
success: (data) ->
alert "Hit the Success part"
alert 'data is' + data
panelHeading = $('input.ColumnTitleSubmit').parent()
$(panelHeading).html("<h3 class='panel-title'> <h3>").text(data)
error: (xhr, err) ->
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
The relevant action methods from the controller are below
[Route("{p_BoardName}")]
public IActionResult Show(string p_BoardName)
{
m_Board.BoardName = p_BoardName;
ViewData["BoardName"] = m_Board.BoardName;
return View(m_Board);
}
[HttpPost]
public JsonResult ChangeColumnName(string newColumnData)
{
ColumnModel column = JsonConvert.DeserializeObject<ColumnModel>(newColumnData);
// Update column name in the board model, the board model stores a list of columns
m_Board.ColumnList[column.ColumnNumber].ColumnName = column.ColumnName;
var json = JsonConvert.SerializeObject( m_Board.ColumnList[column.ColumnNumber]);
return Json(json);
}
Also the column and board models are below
public class ColumnModel
{
private string m_name;
private int m_columnNumber;
public int ColumnNumber { get { return m_columnNumber; } set {m_columnNumber = value;} }
public string ColumnName { get { return m_name;} set { m_name = value; } }
public ColumnModel(string p_Name, int p_ColumnNumber)
{
m_name = p_Name;
m_columnNumber = p_ColumnNumber;
}
public ColumnModel() { }
}
public class BoardModel
{
private string m_BoardName;
private List<ColumnModel> m_ColumnList;
[Required]
public string BoardName { get { return m_BoardName; } set { m_BoardName = value; } }
public List<ColumnModel> ColumnList
{
get { return m_ColumnList; }
set { m_ColumnList = value; }
}
}
I have done a lot of googling and I still can't get this to work. The request is not hitting the success attribute and is hitting the error attribute. I still get a 200 status code to show it is OK, and for some reason my data is a long html file, or in this case the 'Show' view from the board controller. I have requested requested Json and I am getting html. I don't know what is going on, I feel what might be going wrong is the http post method ChangeColumnName in the controller. Maybe I am not receiving or sending a valid JSON object. Any help will be greatly appreicated.
The key here is [ValidateInput(false)]
Try this :
Rather than sending a JSON.stringify, just send it as an object which means
var Data = {ColumnName: columnName, ColumnNumber: columnNumber};
You were already doing this from your link!
Change your signature to receive your ColumnModel directly rather than a string and add the attribute [ValidateInput(false)] to your action. You'll not need to deserialize with this approach!
[ValidateInput(false)]
public JsonResult ChangeColumnName(ColumnModel newColumnData)
{
Console.WriteLine(newColumnData.ColumnName);
}
Let me know if this solves your problem!
You are supplying the correct variable
in ajax
data: {ColumnName: columnName, ColumnNumber: columnNumber}
In controller
[HttpPost]
public JsonResult ChangeColumnName(string ColumnName, int ColumnNumber)
{
..your code..
}
hope this helps

ModelState validation fails for nullable types

Can't pass ModelState validation in WebApi application for object which contains nullable types and has null values. The error message is "The value 'null' is not valid for DateProperty."
The code of object:
public class TestNull
{
public int IntProperty { get; set; }
public DateTime? DateProperty { get; set; }
}
Controller:
public class TestNullController : ApiController
{
public TestNull Get(int id)
{
return new TestNull() { IntProperty = 1, DateProperty = null };
}
public HttpResponseMessage Put(int id, TestNull value)
{
if(ModelState.IsValid)
return Request.CreateResponse(HttpStatusCode.OK, value);
else
{
var errors = new Dictionary<string, IEnumerable<string>>();
foreach (var keyValue in ModelState)
{
errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage);
}
return Request.CreateResponse(HttpStatusCode.BadRequest, errors);
}
}
}
Request:
$.getJSON("api/TestNull/1",
function (data) {
console.log(data);
$.ajax({
url: "api/TestNull/" + data.IntProperty,
type: 'PUT',
datatype: 'json',
data: data
});
});
I just did a quick test in one my own WebAPI projects and passing null as a value for a nullable value-type works fine. I suggest you inspect the actual data that is being send to your server using a tool like Fiddler
Two valid scenarios that will work are:
{ IntProperty: 1, DateProperty: null }
{ IntProperty: 1 } // Yes, you can simply leave the property out
Scenarios that will NOT work are:
{ IntProperty: 1, DateProperty: "null" } // Notice the quotes
{ IntProperty: 1, DateProperty: undefined } // invalid JSON
{ IntProperty: 1, DateProperty: 0 } // Will not be properly interpreted by the .NET JSON Deserializer
If the two default scenario's do not work then I suspect your problem lies elsewhere. I.e. Have you changed any of the default settings of the JSON serializer in your global.asax?
Almost 9 years later I'm still having similar problem in ASP.NET Core 3.1
But I've found a working workaround for me (just exclude null values from data being sent - as opposed to sending values as nulls).
See https://stackoverflow.com/a/66712465/908608
It's not a real solution, becasue backend still does not handle null values properly, but at least ModelState validation does not fail for nullable properties.

STRUTS2 and AJAX - Select the country, populate the States

I want to show the states after selecting the country.
JSP
<s:select label="COUNTRY" name="summaryData.addressCountry" id="addForm_countryCode"
list="loyaltyCountryMap" tabindex="" headerKey="US" headerValue="United States"
listKey="key" listValue="value.countryName"
onchange="getStateList('#addForm_countryCode')">
</s:select>
<s:select label="STATE" name="summaryData.addressCityCode" headerValue="-Select-" headerKey="-Select-" list="stateList" required="true" cssClass="storedPaymentInput_size1 required" id="stateList"/>
JAVASCRIPT:
function getStateList() {
var countryCode = $('#addForm_countryCode").val();
$.ajax({
url: 'ajaxStateList',
dataType: 'html',
data: { countryCode : countryCode},
success: function(data) {
$('#stateList').html( data );
}
});
}
STRUTS.XML
<action name="ajaxStateList" class="actions.AjaxStateList">
<result name="success"/>
</action>
ACTION CLASS
private List<String> stateList;
private String countryCode;
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public List<String> getStateList() {
return stateList;
}
public void setStateList(List<String> stateList) {
this.stateList = stateList;
}
public String execute() {
LoyaltyStateProvinces.getInstance();
stateList = StateProvinces.getAllStateProvinceByCountryCode(countryCode);
for(StateProvince state: states){
stateList.add(state.getStateProvinceCode());
}
return SUCCESS;
}
How can I make it work using AJAX+Struts2?
See struts2-json-plugin. Have your actions return a json result type (via this plugin). Your action class can remain largely unmodified.
Once you have created and tested that your action returns JSON (just enter the url in your browser). Then you need some javaScript. I see you are using jQuerys $.ajax method... I prefer the $.getJSON which does the same but assumes the data in a json format.
Here is some js from my own code:
function punch(){
$.getJSON("<s:url namespace="/timeclock/json" action="punch"/>",
{
badge: $("#input_badge").val()
},
function(data) {
$("#input_badge").val("");
$("#emp_name").text(data.name);
$("#emp_time").text(data.punch);
$("#notification").fadeIn("slow", hide);
});
return false;
}
You'll notice three parameters: Fist being the url for the call which is always best constructed with the sturts2 url tag. Second being the parameters being sent to the action, in this case "badge" is set to what ever was in the text field with the id of "input_badge" and then sent to the server. Finally the function which is called when the call back succeeds, you can see parameters such as "name", "punch" are returned.

EXTJS and Spring MVC Portlet File Upload

I have successfully been able to upload a file to my ActionResponse method in my controller for my spring portlet using extjs. My problem is that extjs is expecting a json response in order to know the upload is complete, and the response for my action request renders out the entire portal.
I am needing a way to tell the response for my request to only be a json string.
here is my controller.
#Controller
#RequestMapping(value = "VIEW")
public class MediaRoomViewController {
private static final Logger _log = Logger.getLogger(MediaRoomViewController.class);
#RenderMapping
public String renderView(RenderRequest request, RenderResponse response, Model model){
return "view";
}
#InitBinder
protected void initBinder(PortletRequest request, PortletRequestDataBinder binder) throws Exception {
// to actually be able to convert Multipart instance to byte[]
// we have to register a custom editor
binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
// now Spring knows how to handle multipart object and convert
}
#ActionMapping(params="action=uploadFile")
public String uploadFile(FileUploadBean uploadItem, BindingResult result,ActionResponse response) throws Exception {
_log.debug("Upload File Action");
ExtJSFormResult extjsFormResult = new ExtJSFormResult();
try{
if (result.hasErrors()){
for(ObjectError error : result.getAllErrors()){
System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
}
//set extjs return - error
extjsFormResult.setSuccess(false);
}
// Some type of file processing...
System.err.println("-------------------------------------------");
System.err.println("Test upload: " + uploadItem.getFile().getOriginalFilename());
System.err.println("-------------------------------------------");
//set extjs return - sucsess
extjsFormResult.setSuccess(true);
}catch(Exception ex){
_log.error(ex,ex);
}
return extjsFormResult.toString();
}
here is my extjs file upload code
Ext.create('Ext.form.Panel', {
title: 'File Uploader',
width: 400,
bodyPadding: 10,
frame: true,
renderTo: self._Namespace + 'file-upload',
items: [{
xtype: 'filefield',
name: 'file',
fieldLabel: 'File',
labelWidth: 50,
msgTarget: 'side',
allowBlank: false,
anchor: '100%',
buttonText: 'Select a File...'
}],
buttons: [{
text: 'Upload',
handler: function() {
var form = this.up('form').getForm();
if(form.isValid()){
form.submit({
url: self._Urls[0],
waitMsg: 'Uploading your file...',
success: function(form,action) {
alert("success");
},
failure: function(form,action){
alert("error");
}
});
}
}
}]
});
There are several ways to go here:
Manually force response as text like this
response.setContentType("text/html"); //or json if u wish
responseText = "{'success':'true'}";
response.getWriter().write(responseText);
Use Jackson lib as covered here:
Spring 3.0 making JSON response using jackson message converter
Move on to Grails and forget about verbose MVC configs. My preferred method :)

Resources