Angularjs Unexpected token JSON - angularjs

I have a problem with angularjs and JSON.
This is my code.
list_user.jsp (this is the page where I print the table)
<tr ng-repeat="per in persons">
<td>{{ per.user }}</td>
<td>{{ per.password }}</td>
<td>{{ per.profile }}</td>
</tr>
controller.js
$http({
method : 'POST',
url : 'views/user/user.json'
}).success(function(data){
$scope.persons = data;
});
user.json
[
{
"user": "Quarterback",
"password": 5,
"profile": "ppp"
},
{
"user": "Wide Receiver",
"password": 89,
"profile": "oooo"
}
]
This way the table is generated correctly, but the json is fixed.
Now I'll paste the code with which I want to print the data by taking them from a query
controller.js
$http({
method : 'POST',
url : 'views/user/user.jsp'
}).success(function(data){
/*
var jsonStr="your json string";
var json=JSON.stringify(data);
json=JSON.parse(json)
console.log(json);
*/
console.log(data);
$scope.persons = data;
});
The code between / * .. * / left them to show that I also tried that road without success.
user.jsp
JSONArray jdata = new JSONArray();
UserRest as = new UserRest();
jdata = as.getAll();
logger.info("jdata in user.jsp "+jdata);
UserRest.class (just paste the code where I create the JSON)
while (iter.hasNext()) {
User ut = (User) iter.next();
JSONObject jtemp = new JSONObject();
jtemp.put("user", ut.getUserName());
jtemp.put("password", ut.getPassword());
jtemp.put("profilo", ut.getProfilo());
jarray.put(jtemp);
}
return jarray;
the result of logger.info("jdata in user.jsp "+jdata) in user.jsp
jdata in user.jsp [{"user":"aaaaaaa","password":"1111111","profile":"0"},{"user":"bbbbbbbb","password":"222222222","profile":"1"}]
As you can see the json looks the same, but when in the browser I call the list_user.jsp page in the console the value "data" in controller.js returns me
<? Xml version = "1.0" encoding = "utf-8"?>
I also tried with JSON.parse or JSON.stringify but it does not work.
I also added "track by $ index" here:
<tr ng-repeat = "for people track by $ index">
in list_user.jsp but it does not work.
Please help me because I do not know how to do it anymore.

Well, your problem appears to be that you should call a SERVICE, not a jsp.
A JSP builds a new web page for you and so it will put that:
< ? Xml version = "1.0" encoding = "utf-8"? >
Try doing, instead a jsp, a servlet (or use JAX-RS, as you prefer) and putting you logic inside the 'doGet' method (again, or use JAX-RS).
Do a simple thing, like
protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
response.getWriter().append(your working JSON properly hardcoded);
}
This way should work. Then put your service logic there.

Thank you very much #inigoD, I solved my problem.
Following the new code.
controller.js (UserRest is the servlet)
$http({
method : 'POST',
url : 'UserRest'
}).success(function(data){
$scope.persons = data;
});
web.xml
<servlet>
<servlet-name>UserRest</servlet-name>
<servlet-class>"path application".UserRest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserRest</servlet-name>
<url-pattern>/UserRest</url-pattern>
</servlet-mapping>
UserRest.class
#Override
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
#Override
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
try
{
JSONArray jdata = new JSONArray();
jdata = getAll();
logger.info("prima del response "+jdata);
response.setContentType("application/json");
response.getWriter().write(jdata.toString());
}
catch ( Exception ex )
{
ex.printStackTrace();
}
}
The function getAll() Is the same as I had pasted on, which contained this code.
while (iter.hasNext()) {
User ut = (User) iter.next();
JSONObject jtemp = new JSONObject();
jtemp.put("user", ut.getUserName());
jtemp.put("password", ut.getPassword());
jtemp.put("profilo", ut.getProfilo());
jarray.put(jtemp);
}
return jarray;

I resolve the problem with servlet, but I would like call a REST api.
I prefer don't use the servlet.
I change my code.
controller.js
angular.module('inspinia')
.controller("DataTable",['$scope','$http',function($scope,$http){
$http({
method : 'GET',
url : '/api/utenti'
}).success(function(data){
$scope.persons = data;
});
web.xml
<servlet>
<servlet-name>SpringServlet</servlet-name>
<servlet-class>com.xxx.yyy.userInterface.servlet.SpringServlet</servlet-class>
<load-on-startup>3</load-on-startup>
</servlet>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet-mapping>
<servlet-name>SpringServlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
UtentiController.class
#Path("/utenti")
#Component
#Scope("request")
public class UtentiController {
#GET
#Produces("application/json")
public JSONArray getAll() {
/* call the interface that return a json */
return jarray;
}
}
the error in the console is:
HTTP Status [404] – [Not Found]
Type Status Report
Message /api/utenti/
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Thanks for your help

Related

Setting up endpoints (Camel)

I am new to Camel and learning to setup routes.
So I started with a simple scenario, a URL that I hit and it returns me some data. For this example I have used http://services.groupkt.com/country/get/all for returning that data.
This is the setup for my path
from("direct:greet")
.autoStartup(true)
.routeId("greet")
.setHeader(Exchange.HTTP_METHOD, constant(HttpMethods.GET))
.to("http4://services.groupkt.com/country/get/all")
Now I have requestMapping to a URL /check and when I hit this URL http://localhost:8080/check it returns this
{
"timestamp": 1527882311362,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/check"
}
I was expecting the JSON response to show up with the data for all the countries listed which you see when you hit the URL(http://services.groupkt.com/country/get/all) in your browser.
The mapping is in other class:
#RequestMapping(value = "/check", method = RequestMethod.GET)
public String get(#RequestParam(value = "name") String name) {
return serviceProcessor.getServiceResponse(name);
getServiceResponse goes as follows:
public String getServiceResponse(String name) {
final ModelCamelContext context = userServiceRoute.getContext();
final ProducerTemplate template = new DefaultProducerTemplate(context);
try {
template.start();
} catch (Exception e) {
LOGGER.error("Error starting producerTemplate with userServiceRoute" + e);
}
final Endpoint endpoint = context.getEndpoint("direct:greet");
template.setDefaultEndpoint(endpoint);
return template.requestBody((Object)name, String.class);
}
Is there something wrong with the path setup or the approach itself is wrong here?

angularjs rest API Spring

i have a problem with rest API in angularjs.
web.xml
<servlet>
<servlet-name>SpringServlet</servlet-name>
<servlet-class>com.mycompany.xxxx.userInterface.servlet.SpringServlet</servlet-class>
<load-on-startup>3</load-on-startup>
</servlet>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet-mapping>
<servlet-name>SpringServlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
SpringServlet.class
#Override
public void init() throws ServletException
{
super.init();
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
SpringBeanReader.getInstance().setApplicationContext(applicationContext);
//SpringBeanReader.getInstance().getApplicationContext().getBean(")
}
I have problems when I call api.
controller.js
.service('ApiCall', ['$http', function ($http){
//Get All Employees
this.getEmployees = function () {
console.log('dentro service.js');
return $http.get("/utenti/all");
}
}])
.controller("DataTable",['$scope','ApiCall',
function($scope,ApiCall){
$scope.persons = ApiCall.getEmployees();
}])
Controller.class
#Path("/utenti")
public class UtentiController {
#Path("/all")
#GET
#Produces("application/json")
public JSONArray getAll() {
/**** code for JSON array ***/
}
The code "$http.get("/utenti/all");" return error
HTTP Status [404] – [Not Found]
Type Status Report
Message /foodplan/utenti/all
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Thanks to all.

Passing String from angular to Spring using #Requestbody

I am working on a project using angularjs+springboot. Am trying to send email via my application using spring-boot-starter-mail. The message and object of the email are written by the user in a form. what I want to do is to get the message and object values in my RestController using #RequestBody.
the function in my service.js
// send mail
var sendMail = function(id, objet, msg) {
var deferred = $q.defer();
$http.post(urlBase + id, objet, msg).then(
function(response) {
deferred.resolve(response.data);
}, function(errResponse) {
console.error('Error while sending email');
deferred.reject(errResponse);
});
return deferred.promise;
}
the method in my restContoller
#RestController
public class EmailController {
#Autowired
private JavaMailSender javaMailSender;
#Autowired
UtilisateurService service;
#RequestMapping(value = "/users/{id}", method = RequestMethod.POST)
public ResponseEntity<Void> sendMail(#PathVariable("id") int id, #RequestBody String objet,
#RequestBody String msg) {
Utilisateur currentUser = service.findById(id);
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(currentUser.getEmailUtil());
message.setSubject(objet);
message.setText(msg);
javaMailSender.send(message);
return new ResponseEntity<Void>(HttpStatus.OK);
}}
This throws this exception :
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity<java.lang.Void> com.sla.utilisateur.controller.EmailController.sendMail(int,java.lang.String,java.lang.String)
How can I fix it?
thank you,
Your usage of $http.post is not correct. You should have a look at the AngularJS POST documentation. $http.post arguments are the following:
post(url, data, [config]);
AngularJS sends the data by default in JSON. So you should send the request using the following statement (for example):
$http.post(urlBase + id, {subject:objet, body:msg})
And in your controller you should define only one #RequestBody maps for the ease of the example to a Map (You could change it to a POJO. ):
#RequestMapping(value = "/users/{id}", method = RequestMethod.POST)
public ResponseEntity<Void> sendMail(#PathVariable("id") int id, #RequestBody Map<String,String> msg) {
Utilisateur currentUser = service.findById(id);
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(currentUser.getEmailUtil());
message.setSubject(msg.get("subject");
message.setText(msg.get("body"));
javaMailSender.send(message);
return new ResponseEntity<Void>(HttpStatus.OK);
}}

Not able to access web api calls in a api/controller format

Hi I am developing one application using web api2 and accessing calls via angularjs. I created web api calls and hosted in iis server(public ip). I am accessing the web api2 methods in the below format.
$http.post('http://111.93.133.98:4500/api/NCT_Login/', credentials).success(function (response) { alert(response); });
This is my web api config.cs file.
routeTemplate: "api/{controller}/{id}"
This is my controller code.
public class NCT_LoginController : ApiController
{
public NCTEntities entityObject = new NCTEntities();
[EnableCors(origins: "*", headers: "*", methods: "GET, POST, PUT, DELETE")]
public IHttpActionResult Post(LoginClass obj)
{
try
{
if (ModelState.IsValid)
{
obj.User_Password = PasswordEncryption.sha256_hash(obj.User_Password);
bool result = (from c in entityObject.NCT_UserRegistration where obj.User_Name ==c.User_Name && obj.User_Password == c.User_Password select c).Any();
if(result==true)
{
obj.UserRole = (from c in entityObject.NCT_UserRegistration where obj.User_Name == c.User_Name && obj.User_Password == c.User_Password select c.User_Role).FirstOrDefault();
obj.Success = 0;
obj.User_Password = "";
var response = Request.CreateResponse(HttpStatusCode.OK, obj);
var newSessionId = new SessionIDManager().CreateSessionID(HttpContext.Current);
var cookie = new CookieHeaderValue("session-id", newSessionId);
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";
response.Headers.AddCookies(new[] { cookie });
return ResponseMessage(response);
}
else
{
return Content(HttpStatusCode.BadRequest, 1);
}
}
else
{
return Content(HttpStatusCode.BadRequest, 1);
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
If i remove api from route template I am able to access api's and if i put api.NCT_Login then I am getting preflight error. I am not sure what i am missing here. Any help would be appreciated. Thank you.
I would decorate the post method with a attribute route like this
[RoutePrefix("api/NCT_Login")]
public class NCT_LoginController : ApiController
{
public NCTEntities entityObject = new NCTEntities();
[EnableCors(origins: "*", headers: "*", methods: "GET, POST, PUT, DELETE")]
[Route("Login")]
[HttpPost]
public IHttpActionResult Post(LoginClass obj)
{
This would set the route to api/NCT_Login/Login
IMO its a good practice to use attribute routing as it gets very clear what each method route is.
Also when controllers grow its easy to define new routes on the same http verb

angularjs sending request front to back-end

i am sending remove request from front-end using angularjs code for js is
var data = ersutils.getJsonCopy({"id" : $scope.resourceList[idx].id},$scope.resourceList[idx]);
ResourceService.remove(data, function(data){
//vm.dtInstance.reloadData(undefined, false);
$modalInstance.close();
}, function (resp){
if(resp.status == 500){
scope.modalinfo.message = "<code> this resource has booking(s) do you want to delete? </code>";
ResourceService.remove({'id': delRes}, function(){
//vm.dtInstance.reloadData(undefined, false);
$modalInstance.close();
})
}else{
scope.modalinfo.message = "<code> Unable to delete this Resource </code>";
}
});
here ersutils provide jsoncopy for multiple parameters...when i have sent this data to rest api it says that unsupported media type
restapi code for delete is
#DELETE
#Path("/{id:\\d+}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response removeRes(#PathParam("id") int id,Map<String, Object> source){
Map<String, Object> resp = new HashMap<>();
//Map<String, Object> source=new HashMap<>();
try{
resp.put("response",service.removeRes(id,source));
return Response.status(Status.OK).entity(resp).build();
}catch(FrontErsException e){
resp.put("cause", e.getMessages());
return Response.status(Status.CONFLICT).entity(resp).build();
}catch(ErsException e){
resp.put("cause", e.getMessages());
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(resp).build();
}
}
error is
angular.js:10514 DELETE http://localhost:8080/ers_dev/rest/resources/10?dynamicFields=%7B%22code%22…2016-05-27%22%7D&firstName=vinay&isHuman=true&name=N%2FA&typeName=Employee 415 (Unsupported Media Type)
Did you try using #Consumes(MediaType.APPLICATION_FORM_URLENCODED) instead of APPLICATION_JSON?
Don't know exactly what you're using for your backend, but uUsually DELETE requests doesn't care about request body, so params are URL encoded.

Resources