how to access model value in angular controller - java

I want to access model attribute values in angular controller. I have returned from spring controller like this.
#RequestMapping(value="/helloWorld", method=RequestMethod.GET)
public void helloWorld(HttpRequest req, Model model) {
String typeOfMoney = req.getSession().getAttribute("typeOfMoney").toString();
model.addAttribute("typeOfMoney",typeOfMoney);
return "MyJsp";
}
That typeOfMoney need to assign in my angular controller. How can I get this typeOfMoney in angular controller.like the below
var app = angular.module('App', ['ui.bootstrap']);
app.controller('fcController', function($scope) {
var y = typeOfMoney;
});

I think Model and view(i.e attributes of request or response or Session) is specific to Spring(i.e Java) It can't be accessed in Angular Js directly.

Related

Use ModelAndView in a Rest API app

I'm writing a web app which only consists of Rest API endpoints. There is no jsp, nor any UI written in Java provided by the app. (I'm planning to write the front end in React in future)
Does it make sense to use ModelAndView in my controllers ? I want to do a redirect to another URL ? I see sample codes similar to the following code:
#Controller
#RequestMapping("/")
public class RedirectController {
#GetMapping("/redirectWithRedirectPrefix")
public ModelAndView redirectWithUsingRedirectPrefix(ModelMap model) {
model.addAttribute("attribute", "redirectWithRedirectPrefix");
return new ModelAndView("redirect:/redirectedUrl", model);
}
}
If your controller is always going to redirect, you can just return a String e.g.
return "redirect:/redirectedUrl";
Otherwise, you can return a response entity:
final HttpHeaders headers = new HttpHeaders();
headers.add("Location", "/redirectedUrl");
return new ResponseEntity<Foo>(headers, HttpStatus.FOUND);
I don't think it makes sense to return a ModelAndView if there is no view.

AngularJs how to access Model Attribute value from Spring MVC controller

I have a Spring MVC Controller returning a page with an attribute as followed
#RequestMapping(method = RequestMethod.GET, value = "/create")
public ModelAndView getAddAccountView() {
ModelAndView model = new ModelAndView("protected/accounts/AccountAddView");
List<Client> clients=clientService.findAll();
model.addObject("listClients", clients);
return model;
}
Client is a #Entity
in my AccountAddView.jsp file, i'm trying to use the ng-init as follow:
<div class="row-fluid" ng-controller="accountsController as ctrl" ng-init="clients=${listClients}">
and in my app.js, in my controller, i try to access the list of client as followed
var listOfClients=$scope.clients;
but I'm still getting the following error
angular.min-1.5.3.js:116 Error: [$parse:lexerr] http://errors.angularjs.org/1.5.3/$parse/lexerr?p0=Unexpected%20nextharacter%20&p1=s%2033-33%20%5B%40%5D&p2=clients%3D%5Bsoftbank.ui.model.Client%4042%2C%softbank.ui.model.Client%4041%2C%softbank.ui.model.Client%4043%5D
at Error (native)
at http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:6:416
at gc.throwError (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:212:149)
at gc.lex (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:211:16)
at Object.ast (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:216:103)
at Object.compile (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:225:232)
at hc.parse (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:252:380)
at e (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:123:317)
at m.$eval (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:142:463)
at pre (http://localhost:8080/softbank/resources/js/angular.min-1.5.3.js:271:500)
please what is wrong here. why is ng-init generating this errors?
thanks in advance for your answer.
I'm just starting with Angular with Spring so what I'll do is explain how I did it and you can see if it's a viable option for you.
For one, I didn't try to go through the ModelAndView for my data. I let my "regular" controller return the view but got my data via the angular controller and service along with a #RestController on the Spring side (that's two separate Spring controllers then).
To return only the view you have at least two options that I'm aware of. One, you can just return a ModelAndView without a model like so:
public ModelAndView yourView() {
return new ModelAndView("yourView");
}
Or two, return the name of the view as a string like so:
public String yourView() {
return "yourView";
}
In both cases you'd obviously need the correct #RequestMapping.
In my view I had an angular controller function that made a call to my associated angular service which in turn called my #RestController and so on. I initiated the data like so:
ng-controller="MyController as ctrl" ng-init="ctrl.allThings()"
Examples of the code:
Angular controller:
self.allThings = function () {
ThingService.things()
.then(
function (data) {
self.things = data;
},
function (errResponse) {
console.error("Error retrieving thing list");
}
);
};
Angular service:
things: function() {
return $http.get('/things')
.then(
function(response) {
return response.data;
},
function (errResponse) {
return $q.reject(errResponse);
}
);
},
Spring REST controller:
#RequestMapping(value = "/things", method = RequestMethod.GET)
public List<Thing> things() {
return thingService.findAll();
}
I imagine you know the remaining code for the Spring side. Jackson will handle all the object conversions for you.
Old Post but still I would like to answer so that anyone who is using Angular with Spring MVC get some help.
Using model attribute is a challenge with Angular. Earlier I was setting employee data in model attribute like mav.addObject("employee",employee), but when I was trying to use ${employee} inside the jsp, Angular wasn't able to set the java object using ng-init directive because it was expecting a java script object. So I set json inside the model Attribute mav.addObject("employeeJson", empJson) and parsed it using json.Parse() to convert it into Java Script Object and was able to use it with Angular expressions on the jsp Below are the steps which I followed:
1. Spring Controller
In your controller, set json in the model attribute. For e.g.
mav.addObject("employeeJson", empJson);
Make sure before adding it to ModelAttribute, replace quotes with html entity " otherwise there will be error while parsing the json
empJson.replaceAll("\"", "\&\quot;");
2. Jsp
Use angular init directive, data-ng-init="yourController.getEmployeeData('${employeeJson}')"
3. In Angular js parse this json to get the json
var vm = this;
vm.employee = {};
vm.getEmployeeData = function(employeeJson){,
vm.employee = JSON.parse(employeeJson);
};
4. Inside jspI can access employee name as
{{yourController.employee.firstName}}

Setting Cookie not working in Spring web-mvc 4

I need to set a cookie with redirect in my login controller. I used code below to set cookie.
#RequestMapping("/fbresponse")
public String getToken(#RequestParam(required = false, value = "code") String code, HttpServletResponse sResponse) {
sResponse.addCookie(new Cookie("logged", "123"));
return "redirect:"+user.getLastPage();
}
In my index I try to retrive the cookie using following code:
#RequestMapping("/")
public String getIndex(#CookieValue(value="logged", required=false)String test){
user.setLastPage("/");
loginCheck();
System.out.println(test);
return "index";
}
But it always returns null. I tried returning new ModelAndView. It also did not work and since I need some components in model it does not suit my requirement.
How can set and retrieve a cookie? Is it possible to do it with redirect?
UPDATE
I have class level #RequestMapping in my login controller.
#Controller
#RequestMapping("/login")
public class LoginController {
#RequestMapping("/fbresponse")
public String getToken(#RequestParam(required = false, value = "code") String code, HttpServletResponse sResponse) {
sResponse.addCookie(new Cookie("logged", "123"));
return "redirect:"+user.getLastPage();
}
}
When I remove the class level request mapping add cookies works. How can I add a cookie correctly with class level request mapping?
You need to set the path of the cookie, otherwise it's valid only for the current path.

Does HttpServletRequestWrapper work with RequestDispatcher

I have a requirement where the back-end Spring controller is expecting certain values in the request header, i.e certain custom headers.
The view, a jsp has a html form which will submit the parameters from the end user to the controller. Since it is not possible to send custom headers from an html form or javascript function without using XMLHttpHeader. I cannot use XMLHttpHeader in this case since that will be an AJAX call and in my case i want a form submit.
The only option left for me is, add a mediator servlet which will intercept the call from the jsp, read the values from the request parameter and then add them as request headers and forward them to the final controller. Since it is not possible to add custom header in HttpServletRequest, i used HttpServletRequestWrapper as given in the
example.
The problem is to forward it to the Spring controller , the following code
MockHttpRequestWrapper req = new MockHttpRequestWrapper(request);
req.addHeader("REMOTE_USER", ssoId);
req.addHeader("REALM", realmId);
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(req, response);
where MockHttpRequestWrapper is a type of HttpServletRequestWrapper as per the example
public class MockHttpRequestWrapper extends HttpServletRequestWrapper {
private Map customHeaderMap = null;
public MockHttpRequestWrapper(HttpServletRequest request) {
super(request);
customHeaderMap = new HashMap();
}
public void addHeader(String name,String value){
customHeaderMap.put(name, value);
}
#Override
public String getParameter(String name) {
String paramValue = super.getParameter(name); // query Strings
if (paramValue == null) {
paramValue = (String) customHeaderMap.get(name);
}
return paramValue;
}
}
I haven't tested the sample with Filters but i expected the same to work with RequestDispatchers. The final controller is called but the headers are not to be found.
Is the same Request object not passed to the controller? IN the controller the code
request.getHeader("REMOTE_USER")
returns null.
Looking forward to answers to expand my understanding on the subject :)

.getJSON 404 Error with ModelAndView

I am trying to retrieve some JSON data in my javascript by making a call to the controller. The controller returns a MappingJacksonJsonView ModelandView, but the .getJSON is always reporting a 404 at .../handhygiene.json.
Is there a problem with the way I am returning the ModelandView from the controller?
Controller
#RequestMapping(value = "/{room}/handhygiene.json", method = RequestMethod.GET)
public ModelAndView getHandHygienePageAsync(
#PathVariable(value = "room") String roomCode) {
ModelAndView mav = new ModelAndView(new MappingJacksonJsonView());
mav.getModelMap().addAttribute(blahblahblah); //adds some attributes
...
return mav;
}
Javascript
var currentURL = window.location;
$.getJSON(currentURL + ".json",
function(data) {
... //does stuff with data
}
If you're trying to get only an JSON object from Ajax request, you need to add #ResponseBody to your method, and make you result object as return from your method.
The #ResponseBody tells to Spring that he need to serialize your object to return to the client as content-type. By default, Spring uses JSON Serialization. ModelAndView will try to return an .JSP page. Maybe you don't have this jsp page on your resources so, the server return 404 error.
I Think this code should work for you:
#RequestMapping(value = "/{room}/handhygiene.json", method = RequestMethod.GET)
public #ResponseBody Room getHandHygienePageAsync(#PathVariable(value = "room") String roomCode) {
Room room = myService.findRoomByRoomCode(roomCode);
return room;
}
I'm assuming you're using the Room as your result object, but it may be another object or ArrayList, for example.
You cant take a look here for Spring example, and here for example and configuration.

Categories