I'm trying to do post a string (later it will probably be an array or map) to my Jersey application but I can't get it to work.
jersey method :
#GET
#javax.ws.rs.Path("/angu/{param}")
#Consumes(MediaType.APPLICATION_JSON)
public void testAngu(#PathParam("param") String param){
}
Angular service:
services.factory('testFactory', function ($resource) {
return $resource('/app/api/folders/angu/:param', {}, {
save: {
method: 'POST',
params: {param : '#param'}
}
})
});
Angular controller :
app.controller('scanController', ['$scope', 'firstScanFactory', 'testFactory', function ($scope, firstScanFactory, testFactory) {
firstScanFactory.get({}, function (firstScanFactory) {
$scope.shows = firstScanFactory.listShows;
})
$scope.callJersey = function() {
testFactory.save("toto");
}
}]);
And finally the button for the call :
<a class="ls-sc-button default" ng-click="callJersey()">Valider</a>
What am I doing wrong ?
Your Jersey-method is annotated with #GET, however your Angular code uses method: 'POST'.
Because of that, Jersey will never select testAngu() as the matching route.
If you use the #, you need to pass the parameter as a property of an object. The #param string will tell the resource to replace :param with the property param on the object you pass it as parameters:
testFactory.save({"param": "toto"});
The API documentation says:
If the parameter value is prefixed with # then the value for that parameter will be extracted from the corresponding property on the data object (provided when calling an action method). For example, if the defaultParam object is {someParam: '#someProp'} then the value of someParam will be data.someProp.
Related
I am trying to access the POST API from my spring app to angular but little bit confused how to use and access the given API in my angular app.
Spring REST API
#RequestMapping(value = "/getWelcomeMessage", method = RequestMethod.POST)
public String getLoginWelcomeMessage() {
return details.getLoginWelcomeMessage();
}
The given API is fetching the welcome message details from my oracle DB and returning a string value. I am trying to access the given REST API in my angular code through services. I had define the post service as follows
export class LoginService {
constructor(private http : HttpClient) { }
welcomeMessageService(){
const headers = {'content-type':'application/text'}
return this.http.put("http://localhost:8080/API/getWelcomeMessage",null,
{'headers':headers});
}
}
As the post method requires three arguments URL, Body and header. But in my case my spring REST API doesn't contain any body and returning a string. So, I had define the body as null and change the header type to text as it is JASON by default.
At last, I am trying to access the given service method by injecting it in my component as follows-
export class LoginComponent implements OnInit {
message:string;
constructor(private loginService : LoginService) { }
ngOnInit(): void {
this.loginService.welcomeMessageService().subscribe(
response =>{
console.log(response);
this.message = response;
}
)
}
}
But when I am trying to assign the response to the string I am getting the error that string cannot be assigned to the object. I am little bit confused why this error is occurring as I had also changed the header type to string while defining my service but still getting the error.
It can be a great help if anybody guide me regarding this as I am new to angular and little bit confused with integration part of API with angular.
Use { responseType: 'text' } and also send an empty body not null
export class LoginService {
constructor(private http : HttpClient) { }
welcomeMessageService(){
return this.http.put("http://localhost:8080/API/getWelcomeMessage",{},
{ responseType: 'text' });
}
}
Maybe you have copied the function wrong but check also here
#RequestMapping(value = "/getWelcomeMessage", method = RequestMethod.POST)
public String getLoginWelcomeMessage() {
return details.getLoginWelcomeMessage();
}
This is a Post method not a put that you are trying to call
As for cors error add the following to the backend just above #Controller or #RestControler whatever you have
#CrossOrigin(value = {"http://localhost:4200"}, methods = {GET,POST,PUT,DELETE})
I have a simple JSP file with some radios, one text input and one button.
In the button onClick I am doing an Ajax request to a Spring controller as you can see bellow:
function callFiltrarViaAJAX() {
var filtro = $("#filtro").val();
var optFiltro = $('input[name=optFiltro]:checked').val();
$.ajax({
type : "GET",
url : "filtrar",
//dataType : "json",
data : {
filtro : filtro,
optFiltro : optFiltro
},
success: function(data) {
console.log("SUCCESS: ", data);
},
error: function(e) {
console.log("ERROR: ", e);
},
done: function(e) {
console.log("DONE");
}
});
}
In the Spring controller I am receiving this request with success with the following code:
#Controller
public class FiltroController {
#RequestMapping(value = "/filtrar", method = RequestMethod.GET)
public #ResponseBody String filtrarVacina(FiltroTO filtro, HttpServletResponse response, ModelAndView model) {
VacinaTO v = new VacinaTO();
v.setId(new Long(10));
v.setLote("Lote 1");
v.setNome("BCG");
model.addObject("vacina", v);
response.setStatus(200);
return "TEST OK";
}
}
As you can see in the code above, I'm adding a POJO object in the ModelAndView that I'am trying to use in the JSP to show the return of the Ajax request in a table.
My Ajax request returns with success too but the problem is that even returning with success I can't use the POJO object, when I try to access the object by expression language I got nothing.
I've been searching about this situation and I found a lot of contents but none of the solutions that I've found works for me, but I found an interesting answer:
JSP inside ListItems onclick
So, is it means that I can't get a new parameter in the same JSP file with a Ajax request ? If yes, would be a JSON file the better way to get the return from the Spring controller ?
You can't access the model because you're returning an arbitrary string from controller instead of the view in which you want to access model.
If you're trying to access vacine from some.jsp, then you should return some from the controller method.
Of course, what I said is valid if you have proper ViewResolver configuration.
I am trying to POST to a Spring MVC controller method via ajax. Using Chrome's developer tools, I can tell that the values from the form are being sent, but in the method, the form values are null.
Here is the jquery call:
var form = $('#renegotiationForm').serialize();
$.ajax({
method:'POST',
url:'/renegotiate/wizard/startRenegotiation',
data:{'renegotiationForm': form},
success: function(data) { this.transitionTo(data); }
});
Here is the Spring MVC method (meant to return only a single string):
#RequestMapping(value="wizard/startRenegotiation", method = RequestMethod.POST)
public #ResponseBody String processStart(#ModelAttribute("renegotiationForm") RenegotiationForm form, BindingResult bindingResult) {
log.debug("Entered showStart(), method=POST");
RenegotiationType type = RenegotiationType.valueOf(form.getRenoType().trim().toUpperCase());
RenegotiationActivity activity = RenegotiationActivity.valueOf(form.getRenoActivity().trim().toUpperCase());
String result = "";
if (type == RenegotiationType.TYPE1 && activity == RenegotiationActivity.ACTIVITY1) {
result = "deleteType1";
}
return result;
}
The values are bound using the Spring Form taglib, and I have confirmed that the path attributes of the form tags match the fields of the RenegotiationForm.
I think it's because you are trying to send an "string" from ajax and you want to get and Object (RenegotiationForm), try to change it to String and Format in Server-side. I recommend you to add the type you are sending from client-side, too.
#RequestMapping(value = "wizard/startRenegotiation", method = RequestMethod.POST, produces="application/json")
Found the answer. Further on in my code, I had a function like this:
var ajaxcall = function() { $.ajax({
// ajax settings
});
}
Unfortunately, setting it up this way doesn't make it work as a jquery deferred, and specifically I couldn't use the .then() function to process of ajax requests.
Thanks for the help.
So I am trying to wire up an AngularJS front-end to a Java Spring back-end using a REST service.
My DELETE requests keep getting the following error (notice the speaker?id=) - Why is it generating speaker?id= instead of speaker/ ?
DELETE http://localhost:8082/rest/speaker?id=54200b6b772f1e7b0688307b 405 (Method Not Allowed)
The code is as follows:
Java:
#RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
public void delete(#PathVariable String id) {
speakerService.delete(id);
}
Angular JS service
this.delete = function (id, callback) {
SpeakerResource.delete({ id: id }, function () {
callback();
});
}
Angular JS factory
app.factory('SpeakerResource', function ($resource) {
return $resource('rest/speaker/:speakerId',
{
speakerId: '#speakerId'
},
{
'update': { method: 'PUT' }
},
{
'delete': { method: 'DELETE', params: {id: '#speakerId' } }
}
If I use the $http statement then everything works correctly, but obviously I'd like to stick to using the factory as the PUT/POST methods are working fine!
$http.delete('http://localhost:8080/rest/speaker/' + data.id);
Cheers,
I think you should remove the params object on the delete action or rename the parameter to speakerId, because otherwise AngularJS cant set the url parameter in the resource (your url placeholder is speakerId, but your property is named id)
I'm trying to make a simple AJAX call in my Spring MVC project but am running into trouble. I am making my AJAX request by sending an String type argument and I'm wanting to get an ArrayList type back. I've read many tutorials at this point and can't figure out what's wrong with my AJAX/Controller configuration. I am using the ResponseBody annotation when trying to return my needed result back to the view. In this controller I am not returning an updated ModeAndView object, but this shouldn't matter since the page does not need to be refreshed because I'm using AJAX. Below is my AJAX call and controller code. I would really appreciate it if someone could give me a hint on what I'm doing wrong here.
function getdays() {
var monthSelected = $("#monthselect option:selected").text();
alert(monthSelected);
$.ajax({
url : '${pageContext.request.contextPath}/ajaxdays',
data: monthSelected,
success : function(data)
{
$('#daySelect').html(data);
alert(data);
}
});
}
Here is my controller class:
#Controller
#SessionAttributes
public class WorkstationController
{
#RequestMapping(value = "/ajaxdays", method = RequestMethod.GET)
public #ResponseBody
ArrayList<String> getTime(HttpServletRequest request)
{
ArrayList<String> retList = new ArrayList<>();
retList = this.getList();
return retList;
}
}
you have following errors
wrong url
change url : 'ajaxdays.html'to ${pageContext.request.contextPath}/ajaxdays
no parameter passed
you are not passing any data to server side so there is no need to write data: monthSelected
URL mentioned in ajax call should be the context path followed by the controller mapping. And '.html' should not be specified.
url: ${pageContext.request.contextPath}/ajaxdays