How to get angularjs parameters in java backend? - java

I have an angular app with these routes:
$routeProvider
// Home screen
.when('/', {
title : 'APP.NAME',
bodyClassName : 'home',
templateUrl : 'app/custom/templates/customTemplate.html',
controller : 'customTemplateController',
resolve : { unauthorizeRequest: unauthorizeRequest }
})
.when('/connect/:connectionToken', {
bodyClassName : 'client',
templateUrl : 'app/client/templates/client.html',
controller : 'clientController',
resolve : { updateToken: updateToken}
})
.otherwise({
resolve : { unauthorizeRequest: unauthorizeRequest }
});
and on the java side:
#POST
public APIAuthenticationResult createToken(
#FormParam("connectionToken") String token,
#Context HttpServletRequest consumedRequest,
MultivaluedMap<String, String> parameters)
HttpServletRequest request = new APIRequest(consumedRequest, parameters);
String token = request.getParameter("connectionToken");
The problem is that if I use a url like:
http://localhost:8090/connect/{connectionToken here}
I always get null on the Java side. And if I use a url like:
http://localhost:8090/connect/?connectionToken={connectionToken here}
angular doesn't hit the correct route, it goes to the otherwise route, but on the Java side I can get the token via request.getParameter.
How can I deal with this?

Try to define your controller method like this:
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/connect/{connectionToken}")
public Response doStuff(#PathParam("connectionToken") String token){
System.out.println(token);
//stuff..
}
or, if you're using Spring:
#RequestMapping(value="/connect/{connectionToken}", method = RequestMethod.GET, produces="application/json")
public Response getOrderEquipment(#PathVariable("connectionToken") String token){
System.out.println(token);
//stuff..
}

Related

Spring boot rest endpoint returning null with fetch request

I have already created Rest Endpoint in Java spring boot. It returns appropriate response when I request it via Postman. But when I use react fetch it does not show any response in browser if return is Json.
Spring boot controller:
#RestController
#RequestMapping(path = "/v1/test")
#AllArgsConstructor(onConstructor_ = {#Autowired})
public class TestController {
...
}
Below endpoint is returning appropriate response.
#GetMapping(value = "/helloWorld", produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
public String getHelloWorld() {
return "Hello, World1!";
}
But when I try to hit below endpoint it returns null when I make fetch request. But it returns appropriate response when I hit it via postman.
#GetMapping(value = "/testEndpoint", produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
public String returnTestResponse() {
HashMap<String, Object> map = new HashMap<>();
map.put("key1", "value1");
map.put("results", "value2");
return "{\"a\":1, \"b\":\"foo\"}";
}
Also tried returning POJO object. But still no response.
#GetMapping(value = "/testModel", produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
public SearchResultsModel testModel() {
this.myService.getSearchResult();
}
React fetch call:
await fetch(ALL_ARTICLES_ENDPOINT, {
mode: 'no-cors',
method: 'GET',
redirect: 'follow',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
}).then(response => {
console.log(response);
})
.then(data => {
console.log('Success:', data);
}).catch((error) => {
console.error('Error:', error);
});
Postman have couple hidden headers which are being sent with all requests.
Check Hide auto-generated headers
What you are missing in react call is is Accept header with application/json value
EDIT:
Just saw that you are returning string as json. You need to wrap it in POJO object and return it in returnTestResponse class
SECOND EDIT:
This will work. Try to implement your POJO
#GetMapping(value = "/testEndpoint", produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
public YourObject returnTestResponse() {
HashMap<String, Object> map = new HashMap<>();
map.put("key1", "value1");
map.put("results", "value2");
return new YourObject(map);
}
Issue was caused by adding mode: 'no-cors' option in fetch request. This option helped me to get rid of cors error but it means that in return I won't be able to see body and headers in chrome.
To resolve the issue I removed mode: 'no-cors' and added #CrossOrigin annotation on my spring boot controller.

How to do a request using AuthHttp JWT Token in Angular 4 to a Spring Boot API mapped with #RequestPart?

I hava a Rest API developmented in Java using Spring boot. And it provides a resource mapped with #RequestPart that I receive an File and another content to pass to a service. Until now, all right. I can test in Postman no problems.
#RestController
#RequestMapping("/content")
public class ContentResource {
private ContentService conteudoService;
#Autowired
public ContentResource(ContentService contentService) {
this.contentService= contentService;
}
#PostMapping
public ResponseEntity<Content> publicaContent(#RequestPart("file") MultipartFile file, #RequestPart String content ) throws JsonParseException, JsonMappingException, IOException {
Content convertedContent = new ObjectMapper().readValue(content , Content.class);
Content storagedContent = contentService.uploadContent(convertedContent, file);
return ResponseEntity.ok(storagedContent );
}
So, I need to do a request from my Angular 4 application, using AuthHttp of the JWT. How I could do it ?
Follows an example of other service I've implemented using JWT.
#Injectable()
export class StudentService {
url = 'localhost:8080/api/student';
constructor(
private http: AuthHttp
) { }
save(student: Student): Promise<any> {
return this.http.post(this.url, student)
.toPromise()
.then(response => response.json());
}
}

How to pass large number of parameters from Angular js to rest service

I am trying to fetch parameters from angular JS $http service to rest service using **#queryParam** . I need to fetch lot of parameters(below have shown for 3 as an example ,but I need to use around 12-15 of them which I need to pass to the java side) ,so fetching all with #QueryParam makes the code look pretty bad .I am using GET.
How can I optimize this ?
Example what I am doing -
Angular Js code -
$http({
url: someUrl,
method: "GET",
params: {filter1: $scope.filter1,
filter2:$scope.filter2,
filter3:$scope.filter3
});
Java side -
#path("/getAllData")
#GET
#Produces({..}
public response getAllData(#QueryParam("filter1") final String filter1,
#QueryParam("filter2") final String filter2,
#QueryParam("filter3") final String filter3){
}
Also ,wanted to know the optimization in case when I am building URL instead of params object, and picking the same with #PathParam
$http.get('rest/test/getAllData/?filter1='$scope.filter1 +
'&filter2='$scope.filter2 + '&filter3='$scope.filter3 +
'&filter4='$scope.filter4)
I am able to do it by passing individually in #QueryParam . I am looking for optimized code when we a large number of parameters.
Create a POJO with all the required parameters.
In angular, do this
var obj = {};
obj.filter1 = $scope.filter1;
obj.filter2 = $scope.filter2;
obj.filter3 = $scope.filter3;
$http({
url: someUrl,
method: "GET",
params: obj
});
You can accept all the parameters in you rest like this -
#path("/getAllData")
#GET
#Produces({..}
public response getAllData(MyPojo obj){
//String filter1 = obj.filter1;
}
You can do it in 2 ways:
1) org.json.simple.JSONObject.
2) Bean or POJO Class.
AngularJS Controller:
var URL = appURL+'/adm/addCollProcess.do';
var json = {"col_pro_id":$scope.col_pro_id, "col_code": $scope.col_code, "exam_type_ids": $scope.exam_types.toString().replace("[","").replace("]",""),
"created_by" : "admin", "file_path" : $scope.file_path, "website" : $scope.website, "facebook" : $scope.facebook};
// using JSONObject
$http.post(URL, json).then(function(response){
if(response.data){
// Code
}
});
// using Bean Class
$http.post(URL, JSON.stringify(json)).then(function(response){
if(response.data){
// Code
}
});
Java Controller:
// using JSONObject
#RequestMapping(value="/addCollProcess.do", method=RequestMethod.POST)
public boolean addCollProcess(#RequestBody JSONObject json){
// Code
}
// using Bean Class:
#RequestMapping(value="/addCollProcess.do", method=RequestMethod.POST)
public #ResponseBody boolean addCollProcess(#RequestBody AdmissionProcessBean processBean) {
// Code
}

AngularJS consumes JAX-RS rest web service

This is the first time that I am using a Java back-end for my web application. I have a Jax-rs webservice that I am trying to consumes with my AngularJS app
AngularJS call
$http({
url : REST_END_POINT + '/checkuser',
method : "GET",
data : {
'userId' : credentials.username,
'pwd' : credentials.password
},
dataType : "json",
headers : {
"Content-Type" : "application/json"
}
});
Webservice
#GET
#Produces("application/json")
#Consumes("application/json")
#Path("checkuser/")
public string getCheckUser(#QueryParam("userId") String userId, #QueryParam("pwd") String pwd){
try{
if(port != null){
boolean result = port.checkUser(userId, pwd);
return new java.lang.Boolean(result).toString();
}
}catch(Exception ex){
//TODO
}
return null;
}
Both userId and pwd are always null
With Firebug I can see that data contains
Object{
userId="aaa",
pwd="aa"
}
I also tried with JSON.stringify which send those data :
"{"userId":"aaa","pwd":"aa"}"
I believe that the way you are trying to access your userID and pwd is incorrect, you are using the #QueryParam which would look for the userID and pwd as query parameters of the GET request like so:
http://myservice:port/checkuser?userId=myuserid&pwd=pass
if you change your GET request to
$http({
url : REST_END_POINT + '/checkuser',
method : "GET",
params : {
'userId' : credentials.username,
'pwd' : credentials.password
},
dataType : "json",
headers : {
"Content-Type" : "application/json"
}
});
Then you should have more luck.
However I wouldn't advise this method as it could be insecure. I'd instead look at trying to utilize an existing authentication system rather than rolling your own as these existing authentication systems will be far more secure.
You can use Jackson api for converting json to/ from Java objects.
Jackson contains simple mapper methods to implicitly map your json properties to Java class member variables.
Instead of #querypram use a Java class having fields as userId and pwd

how to encode and decode url in path string in java

I have requirement such that i need to send a URL in Ajax and the URL is /somehost/users/{userid}/feed/{feedurl} where userid and feedurl are path params which will be
accepted in a servlet written Using Rest Frame work.
My Ajax call is
$.ajax({
url : "/somehost/users/1/feeds/"+encodeURIComponent("**Please Think
that i passing a valid URL here**")),
type : "DELETE",
/*contentType: 'Content-type: text/plain; charset=iso-8859-1',*/
data : {feed_url : tr.attr("value")},
....
....
....
)};
My servlet is
#Path("/users")
public class UserServlet {
#DELETE
#Path("{user_id}/feeds/{feed_url}")
#Produces(MediaType.APPLICATION_JSON)
public String deletefee(
#PathParam("feed_url") String feedId,
#PathParam("user_id") #DefaultValue("1") String userId) {
System.out.println("I am in UserServlet delete");
}
}
Now i am not able hit my servlet.
I want to know how to send url as a #pathparam to my servlet.
If you add the extra slash to "/somehost/users/1/feeds" so it becomes "/somehost/users/1/feeds/" does that work?
Currently you are accessing a URI like "/somehost/users/1/feeds1" instead of "/somehost/users/1/feeds/1"

Categories