I'm trying to send data to controller by ajax,but met with problem Failed to load resource: the server responded with a status of 400 (Bad Request).I don't know which part of the problem
JS:
var info ={
"questions":{"q1":trim(q1), "q2":trim(q2),"q3":trim(q3),"q4":trim(q4),"q5":trim(q5),"q6":trim(q6),"q7":trim(q7),"q8":trim(q8)},
"answers":{"datetimepicker":datetimepicker,"sexual":sexual,"nation":nation, "province":province,"city":city, "sheng":sheng,"shi":shi,"xian":xian, "height":height,"weight":weight}
};
var info_str = JSON.stringify(info);
$.ajax({
type:'GET',
data:info_str,
contentType: "application/json; charset=utf-8",
dataType: "json",
url :'/yiban',
success :function(data) {
alert(data);
},
error :function(e) {
alert("error");
}
});
Java:
#RequestMapping(value = "/yiban", method = RequestMethod.GET)
public void yiban(HttpServletRequest request)
{
String jsonStr = request.getParameter("info_str");
JSONObject questions = JSONObject.fromObject(jsonStr).getJSONObject("questions");
JSONObject answers = JSONObject.fromObject(jsonStr).getJSONObject("answers");
String q1 = questions.getString("q1");
String ans = answers.getString("nation");
System.out.println(q1);
}
#RequestMapping(value = "/yiban", method = RequestMethod.POST)
public void yiban(HttpServletRequest request) throws IOException {
//GET method parameter is passed with url , json data can't go with url. json or xml is passed in request boy
// String jsonStr = request.getParameter("info_str");
ServletInputStream inputStream = request.getInputStream();
String jsonStr=StreamUtils.copyToString(inputStream, Charset.forName("UTF-8"));
JSONObject questions = JSONObject.fromObject(jsonStr).getJSONObject("questions");
JSONObject answers = JSONObject.fromObject(jsonStr).getJSONObject("answers");
String q1 = questions.getString("q1");
String ans = answers.getString("nation");
System.out.println(q1);
}
Above is my code which works in my project .
Firstly ,use POST to send json or xml!
and use request.getInputStream to receive json data!
Secondly you RequestMappingMethod returns nothing, your front web receive nothing !
What view you want to return to Front?
Related
I am working on Spring Boot application where I need to provide download zipped report files feature. In order to do that I am converting zipped report files to byte array and then trying to send it at the browser side. I am able to download the zipped report file but when I try to extract it gives an error message that 'The Compressed zipped folder is invalid.' Please find the code snippet below:
Server Side Code:
#ResponseBody
#RequestMapping(value = "/downloadResult", method = RequestMethod.POST, produces="application/zip" )
public byte[] downloadResult(#RequestBody ResultParamsVO resultParamsVO, HttpServletRequest request,
HttpServletResponse response) {
byte[] result = null;
try {
HttpSession session = request.getSession(false);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String user = auth.getPrincipal().toString();
String testType = null;
if (session.getAttribute("testType") != null) {
testType = session.getAttribute("testType").toString();
}
result = jobService.downloadResult(resultParamsVO, testType, user);
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=resultDownload1.zip");
} catch (Exception e) {
logger.error("Error in getResult() for job id - " + resultParamsVO.getJobId(), e.getMessage());
e.printStackTrace();
}
return result;
}
Browser Side Ajax Call:
$.ajax({
type: "POST",
url: "/downloadResult",
contentType: "application/json",
data: JSON.stringify(resultParamsVO),
success: function(result) {
var downloadUrl = window.URL.createObjectURL(new Blob([result], {type: "application/zip"}));
var a = document.createElement("a");
a.href = downloadUrl;
a.download = "resultDownload.zip";
document.body.appendChild(a);
a.click();
}
});
Please help. Thanks in advance.
Im making an AJAX POST request to a spring controller and getting returned an byte array as the response. I want to make it downloadable. What is the best approach to take?
Heres my implementation :
var params = [[${params}]];
$("#download-button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
contentType: "application/json",
url: "/patient-listing/excel",
data: JSON.stringify(params),
success: function(result) {
var byteArray = result;
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], { type:'application/octet-stream' }));
a.download = "file.XLSX";
document.body.appendChild(a)
a.click();
document.body.removeChild(a)
},
error: function(result) {
console.log('error');
}
});
});
In here even though the file is downloaded there is no data.
Controller :
#PostMapping(value = "/patient-listing/excel", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity getEmployeeReportXlsx(#RequestBody Param param) {
logger.info("Generating Excel report of param : " + param);
final byte[] data = poiService.getExcelFile(param);
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
header.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=case-data-report.xlsx");
header.setContentLength(data.length);
return new ResponseEntity<>(data, header, HttpStatus.OK);
}
You can simply download excel without AJAX request,
Change POST method to GET method using #GetMapping
#GetMapping(value = "/patient-listing/excel", consumes = MediaType.APPLICATION_JSON_VALUE)
in thymeleaf ,
<a class="sidebar-element" th:href="#{/patient-listing/excel}">
Generate Excel
</a>
I am not able to parse a list of objects in AJAX, Whenever I try to parse the list, ERROR code 406 pops. But if I try to send a string it receives fine.
Controller Code
#RequestMapping(value = "getstates", method= RequestMethod.POST, produces="application/json")
#ResponseBody
public List<State> liststates(HttpServletRequest request){
String country = request.getParameter("country");
List<State> states = adminService.getAllstates(Integer.parseInt(country));
System.out.println("The states we recieved is" +states);
String result ="hello Bhaskar "+ country;
return states;
}
JSP AJAX Code
var id = $('#select_country').val();
$.ajax({
url : "getstates",
data: {country : id},
dataType: 'application/json',
type: 'POST',
success : function(response) {
alert("Access Success "+ response);
$('#select_country').append("<option value='-1'>Select User</option>");
for ( var i = 0, len = response.length; i < len; ++i) {
var user = response[i];
$('#select_country').append("<option value=\"" + user.id + "\">" + user.state+ "</option>");
}
},
error : function(response) {
alert("Access Fail "+ response);
}
* Browser Output* Access Failed [object Object]
Open Output Image
* Console Output*
The states we received is [in.complit.model.State#7dee7dc6, in.complit.model.State#54263ffc, in.complit.model.State#43e78960, in.complit.model.State#4ce669b5]
The Problem Solved by adding a try-catch block while calling the service class method in the Controller Class. The code after adding it is as shown below.
#RequestMapping(value = "getstates", method= RequestMethod.POST, produces="application/json")
#ResponseBody
public List<State> liststates(HttpServletRequest request){
//List<Country> listCountries = adminService.getAllcountries();
String country = request.getParameter("country");
List<State> states = new ArrayList<State>();
try {
states = adminService.getAllstates(Integer.parseInt(country));
}catch(Exception e) {
System.out.println(e);
}
System.out.println("The Country We Recieved "+ country);
System.out.println("The states we recieved is" +states);
return states;
}
I'm trying to upload an image from my Flutter application using the following code:
Future<String> saveImage(File image) async {
var stream = new http.ByteStream(DelegatingStream.typed(image.openRead()));
var length = await image.length();
String token = "blah"; //token for authentication
var uri = Uri.parse(url); //I get the URL from some config
Map<String, String> headers = { "Authorization": "Bearer $token", "content-type": "multipart/form-data" };
var request = new http.MultipartRequest("POST", uri);
request.headers.addAll(headers);
var multipartFile = new http.MultipartFile('file', stream, length);
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
But this request fails on my spring-boot server with the following error:
{"timestamp":1562637369179,"status":400,"error":"Bad Request","exception":"org.springframework.web.multipart.support.MissingServletRequestPartException","message":"Required request part 'file' is not present","path":"/api/v1/user/photo"}
This is what my Java controller method looks like:
#RequestMapping(value = "/photo", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> uploadImage(#RequestPart(required = true) #RequestParam("file") MultipartFile image) throws IOException {
}
I would like to mention that the method works if I use postman to upload an image. There seems to be something wrong with my flutter code.
Thanks for any help.
Figured it out. Instead of using the new http.MultipartFile() constructor I used this static method:
request.files.add(await http.MultipartFile.fromPath('file', image.path,
contentType: new MediaType('image', imageType)));
Can anyone tell what am I doing wrong here???
In bankbonejs, I am trying to make a POST request. Here is my code: Im using tomcat server.
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
saveDetails: function (ev) {
var abcDetails= $(ev.currentTarget).serializeObject();
var abc= new ABC();
bank.save(abcDetails, {
success: function (abc) {
router.navigate('', {trigger:true});
}
});
return false;
}
Call goes to the server side (Tomcat) but the post request params are coming as null. I have checked var abcDetails just before requesting the save has the values populated correctly. Also, checked by sending post request thru PostMaster to make sure that values are passed from the client side correctly. However, on the server side these posted request params are null. I am some how stuck here.vAppreciate help in this regard.
Server Side
.
#RequestMapping(value = { "/postedValues" }, method = RequestMethod.POST)
public String getpostedValues( HttpServletResponse response, HttpServletRequest request) throws Exception {
JSONArray jsonarray = new JSONArray();
JSONObject jsonobj = new JSONObject();
String _id = StringEscapeUtils.escapeHtml4(request.getParameter("id"));
String col1= StringEscapeUtils.escapeHtml4(request.getParameter("col1"));
String col2= StringEscapeUtils.escapeHtml4(request.getParameter("col2"));
Also,
Enumeration paramaterNames = request.getParameterNames();
while(paramaterNames.hasMoreElements() ) {
System.out.println(paramaterNames.nextElement());
}--> observation:does not go inside the while loop