AngularJS DELETE request to my REST webservice is in plain text? - java

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)

Related

How to call and use the spring REST POST API in my angular app which is returning string without body?

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})

How to redirect to another request mapping of a spring MVC controller from a jsp within a jsp

Situation:
I have a jsp within a jsp. I load another jsp into a div of the outer jsp using .html(). I want to redirect my url into an entirely new url mapping from a controller.
Sample controller:
#RequestMapping(value = { "/main/submit" }, method = RequestMethod.POST)
public String main(ModelMap model) {
System.out.println("In controller");
return "redirect:/anotherJSP";
}
#RequestMapping(value = { "/anotherJSP" }, method = RequestMethod.POST)
public String anotherJSP(ModelMap model) {
System.out.println("In another");
return "anotherJSP";
}
Jsp within a jsp:
$.ajax({
type : "POST",
url : "/main/submit",
success : function(msg) {
console.log('redirect');
},
error : function() {
alert("Error.");
}
});
Now, the problem is that the outer jsp stays, and the /anotherJSP url only gets loaded in the innerJSP. I wanted to leave the two jsps and go to the new request mapping URL. Is there anyway I can do it? Thanks a lot in advance!
You can't redirect a POST.
When you return redirect:/anotherJSP, the server sends a redirect instruction back to the web browser, and the browser then sends a new GET request for the given URL.
The GET request will be for the URL given, with any query parameters. This means that and POST payload (data) will be lost.
Change #RequestMapping(value = { "/anotherJSP" }, method = RequestMethod.POST) to #GetMapping("/anotherJSP") (assuming Spring 4.3 or later).
Since an ajax call is asynchronous the effect of return "redirect:/anotherJSP"; is not affecting the browser window, instead you should use window.location.href in your ajax call like this:
$.ajax({
type : "POST",
url : "/main/submit",
success : function(msg) {
console.log('redirect');
window.location.href = /anotherJSP;
},
error : function() {
alert("Error.");
}
});

Can I get a POJO in an Ajax Request to a Spring Controller?

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.

POST angularjs jersey with $resource

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.

How to call #POST RESTful service from Angular JS create function using $resource

I'm trying to call REST service at Java backend from Angular-JS page. I can fetch GET data successfully but could not call #POST resource.
For example at the Java backend here is my RESTful service method -
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public User create(User user) {
User usr1 = new User();
usr1.setId(3);
usr1.setFirstName("John");
usr1.setLastName("Paul");
return usr1;
}
At the AngularJS part here is the Service factory :
var app = angular.module('app', ['ngResource']);
app.factory('UsersFactory', function ($resource) {
return $resource('http://localhost:8080/demoApp/service/users', {}, {
query: { method: 'GET', isArray: true },
create: { method: 'POST'}
})
});
Here is the AngularJS controller :
app.controller('userCreationCtrl', ['$scope', 'UsersFactory', '$location',
function ($scope, UsersFactory, $location) {
$scope.createNewUser = function () {
UsersFactory.create($scope.user);
}
}]);
The error is showing in Javascript Console of the Chrome Browser -
XMLHttpRequest cannot load http://localhost:8080/demoApp/service/users. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
Your problem is because in the service rest you can allow to make CORS so you have to change or add some configuration in server side change that, or the more simple way is to put the html code in the same url that is your server, localhost:8080 (you have your html code in localhost:63342)
In your server side you have to add the "Access-Control-Allow-Origin=*" or something like that

Categories

Resources