How to send string[] to the spring controller? - java

I have the following JQuery code which sends some request parameters to my Spring MVC controller. For some parameters I should get multiple values.
$('#tb-email').click(function(event) {
var base, data, formats, recipients, reportSource, reportSourceType;
if ($(this).parent('li').hasClass('disabled')) {
return false;
}
base = "<base href=\"" + window.location.protocol + "//" + window.location.host + window.DashboardGlobals.baseUrl + "\">";
data = $('html').clone().find('script').remove().end().find('nav').remove().end().find('#dashboardCanvas').removeClass('dashboardCanvas').end().find('head').prepend(base).end().html();
data = encodeURIComponent(Base64.encode('<html>' + data + '</html>'));
$.post(window.DashboardGlobals.sendMail, {
formats: ['png', 'pdf'],
recipients: ['abc#xyz.com', 'xyz#abc.com'],
reportSource: data, //Base64 data
reportSourceType: 'adhoc',
reportName: 'DataQualityApp'
});
event.preventDefault();
});
When the tb-email is clicked, request is submitted to some controller which is saved in the DashboardGlobals variable.
At the server side I have written the following Java code to get the multiple values for the parameters formats and recipients.
public #ResponseBody String process(#RequestParam("formats") String[] formats, #RequestParam("recipients") String[] recipients, #RequestParam("reportSource") String reportSource, #RequestParam("reportSourceType") String reportSourceType, HttpServletRequest request) {
...Some Processing....
return null;
}
I checked the formats and recipients length which is 1.
I even tried to get the values using
String[] formats = request.getParameterValues("formats");
String[] recipients = request.getParameterValues("recipients");
Still I am getting single values in the array. The length is still one?
What is going wrong?

You may try this, spring controller can take csv as array or list:
$.post(window.DashboardGlobals.sendMail, {
formats: ['png', 'pdf'].join(","),//<-- create csv string
recipients: ['abc#xyz.com', 'xyz#abc.com'].join(","),//<-- create csv string
...
});
OR
$.post(window.DashboardGlobals.sendMail, {
formats: 'png,pdf',
recipients: 'abc#xyz.com,xyz#abc.com',
...
});

Related

Unable to pass Array from Angular 2 typescript to Spring Java

I am trying to pass a String array from my typescript
tmp : Array<string> = [];
So I have a function which takes in this array as a parameter input
passValues(test : Array<string>) {
........
// some method to call post method from service
}
So in service
public passingOfValues( test : Array<string> ) : Observable<Array<string>> {
let headers = new Headers({ 'Content-Type': 'application/json'} );
let options = new RequestOptions({ headers: headers);
let response = this.http.post(this.basePath + this.modulePath + '/getArrayValue', {'test' : test }, options)
.map(this.extractData)
.catch(this.handleError);
return response;
}
But I am getting errors such as System property [org.owasp.esapi.devteam] is not set
And I read on other posts that I have to stringify the array before passing to backend.
Is there a reason why I need to stringify / also can I just pass the raw array?
EDIT 1 :
including backend controller codes
public ResponseEntity<?> getArrayValues( ArrayList<String> test ) {
logger.debug("### Test if array has a size ###" + test.size());
}
Apparently size already shows 0 from here.
EDIT 2 :
While debugging, i realised that the SQL at the back is receiving
say
HOME CHARACTER(20 OCTETS)
does this make any difference?
Like passing of string into octets or do I have to do some conversion?
Sorry if I have alot of questions am also working hard on debugging and learning more about it!
Most of the developers like JSON data as request and it's good practice in RESTful apis. why?
JSON format is {key1: value1, key2: value 2,....}
You are passing
this.http.post(this.basePath + this.modulePath + '/getArrayValue',{'test' : YOUR_ACTUAL_ARRAY})
form the front-end. The httpClient.post(url,body,options?) has url and body as mandatory. How can you get it in back-end? Since you have body only,
public ResponseEntity<?> getArrayValues(#RequestBody List<String> test) {
// codes
}
Key of passed parameter from front-end test and variable which
listens in back-end should be in same name. Otherwise
#RequestBody("KEY_NAME") List<String> any_variable
As you asked from comment, you may have two key value pairs. Eg : { "test" : value1, "tmp": value2}. Assume value1 and value2 both are String array.
this.http.post(this.basePath + this.modulePath + '/getArrayValue',{'myJson' : YOUR_JSON})
There are lot of way(Eg : Gson,ObjectMapper etc). I use another way.
Create a class called TestTmpConverter
class TestTmpConverter{
List<String> test;
List<String> tmp;
//No-argument constructors & Argument constructors
//Getters
}
In controller
public ResponseEntity<?> getArrayValues(#RequestBody List<TestTmpConverter> myJson ) {
List<TestTmpConverter> test=myJson.getTest();
List<TestTmpConverter> tmp=myJson.getTmp();
// Do your work
}
I only showed one way.There are a lot of way to pass data to back-end like #RequestParam, #PathVariable etc. I feel now you get something how you can pass the data.
For your client put your data directly on POST's body:
public passingOfValues( test : Array<string> ) : Observable<Array<string>> {
let headers = new Headers({ 'Content-Type': 'application/json'} );
let options = new RequestOptions({ headers: headers);
let response = this.http.post(this.basePath + this.modulePath + '/getArrayValue',
test, options)
.map(this.extractData)
.catch(this.handleError);
return response;
}
On your REST service use the #RequestBody annotation:
public ResponseEntity<?> getArrayValues(#RequestBody String[] test ) {
logger.debug("### Test if array has a size ###" + test.size());
}

How to export repeat grid layout data to Excel using pzRDExportWrapper in Pega 7.1.8?

I am trying to export repeat grid data to excel. To do this, I have provided a button which runs "MyCustomActivity" activity via clicking. The button is placed above the grid in the same layout. It also worth pointing out that I am utulizing an article as a guide to configure. According to the guide my "MyCustomActivity" activity contains two steps:
Method: Property-Set, Method Parameters: Param.exportmode = "excel"
Method: Call pzRDExportWrapper. And I pass current parameters (There is only one from the 1st step).
But after I had got an issue I have changed the 2nd step by Call Rule-Obj-Report-Definition.pzRDExportWrapper
But as you have already understood the solution doesn't work. I have checked the log files and found interesting error:
2017-04-11 21:08:27,992 [ WebContainer : 4] [OpenPortal] [ ] [ MyFW:01.01.02] (ctionWrapper._baseclass.Action) ERROR as1|172.22.254.110 bar - Activity 'MyCustomActivity' failed to execute; Failed to find a 'RULE-OBJ-ACTIVITY' with the name 'PZRESOLVECOPYFILTERS' that applies to 'COM-FW-MyFW-Work'. There were 3 rules with this name in the rulebase, but none matched this request. The 3 rules named 'PZRESOLVECOPYFILTERS' defined in the rulebase are:
2017-04-11 21:08:42,807 [ WebContainer : 4] [TABTHREAD1] [ ] [ MyFW:01.01.02] (fileSetup.Code_Security.Action) ERROR as1|172.22.254.110 bar - External authentication failed:
If someone have any suggestions and share some, I will appreciate it.
Thank you.
I wanted to provide a functionality of exporting retrieved works to a CSV file. The functionality should has a feature to choose fields to retrieve, all results should be in Ukrainian and be able to use any SearchFilter Pages and Report Definition rules.
At a User Portal I have two sections: the first section contains text fields and a Search button, and a section with a Repeat Grid to display results. The textfields are used to filter results and they use a page Org-Div-Work-SearchFilter.
I made a custom parser to csv. I created two activities and wrote some Java code. I should mention that I took some code from the pzPDExportWrapper.
The activities are:
ExportToCSV - takes parameters from users, gets data, invokes the ConvertResultsToCSV;
ConvertResultsToCSV - converts retrieved data to a .CSV file.
Configurations of the ExportToCSV activity:
The Pages And Classes tab:
ReportDefinition is an object of a certain Report Definition.
SearchFilter is a Page with values inputted by user.
ReportDefinitionResults is a list of retrieved works to export.
ReportDefinitionResults.pxResults denotes a type of a certain work.
The Parameters tab:
FileName is a name of a generated file
ColumnsNames names of columns separated by comma. If the parameter is empty then CSVProperties is exported.
CSVProperties is a props to display in a spreadsheet separated by comma.
SearchPageName is a name of a page to filter results.
ReportDefinitionName is a RD's name used to retrieve results.
ReportDefinitionClass is a class of utilized report definition.
The Step tab:
Lets look through the steps:
1. Get an SearchFilte Page with a name from a Parameter with populated fields:
2. If SearchFilter is not Empty, call a Data Transform to convert SearchFilter's properties to Paramemer properties:
A fragment of the data Transform:
3. Gets an object of a Report Definition
4. Set parameters for the Report Definition
5. Invoke the Report Definition and save results to ReportDefinitionResults:
6. Invoke the ConvertResultsToCSV activity:
7. Delete the result page:
The overview of the ConvertResultsToCSV activity.
The Parameters tab if the ConvertResultsToCSV activity:
CSVProperties are the properties to retrieve and export.
ColumnsNames are names of columns to display.
PageListProperty a name of the property to be read in the primay page
FileName the name of generated file. Can be empty.
AppendTimeStampToFileName - if true, a time of the file generation.
CSVString a string of generated CSV to be saved to a file.
FileName a name of a file.
listSeperator is always a semicolon to separate fields.
Lets skim all the steps in the activity:
Get a localization from user settings (commented):
In theory it is able to support a localization in many languages.
Set always "uk" (Ukrainian) localization.
Get a separator according to localization. It is always a semicolon in Ukrainian, English and Russian. It is required to check in other languages.
The step contains Java code, which form a CSV string:
StringBuffer csvContent = new StringBuffer(); // a content of buffer
String pageListProp = tools.getParamValue("PageListProperty");
ClipboardProperty resultsProp = myStepPage.getProperty(pageListProp);
// fill the properties names list
java.util.List<String> propertiesNames = new java.util.LinkedList<String>(); // names of properties which values display in csv
String csvProps = tools.getParamValue("CSVProperties");
propertiesNames = java.util.Arrays.asList(csvProps.split(","));
// get user's colums names
java.util.List<String> columnsNames = new java.util.LinkedList<String>();
String CSVDisplayProps = tools.getParamValue("ColumnsNames");
if (!CSVDisplayProps.isEmpty()) {
columnsNames = java.util.Arrays.asList(CSVDisplayProps.split(","));
} else {
columnsNames.addAll(propertiesNames);
}
// add columns to csv file
Iterator columnsIter = columnsNames.iterator();
while (columnsIter.hasNext()) {
csvContent.append(columnsIter.next().toString());
if (columnsIter.hasNext()){
csvContent.append(listSeperator); // listSeperator - local variable
}
}
csvContent.append("\r");
for (int i = 1; i <= resultsProp.size(); i++) {
ClipboardPage propPage = resultsProp.getPageValue(i);
Iterator iterator = propertiesNames.iterator();
int propTypeIndex = 0;
while (iterator.hasNext()) {
ClipboardProperty clipProp = propPage.getIfPresent((iterator.next()).toString());
String propValue = "";
if(clipProp != null && !clipProp.isEmpty()) {
char propType = clipProp.getType();
propValue = clipProp.getStringValue();
if (propType == ImmutablePropertyInfo.TYPE_DATE) {
DateTimeUtils dtu = ThreadContainer.get().getDateTimeUtils();
long mills = dtu.parseDateString(propValue);
java.util.Date date = new Date(mills);
String sdate = dtu.formatDateTimeStamp(date);
propValue = dtu.formatDateTime(sdate, "dd.MM.yyyy", "", "");
}
else if (propType == ImmutablePropertyInfo.TYPE_DATETIME) {
DateTimeUtils dtu = ThreadContainer.get().getDateTimeUtils();
propValue = dtu.formatDateTime(propValue, "dd.MM.yyyy HH:mm", "", "");
}
else if ((propType == ImmutablePropertyInfo.TYPE_DECIMAL)) {
propValue = PRNumberFormat.format(localeCode,PRNumberFormat.DEFAULT_DECIMAL, false, null, new BigDecimal(propValue));
}
else if (propType == ImmutablePropertyInfo.TYPE_DOUBLE) {
propValue = PRNumberFormat.format(localeCode,PRNumberFormat.DEFAULT_DECIMAL, false, null, Double.parseDouble(propValue));
}
else if (propType == ImmutablePropertyInfo.TYPE_TEXT) {
propValue = clipProp.getLocalizedText();
}
else if (propType == ImmutablePropertyInfo.TYPE_INTEGER) {
Integer intPropValue = Integer.parseInt(propValue);
if (intPropValue < 0) {
propValue = new String();
}
}
}
if(propValue.contains(listSeperator)){
csvContent.append("\""+propValue+"\"");
} else {
csvContent.append(propValue);
}
if(iterator.hasNext()){
csvContent.append(listSeperator);
}
propTypeIndex++;
}
csvContent.append("\r");
}
CSVString = csvContent.toString();
5. This step forms and save a file in server's catalog tree
char sep = PRFile.separatorChar;
String exportPath= tools.getProperty("pxProcess.pxServiceExportPath").getStringValue();
DateTimeUtils dtu = ThreadContainer.get().getDateTimeUtils();
String fileNameParam = tools.getParamValue("FileName");
if(fileNameParam.equals("")){
fileNameParam = "RecordsToCSV";
}
//append a time stamp
Boolean appendTimeStamp = tools.getParamAsBoolean(ImmutablePropertyInfo.TYPE_TRUEFALSE,"AppendTimeStampToFileName");
FileName += fileNameParam;
if(appendTimeStamp) {
FileName += "_";
String currentDateTime = dtu.getCurrentTimeStamp();
currentDateTime = dtu.formatDateTime(currentDateTime, "HH-mm-ss_dd.MM.yyyy", "", "");
FileName += currentDateTime;
}
//append a file format
FileName += ".csv";
String strSQLfullPath = exportPath + sep + FileName;
PRFile f = new PRFile(strSQLfullPath);
PROutputStream stream = null;
PRWriter out = null;
try {
// Create file
stream = new PROutputStream(f);
out = new PRWriter(stream, "UTF-8");
// Bug with Excel reading a file starting with 'ID' as SYLK file. If CSV starts with ID, prepend an empty space.
if(CSVString.startsWith("ID")){
CSVString=" "+CSVString;
}
out.write(CSVString);
} catch (Exception e) {
oLog.error("Error writing csv file: " + e.getMessage());
} finally {
try {
// Close the output stream
out.close();
} catch (Exception e) {
oLog.error("Error of closing a file stream: " + e.getMessage());
}
}
The last step calls #baseclass.DownloadFile to download the file:
Finally, we can post a button on some section or somewhere else and set up an Actions tab like this:
It also works fine inside "Refresh Section" action.
A possible result could be
Thanks for reading.

How to download a file from AJAX request in Liferay serveResource(-, -) method

I have a requirement like: I am making an AJAX request to pass some data to server. In my server I am creating a file using that data.
"Now problem is the file is not getting downloaded to client-side".
(I am using Apache POI API to create excel file from the given data).
Can any one will help me to do this ?
Here is my code:
(Code to make AJAX request)
<script>
function downloadUploadedBacklogs () {
try {
var table_data = [];
var count = jQuery("#backlogTable tr:first td" ).length;
jQuery("#<portlet:namespace/>noOfColumns").val(count);
var index = 0;
jQuery('tr').each(function(){
var row_data = '';
jQuery('td', this).each(function(){
row_data += jQuery(this).text() + '=';
});
table_data.push(row_data+";");
});
jQuery("#<portlet:namespace/>backlogDataForDownload").val(table_data);
jQuery("#<portlet:namespace/>cmd").val("downloadUploadedBacklogs");
alert('cmd: ' + jQuery("#<portlet:namespace/>cmd").val());
var formData = jQuery('#<portlet:namespace/>backlogImportForm').serialize();
jQuery.ajax({
url:'<%=resourceURL%>',
data:formData,
type: "post",
success: function(data) {
}
});
alert('form submitted');
} catch(e) {
alert('eroor: ' + e);
}
};
</script>
Java code serveResource(-,-) method
/*
* serveResource(-, -) method to process the client request
*/
public void serveResource(ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws IOException,
PortletException {
String cmd = ParamUtil.getString(resourceRequest,"cmd");
System.out.println("**********************cmd*************"+cmd);
if(cmd!="") {
if("downloadUploadedBacklogs".equalsIgnoreCase(cmd)){
String backlogData = ParamUtil.getString(resourceRequest, "backlogDataForDownload");
ImportBulkDataUtil.downloadUploaded("Backlogs", resourceRequest,resourceResponse);
}
}
}
/
* ImportBulkDataUtil.downloadUploaded(-, -, -) method to create excel file
/
public static void downloadUploaded(String schema, ResourceRequest resourceRequest,ResourceResponse resourceResponse) {
String excelSheetName = ParamUtil.getString(resourceRequest,"excelSheetName");
try {
resourceResponse.setContentType("application/vnd.ms-excel");
resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+excelSheetName+"_Template.xls");
OutputStream outputStream=resourceResponse.getPortletOutputStream();
//converting the POI object as excel readble object
HSSFWorkbook objHSSFWorkbook=new HSSFWorkbook();
HSSFSheet objHSSFSheet=objHSSFWorkbook.createSheet(excelSheetName+"_Template");
//set the name of the workbook
Name name=objHSSFWorkbook.createName();
name.setNameName(excelSheetName+"_Template");
objHSSFSheet.autoSizeColumn((short)2);
// create freeze pane (locking) top row
objHSSFSheet.createFreezePane(0, 1);
// Setting column width
String excelData = StringPool.BLANK;
if((schema.equalsIgnoreCase("Backlogs"))){
System.out.println("Inside BacklogsCreation..........");
objHSSFSheet.setColumnWidth(0, 10000);
objHSSFSheet.setColumnWidth(1, 7000);
objHSSFSheet.setColumnWidth(2, 7000);
objHSSFSheet.setColumnWidth(3, 7000);
objHSSFSheet.setColumnWidth(4, 7000);
objHSSFSheet.setColumnWidth(5, 5000);
objHSSFSheet.setColumnWidth(6, 5000);
objHSSFSheet.setColumnWidth(7, 7000);
objHSSFSheet.setColumnWidth(8, 7000);
excelData = ParamUtil.getString(resourceRequest,"backlogDataForDownload");
}
System.out.println("downloadUploaded excelTableData: " + excelData);
// Header creation logic
HSSFRow objHSSFRowHeader = objHSSFSheet.createRow(0);
objHSSFRowHeader.setHeightInPoints((2*objHSSFSheet.getDefaultRowHeightInPoints()));
CellStyle objHssfCellStyleHeader = objHSSFWorkbook.createCellStyle();
objHssfCellStyleHeader.setFillBackgroundColor((short)135);
objHssfCellStyleHeader.setAlignment(objHssfCellStyleHeader.ALIGN_CENTER);
objHssfCellStyleHeader.setWrapText(true);
// Apply font styles to cell styles
HSSFFont objHssfFontHeader = objHSSFWorkbook.createFont();
objHssfFontHeader.setFontName("Arial");
objHssfFontHeader.setColor(HSSFColor.WHITE.index);
HSSFColor lightGrayHeader = setColor(objHSSFWorkbook,(byte) 0x00, (byte)0x20,(byte) 0x60);
objHssfCellStyleHeader.setFillForegroundColor(lightGrayHeader.getIndex());
objHssfCellStyleHeader.setFillPattern(CellStyle.SOLID_FOREGROUND);
objHssfFontHeader.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
objHssfFontHeader.setFontHeightInPoints((short)12);
objHssfCellStyleHeader.setFont(objHssfFontHeader);
objHssfCellStyleHeader.setWrapText(true);
// first column about Backlog title
HSSFCell objBacklogTitleCell = objHSSFRowHeader.createCell(0);
objBacklogTitleCell.setCellValue("Backlog");
objBacklogTitleCell.setCellStyle(objHssfCellStyleHeader);
// second column about Description
HSSFCell objBacklogDescCell = objHSSFRowHeader.createCell(1);
objBacklogDescCell.setCellValue("Description");
objBacklogDescCell.setCellStyle(objHssfCellStyleHeader);
// third column about Project
HSSFCell objProjectNameCell = objHSSFRowHeader.createCell(2);
objProjectNameCell.setCellValue("Project");
objProjectNameCell.setCellStyle(objHssfCellStyleHeader);
setComment("Project which the backlog belongs to", objProjectNameCell);
// fourth column about Category
HSSFCell objCategoryNameCell = objHSSFRowHeader.createCell(3);
objCategoryNameCell.setCellValue("Category");
objCategoryNameCell.setCellStyle(objHssfCellStyleHeader);
setComment("Category which the backlog belongs to (i.e. Bug, New Requirement, Enhancement)", objCategoryNameCell);
// fifth column about Group
HSSFCell objGroupNameCell = objHSSFRowHeader.createCell(4);
objGroupNameCell.setCellValue("Group");
objGroupNameCell.setCellStyle(objHssfCellStyleHeader);
setComment("Group which the backlog belongs to", objGroupNameCell);
// sixth column about Est. Start Date
HSSFCell objEstStartDtCell = objHSSFRowHeader.createCell(5);
objEstStartDtCell.setCellValue("Est. Start Date");
objEstStartDtCell.setCellStyle(objHssfCellStyleHeader);
setComment("Date Format: dd/mm/yyyy", objEstStartDtCell);
// seventh column about Est. End Date
HSSFCell objEstEndDtCell = objHSSFRowHeader.createCell(6);
objEstEndDtCell.setCellValue("Est. End Date");
objEstEndDtCell.setCellStyle(objHssfCellStyleHeader);
setComment("Date Format: dd/mm/yyyy", objEstEndDtCell);
// fifth column about Group
HSSFCell objStatusCell = objHSSFRowHeader.createCell(7);
objStatusCell.setCellValue("Status");
objStatusCell.setCellStyle(objHssfCellStyleHeader);
String excelTableDataRecords[] = excelData.split(";");
for(int i=1; i<excelTableDataRecords.length; i++) {
HSSFRow objHSSFRow = objHSSFSheet.createRow(i);
objHSSFRow.setHeightInPoints((2*objHSSFSheet.getDefaultRowHeightInPoints()));
excelTableDataRecords[i] = excelTableDataRecords[i].substring(0, (excelTableDataRecords[i].length()-2));
if(excelTableDataRecords[i].charAt(0) == ',') {
excelTableDataRecords[i] = excelTableDataRecords[i].substring(1, (excelTableDataRecords[i].length()));
}
String excelTableColumns[] = excelTableDataRecords[i].split("::");
for(int j=0; j<excelTableColumns.length; j++) {
// Apply font styles to cell styles
HSSFFont objHssfFont = objHSSFWorkbook.createFont();
objHssfFont.setFontName("Arial");
CellStyle objHssfCellStyle = objHSSFWorkbook.createCellStyle();
objHssfFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
objHssfFont.setColor(HSSFColor.BLACK.index);
objHssfFont.setFontHeightInPoints((short)10);
objHssfCellStyle.setWrapText(true);
objHssfCellStyle.setFont(objHssfFont);
// other column about Backlog title
HSSFCell objNewHSSFCellFirstNameAdd = objHSSFRow.createCell(j);
objNewHSSFCellFirstNameAdd.setCellValue(excelTableColumns[j]);
objNewHSSFCellFirstNameAdd.setCellStyle(objHssfCellStyle);
}
}
objHSSFWorkbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Exception raised in downloadUploaded() method to download uploaded excel data");
}
}
Can anyone help me ?
There could be 2 issues. Either you don't send file at all or ajax is not downloading it.
From your code I can see that you writing file in response's output stream so I suspect that part is working. Maybe you can open browser developer tool to see response from server if it contains data in response body.
Second part is complicated because from nature of JS (security reason) you cannot download directly in JS itself (download will not start itself).
You need to use either iframe and append file url into and submit form to start download
$("body").append("<iframe src='" + data.message + "' style='display: none;' ></iframe>");
or
you can use new HTML5 FileAPI to do this for you in one request. Just specify blob (responseType: 'blob') type for response, convert URL from response body, append it to href attribute of newly created anchor <a> element and click on it.
See this post for more details.
Hope that helps.
You can write the contents of the POI HSSFWorkbook to a ByteArrayOutputStream and then use the toByteArray() method of the stream in Liferay's PortletResponseUtil sendFile() method as follows:
PortletResponseUtil.sendFile(resourceRequest, resourceResponse, "FILENAME", byteStream.toByteArray(), "CONTENT_TYPE");
instead of writing directly to the resourceResponse.
However, probably for security reasons, (Javascript can not directly write files to a client) you can not do this via Ajax.
You could alternatively save the raw data that you calculate in your JS code to a hidden input and pass that to the server via a regular form submit.
I think it's just your ajax command whose don't follow requirements.
See jquery ajax documentation.
It's seems ajax jquery complains xml data download but it's not accordingly with excel data format.
Set the dataType to "text" in ajax and does the good MIME type before to send the generated file to client..it's make the excel file download to be interpreted by the browser as a real excel file.
just have the request as GET, return the bytestream of file in response and set the headers accordingly (depending on the format of you file excel/pdf) and then at client side just open the response in new tab the browser would start the file download.
Just call the following function with parameters :
url - where you want to request for file data - incase you want to
send some data pageIndex - div id where u want to append iframe
and than it will be deleted without # .
this.ajaxDownload = function(url, data,pageId) {
pageId = '#' + pageId;
if ($(pageId + ' #download_iframe').length == 0) {
$("<iframe id='download_iframe' style='display: none' src='about:blank'></iframe>").appendTo(pageId);
}
var input = "<input type='hidden' name='requestJson' value='" + JSON.stringify(data) + "'>";
var iframe_html = "<html>"+
"<head>"+
"</head>"+
"<body>"+
"<form id='downloadForm' method='POST' action='" + url +"'>" +input+ "</form>" +
"</body>"+
"</html>";
var ifrm = $(pageId + ' #download_iframe')[0].contentWindow.document;
ifrm.open();
ifrm.write(iframe_html);
ifrm.close();
$(pageId + ' #download_iframe').contents().find("#downloadForm").submit();
}

Jsoup transform my javascript string into a single line

I am having trouble with the .append function in Jsoup. I am appending my simple Javascript file response string to a Jsoup Element. But after appending my response transforms into a single line which is hurting me a lot.
My string is like this
(function () {
var count = 0;
var root = this;
var require = root.require;
//var require = cordova.require;
require.config({
config: {
text: { //this hacks the text api to allow cross domain loading of the templates. it is needed only for the packaged applications
useXhr: function (url, protocol, hostname, port) {
//console.log("text.useXhr request came from : " + url + ", " + protocol + " and " + hostname);
return true;
//return true if you want to allow this url, given that the
//text plugin thinks the request is coming from protocol, hostname, port.
}
},
'is': {
isBundled: true
}
},
waitSeconds: 45,
baseUrl: 'scripts/app',
deps: ["app"],
BUt after appending to a Element it will become
(function () { var count = 0; var root = this; var require = root.require; //var require = cordova.require; require.config({ config: { text: { //this hacks the text api to allow cross domain loading of the templates. it is needed only for the packaged applications useXhr: function (url, protocol, hostname, port) { //console.log("text.useXhr request came from : " +
My Code is for this
String temp=script.attr("src");
temp=temp.replace("/"+Heirarchy, DomainName+"/"+Heirarchy.toLowerCase());
script.attr("src", temp);
script.removeAttr("data-main");
script.removeAttr("async");
String innerHtml="</script>\n<script>\n"+old_configString;
script.append(innerHtml);
old_configString is my Javascript response String....
You should use a DataNode for adding scripts or styles.
script.after(new DataNode("<script>" + old_configString + "</script>", "http://domain.tld/path"));

How do I access POST variables in my controller?

I am making the following AJAX request:
$.post('/route', {
arg1 : 'foo',
arg2 : 'bar'
});
Through the route:
POST /route controllers.Test.readPost()
How do I access these POST variables in the method of my controller?
public static Result readPost() {
return TODO; // read post variables
}
I cannot find a simple way of doing this in the documentation. It only states how to get values from JSON requests.
Use DynamicForm
public static Result getValues(){
DynamicForm requestData = form().bindFromRequest();
String name = requestData.get("name");
String desg = requestData.get("desg");
// etc
return ok("You sent: " + name + ", " + desg);
}
There is also other possibility to construct AJAX query and pass arguments via javascriptRoutes: https://stackoverflow.com/a/11133586/1066240
Of course it will pass the params via URL so it's not suitable for every value, but in many places it will be goot enough for sending POST requests with AJAX. Of course javascriptRoutes create the request with type set in routes file.
BTW: it was better if you wrote which version you are using.
you can use GET with an ajaxRequest. more information can be found here http://www.javascriptkit.com/dhtmltutors/ajaxgetpost.shtml
var mygetrequest=new ajaxRequest()
mygetrequest.onreadystatechange=function(){
if (mygetrequest.readyState==4){
if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=mygetrequest.responseText
}
else{
alert("An error has occured making the request")
}
}
}
var namevalue=encodeURIComponent(document.getElementById("name").value)
var agevalue=encodeURIComponent(document.getElementById("age").value)
mygetrequest.open("GET", "basicform.php?name="+namevalue+"&age="+agevalue, true)
mygetrequest.send(null)

Categories

Resources