How to get value from a ModelAndView object in jsp Page? - spring-mvc

For eg:i use a method in controller class :
public ModelAndView fileupload(HttpServletRequest request, HttpServletResponse response) throws Exception
Within that method i use
Map modelMap = new HashMap();
Then set the value like
modelMap.put(name,request.getParameter("uname"));
Then in modelView object I add the object like
modelView.addAllObjects(modelMap);
Then set the view like
modelView.setViewName("salu.jsp");
then returned modelView object.
It is displaying that jsp page but the value I print in jsp using the scriptlet like
<% String username=request.getAttribute("name");
out.println("name is "+username); %>.
But it is printing the value is null. Tell me how i can get thet Value.

Assuming variable name value in your controller is "name", just use ${name} in your JSP.

Related

How to get model saved in session with #ModelAttribute parameter annotation?

In my controller advice I have put one model object in HttpSession session:
Map<String, Game> gamesMap = new HashMap<>();
gamesMap.put("1", new Game());
Games games = new Games();
games.setGames(gamesMap);
session.setAttribute("games", games);
When I try to get that object with #ModelAttribute parameter games.getGames() returns me always null instead of the gamesMap I've set before.
RequestMapping(value = "test", method = RequestMethod.GET)
public String test(#ModelAttribute("games") Games games) {
games.getGames(); // getGames() returns null instead of collection I've set before.
}
Am I doing something wrong? When I use session and get it from there it works fine, but I'm trying to understand why it doesn't work with #ModelAttribute which is more cleaner.
Ok, I found what the issue was. Spring only tries to bind model attribute to session parameter if the controller is annotated with #sessionattributes. If it doesn't find that it creates new instance in which case the map was null.

How to call JSP from a java Controller

I have a simple J2EE application with Spring.
Now I want from Java controller call another page. For example, I'm in registrazione.jsp, I click on one button, and I call a method in registrazioneController.java.
Now I want from registrazioneController.java, call another page, for example
home.jsp and I want pass any parameter in get.
It is possible?
this is the method that I use when I click the button
registrazioenControlle.java
public ModelAndView internalLoadPage(HttpServletRequest request, HttpServletResponse response, Map model) throws Exception
{
//to do
//call another page for example home.html
request.getRequestDispatcher("home.jsp").forward(request, response);
return new ModelAndView("home", model);
}
I'm try to use this code but no found.
In addition to the answer provided in the comments, you can also use RedirectAttributes, and addAttribute method if you want to append a parameter to URL upon redirect. This will also give you the addFlashAttribute that will store the attributes in the flash scope which will make it available to the redirected page. You can also return a simple string as the view name e.g. like
public String internalLoadPage(RedirectAttributes redirectAttributes) throws Exception
{
redirectAttributes.addAttribute("paramterKey", "parameter");
redirectAttributes.addFlashAttribute("pageKey", "pageAttribute");
return "redirect:/home";
}
this assumes that the view suffix is configured in you view resolver configuration

spring mvc-adding a object to the request

I am new to spring-mvc and have a basic question.
I have a controller that reads the parameters that are sent in from a jsp and adds an object called userInfo to the ModelAndView and passes on to another jsp. The second jsp displays the vaious properites of the userInfo.
How do I send back the userInfo object to the controller?
<td><input type="hidden" name="userInfo" value="${requestScope.userInfo}"/></td>
I try to read the userInfo in the controller as follows:
request.getAttribute("userInfo")
However, this is null.
What is the best way for me to do this?
Thanks
HTML <form> <input> elements are sent as url-encoded parameters. You need to access them with HttpServletRequest#getParameter(String)
request.getParameter("userInfo");
Or use the #RequestParam annotation on a handler method parameter
#RequestMapping(...)
public String myHandler(#RequestParam("userInfo") String userInfo) {
...
}
Note however, that this won't send back the object, it will send back a String which is the toString() value of the object because that is what is given with ${requestScope.userInfo}.
Consider using session or flash attributes to have access to the same object in future requests.

SpringWebflow: Setting values in RequestContext -> httpServletRequest is not accessible at JSP

I am setting some values in request in my action/controller class like this:
HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getNativeRequest();
request.setAttribute("testKey", "testValue");
But when I tried to retrieve this from JSP, I am getting null value.
<%
String testKey = ""+request.getAttribute("testKey");
%>
Any idea, please help.
After research I found 2 ways to do this:
1) Using a same modelAttribute in and assign values back and forth
2) setting values into context.getFlowScope().put(KEY,OBJECT);
And retrieving this value (OBJECT) from JSP using ${KEY}.

What is the use of BindingResult interface in spring MVC?

Is BindingResult useful to bind just exceptions with view, or something else?
what is the exact use of BindingResult?
Or is it useful in binding model attribute with view.
Particular example: use a BindingResult object as an argument for a validate method of a Validator inside a Controller.
Then, you can check this object looking for validation errors:
validator.validate(modelObject, bindingResult);
if (bindingResult.hasErrors()) {
// do something
}
Basically BindingResult is an interface which dictates how the object that stores the result of validation should store and retrieve the result of the validation(errors, attempt to bind to disallowed fields etc)
From Spring MVC Form Validation with Annotations Tutorial:
[BindingResult] is Spring’s object that holds the result of the
validation and binding and contains errors that may have occurred. The
BindingResult must come right after the model object that is validated
or else Spring will fail to validate the object and throw an
exception.
When Spring sees #Valid, it tries to find the validator for the
object being validated. Spring automatically picks up validation
annotations if you have “annotation-driven” enabled. Spring then
invokes the validator and puts any errors in the BindingResult and
adds the BindingResult to the view model.
It's important to note that the order of parameters is actually important to spring. The BindingResult needs to come right after the Form that is being validated. Likewise, the [optional] Model parameter needs to come after the BindingResult.
Example:
Valid:
#RequestMapping(value = "/entry/updateQuantity", method = RequestMethod.POST)
public String updateEntryQuantity(#Valid final UpdateQuantityForm form,
final BindingResult bindingResult,
#RequestParam("pk") final long pk,
final Model model) {
}
Not Valid:
RequestMapping(value = "/entry/updateQuantity", method = RequestMethod.POST)
public String updateEntryQuantity(#Valid final UpdateQuantityForm form,
#RequestParam("pk") final long pk,
final BindingResult bindingResult,
final Model model) {
}
Well its a sequential process.
The Request first treat by FrontController and then moves towards our own customize controller with #Controller annotation.
but our controller method is binding bean using modelattribute and we are also performing few validations on bean values.
so instead of moving the request to our controller class, FrontController moves it towards one interceptor which creates the temp object of our bean and the validate the values.
if validation successful then bind the temp obj values with our actual bean which is stored in #ModelAttribute otherwise if validation fails it does not bind and moves the resp towards error page or wherever u want.
From the official Spring documentation:
General interface that represents binding results. Extends the
interface for error registration capabilities, allowing for a
Validator to be applied, and adds binding-specific analysis and model
building.
Serves as result holder for a DataBinder, obtained via the
DataBinder.getBindingResult() method. BindingResult implementations
can also be used directly, for example to invoke a Validator on it
(e.g. as part of a unit test).
BindingResult is used for validation..
Example:-
public #ResponseBody String nutzer(#ModelAttribute(value="nutzer") Nutzer nutzer, BindingResult ergebnis){
String ergebnisText;
if(!ergebnis.hasErrors()){
nutzerList.add(nutzer);
ergebnisText = "Anzahl: " + nutzerList.size();
}else{
ergebnisText = "Error!!!!!!!!!!!";
}
return ergebnisText;
}

Resources