Post API doesn't give any react - java

I am developing an application with using JHipster(Java,Spring Boot,Angular).
I have course and student entities. Students should register courses with clicking register button after they logged in.
I wrote post api and tested it from swagger. IT WORKS FINE.
But when i try to link it to a button with angular1; it gives any react.
My Post API(I test it from swagger it works fine)
#PostMapping("/registercourse/{studentId}/{courseId}")
#Timed
public ResponseEntity<Void> registerCourse(#PathVariable Long studentId,#PathVariable Long courseId) {
log.debug("REST request to register {} Course : {} Student : {}", courseId,studentId);
courseRepository.registerCourse(studentId,courseId);
return ResponseEntity.ok().headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, courseId.toString())).build();
}
course.register.states.js
(function() {
'use strict';
angular
.module('mucsApp')
.config(stateConfig);
stateConfig.$inject = ['$stateProvider'];
function stateConfig($stateProvider) {
$stateProvider
.state('course.register', {
parent: 'entity',
url: '/registercourse/:studentid/:courseid',
data: {
authorities: ['ROLE_USER']
},
controller: function($scope, $stateParams) {
$scope.studentid = $stateParams.studentid;
$scope.courseid = $stateParams.courseid;
$http({
method: 'POST',
url: 'http://localhost:8080/' + $scope.studentid + '/' + $scope.courseid,
headers: {
'Content-Type': 'application/json'
}
}).then(function successCallback(response) {
console.log("GREAT");
}, function errorCallback(response) {
console.log(response)
});
}
});
}})();
course.register.service.js
(function() {
'use strict';
angular
.module('mucsApp')
.factory('CourseRegister', CourseRegister);
CourseRegister.$inject = ['$resource'];
function CourseRegister ($resource) {
var resourceUrl = 'api/registercourse/:studentid/:courseid';
return $resource(resourceUrl, {}, {
'query': { method: 'POST', isArray: true},
'save': {
method: 'POST',
transformRequest: function (data) {
var copy = angular.copy(data);
return angular.toJson(copy);
}
}
});
}})();
My html button:
<button type="submit"
ui-sref="course.register({studentid:vm.mystudentid , courseid:course.id})"
class="btn btn-info btn-sm">
<span class="glyphicon glyphicon-eye-open"></span>
<span class="hidden-sm-down">Kaydol</span>
</button>

Your Spring controller is looking for this:
#PostMapping("/registercourse/{studentId}/{courseId}")
Your $http call is posting to this:
url: 'http://localhost:8080/' + $scope.studentid + '/' + $scope.courseid
You need to change your call to:
url: 'http://localhost:8080/registercourse' + $scope.studentid + '/' + $scope.courseid
Also, your Controller is not actually using your CourseRegister. you need to inject that in your AngularJS controller if you want to use it.: controller: function($scope, $stateParams,CourseRegister).
My two cents is that in your case, you are better of just using $http. I would put the [updated] $http call into your CourseRegister service, and use that. $resource would require more modifications than I think is worth it.
More on $resource is here.

Related

controller get html date by ajax

in my html I need to enter a date value, afterthat, I am going to send the date through ajax to my MVC controller which connected with the database to get the record by date. However, I don't know how to send the date to my controller
Ajax in getData():
$.ajax({
url: 'send'
type: 'GET',
data: {date= $('#date').val,}
contentType: "application/json; charset=utf-8",
success: function(resp) {
//do something
},
error: function(err) {
//error
}
});
get the date from user:
<input type="date" id="date" placeholder="date" onkeyup="getData()">
Controller:
#RequestMapping(value = "/send", method = RequestMethod.GET)
#ResponseBody
public List<Object> send(
#RequestParam(value = "date", required = false) Date date) throws Exception {
// do something
}
Right, I see lot's of issues here.
$.ajax({
url: '//controller action url', // Missed the comma here
type: 'POST', // Changed to post
data: {"date": $('#date').val}, // Your syntax was wrong here
contentType: "application/json", // Simplified this. Not need but I just prefer it this way.
success: function(resp) {
//do something
},
error: function(err) {
//error
}
});
Assuming that the controller action is something like:
public ActionResult Send(DateTime date){
}

Angularjs pass null value in file multipart FormData to Spring MVC

I am attempting to send form data with Multipart data (Image) to Spring MVC controller. From my form. image field is non mandatory. so when i call spring controller without input image field, i get below error in browser console.
Failed to load resource: the server responded with a status of 400
(Bad Request)
Html Code:
<input file="file" type="file" id ="file2"/>
AngularjS Code:
$scope.saveData = function (formObj) {
$http({
url: CONTEXT_PATH+'saveFile',
method: "POST",
headers: { 'Content-Type': undefined },
transformRequest: function (data) {
alert(data.files);
var formData = new FormData();
formData.append("model", angular.toJson(data.model));
formData.append("file", data.files);
return formData;
},
data: { model: formObj, files: $scope.file }
}).then(function (response) {
//alert(response);
});
};
app.directive('file', function () {
return {
scope: {
file: '='
},
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var file = event.target.files[0];
scope.file = file ? file : undefined;
scope.$apply();
});
}
};
});
Spring Controller Code:
#RequestMapping(value = "/saveFile")
public #ResponseBody String storeAd(#RequestParam ("model") String adString, #RequestParam ("file") MultipartFile file) throws IOException {
System.out.println("adString > "+adString);
return "OK";
}
When the image is not uploaded, the request is bad because Spring MVC assumes all parameters required unless otherwise defined.
In your case, you should add required = false.
#RequestParam(value = "file", required = false)
Your server code is expecting a request parameter with name "file" but you are not defining it properly.
Change
<input file="file"
To
<input type="file" name="file"

Spring Ajax JQuery Jackson

Whats wrong in my approach.
Java Mapping :
#POST
#Path("/receive")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public void consumeJSONList(#RequestBody List<Question> clientList) {
String output = "consumeJSONList Client : " + clientList.toString() + "\n\n";
System.out.println(output);
}`
Ajax Call :
function addData(x) {
var x='[{"id":12,"email": "2","lang": "es"}]';
$.ajax({
type: 'POST',
url: "rest/question/receive",
header : {
"Content-Type":"application/json"
},
data: x,
success: function(data, textStatus, jqXHR){
alert('Wine created successfully');
},
error: function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
alert(jqXHR+'addWine error: ' + textStatus+"errorThrown"+errorThrown);
}
});
}
i am able hit the same url with same data in google post man but when use ajax call its throwing 415(Unsupported media type)
Please help to create a controller which can accept list of java object and process the same
As the jQuery docs say, you should give the following a try:
Replace…
header : {
"Content-Type":"application/json"
},
…with…
dataType: 'json',
…and make sure that the server's context path in front of "/receive" is really "rest/question". Depending on the situation also a leading slash "/rest/question/receive" could be worth a try.

Java Rest call with jquery and ajax

I am making a ajax Rest call within jquery and it is supposed to return me a list of beans, which I want to show in the jsp. I am able to make the Rest call but I can't get how to get the result in the ajax call and show it in page.
jsp page with the ajax call
<script type="text/javascript">
$(document).ready(function(){
$('#abcForm').submit(function(){
var v = $('#abc').val();
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://localhost:8080/RestTest/rest/hello/"+v,
});
});
});
</script>
java code
#Path("hello")
public class RestController {
#GET
#Path("{param}")
public Response getMsg(#PathParam("param") String msg) {
String output = "Hello : " + msg;
return Response.status(200).entity(output).build();
}
}
So actually there will be a rest call from the java class and it will return a list which needs to be shown in the jsp page as ajax call. This is where I am stuck.
Help needed.
Thanks
You have a success callback that will be called when the request finishes as successful and will receive the response as the first parameter:
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://localhost:8080/RestTest/rest/hello/"+v,
success: function(data) {
//do something with data.
}
});

JQuery, AJAX, POST request, parameters lost

My web application is basen on Spring MVC (4.0.5).
I'm trying to send a POST request through AJAX, using jQuery (v. 2.1.1):
function deleteItem(id) {
alert("Deleting " + id);
$.ajax({
url: "ajax/delete_item",
type: 'POST',
dataType: 'html',
data: {"id": id},
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
var txt = data;
$('#message').html(txt);
},
error: function(data, status, err) {
$('#message').html(err);
}
});
}
The Controller's method is called successfully but there are no parameters in the request:
#RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST)
public #ResponseBody String ajaxDelete(HttpServletRequest request) {
Enumeration<String> en = request.getParameterNames();
while (en.hasMoreElements()) {
String pname = en.nextElement();
System.out.println("//// " + pname); // just for test
}
String idStr = request.getParameter("id");
Integer id = Integer.parseInt(idStr);
//...
Why the request parameter is lost? Not just the value, the parameter itself is also lost.
What's wrong here?
If you are passing content type contentType: 'application/json' from ajax then add that settings in Spring method declaration as below: ( add produces = "application/json" in definition)
#RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST , produces = "application/json")
public #ResponseBody String ajaxDelete(HttpServletRequest request) {
also there's one more caveat that,
You are mentioning both datatype and mimeType but it is not uniform.
mimeType: 'application/json' should be written with dataType: 'json' and not html.
I am not 100% sure what is wrong with your solution but I can give you an example that works for me
The AJAX request using Jquery :
// Do AJAX
$(function () {
$.post(mobileUrl + "/leave/requestLeave",
{ startDate: startDate, endDate: endDate, leaveTypeId: leaveTypeId,
notes: notes, isStartDayHalfDay: isStartDayHalfDay, isHalfDayEndDay: isHalfDayEndDay },
function (response) {
$('#feedbackTextArea').show();
}
);
});
And the controller method
#RequestMapping(value = "/requestLeave", method = RequestMethod.POST)
#ResponseBody
public String createOrUpdateNewForm(String startDate, String endDate, String leaveTypeText, String leaveTypeId,
String notes, String isStartDayHalfDay, String isHalfDayEndDay) {
startDate = new DateTime(startDate).toDate() etc
}
}
One thing to remember is that the parameter names in the ajax request should match the names of the variables in the controller method implementation
$("#drpop").change(function () {
var code = $(this).val();
$.ajax({
url: '/Ordering/OrderingTable',
type: 'post',
datatype: 'json',
data: { OperCode: code },
success:function(msg){
alert(msg);
} }); });
[HttpPost]
public ActionResult OrderingTable(string OperCode)
{
Orderingbll order = new Orderingbll();
var result = order.ListCategory(OperCode);//here you write your code
return Json(result,JsonRequestBehavior.AllowGet);
}

Categories