ModelAndView and ModelMap in Spring MVC - spring-mvc

#RequestMapping(value = "/testmap", method = RequestMethod.GET)
public ModelAndView testmap(ModelAndView model) {
ModelMap map=new ModelMap();
String greetings = "Greetings, Spring MVC! testinggg";
model.setViewName("welcome");
map.addAttribute("message", greetings);
return model;
}
I had
${message}
on welcome.jsp. But it does not prints the greetings.
Can you tell me the reason?

Model is an Interface. It defines a holder for model attributes and is primarily designed for adding attributes to the model. It contains four addAttribute (Overloaded) and one mergeAttributes and one containsAttribute method.
Example:
#GetMapping("/showViewPage")
public String passParametersWithModel(Model model) {
Map<String, String> map = new HashMap<>();
map.put("spring", "mvc");
model.addAttribute("message", "Baeldung");
model.mergeAttributes(map);
return "viewPage";
}
ModelAndView is a class which allows us to pass all the information required by Spring MVC (Model and View) in one return.
Example :
#GetMapping("/goToViewPage")
public ModelAndView passParametersWithModelAndView() {
ModelAndView modelAndView = new ModelAndView("viewPage");
modelAndView.addObject("message", "Baeldung");
return modelAndView;
}
Hope you get some clarity from this.

Related

Spring MVC, call Controller if the word mentioned in the RequestMapping matches in the URL

Is it possible to call the Controller if the executed URL contains the word mentioned in the #RequestMapping of the respective Controller?
Here is my code
#Controller
#RequestMapping({"/employee","/nonemployee","/temp"})
public class EmployeeController {
#Autowired
EmployeeService service;
#RequestMapping("/add")
public ModelAndView employee() {
ModelAndView modelAndView = new ModelAndView("emp/add", "command", new Employee());
return modelAndView;
}
#RequestMapping("/employees")
public ModelAndView getEmployeeList() {
ModelAndView modelAndView = new ModelAndView("/emp/employees", "list", service.getEmployeeList());
return modelAndView;
}
#RequestMapping(value = "/create")
public String createEmployee(#ModelAttribute Employee employee, ModelMap model) {
service.newEmployee(employee);
model.addAttribute("name", employee.getName());
model.addAttribute("age", employee.getAge());
model.addAttribute("id", employee.getId());
return "/emp/create";
}
}
Using the above code with #RequestMapping({"/employee","/nonemployee","/temp"}) and #RequestMapping("/employees"), we can call the following urls, to list values:
http://localhost:8080/Spring/employee/employees
http://localhost:8080/Spring/nonemployee/employees
http://localhost:8080/Spring/temp/employees
On observing closely, we can see the matching word emp within all the three words/values passed to the RequestMapping. So, what I am looking for is the way using which the execution of Controller is occurred, if the URL contains the word emp.
On execution of the following URLs, list of values must be returned by the same method (getEmployeeList()), but without passing multiple or all the values to RequestMapping Annotation:
http://localhost:8080/Spring/employee/employees
http://localhost:8080/Spring/nonemployee/employees
http://localhost:8080/Spring/temp/employees
http://localhost:8080/Spring/exempt/employees
http://localhost:8080/Spring/attempt/employees
Change you Request Mapping to -
#RequestMapping("/*emp*")
This should work for what you want to do.

How pass POST parameters from controller to another Controller Spring MVC?

I have startController and start view. In this view I input number and amount and validate it. If validation was successful, I want pass this parameters(number and amount) to another controller, and after that make some operations with it, in this controller. I see two way:
make this operations in first controller, in another methods and use second view for it. But my controller will very big and all logic will be this.
create second controller and second view and pass parameters to this controller.
I make this:
#Controller
#RequestMapping("/")
public class StartController {
#Autowired
private ValidateService validateService;
#RequestMapping(method = RequestMethod.GET)
public ModelAndView printWelcome() {
ModelAndView modelAndView = new ModelAndView("start");
return modelAndView;
}
#RequestMapping(value = "process", method = RequestMethod.POST)
public ModelAndView process(HttpServletRequest request) {
ModelAndView modelAndView;
String phoneNumber = request.getParameter("phone_number");
int amount = Integer.parseInt(request.getParameter("amount"));
String result = validateService.validate(phoneNumber, amount);
if (!result.equals("OK")) {
modelAndView = new ModelAndView("start");
modelAndView.addObject("result",result);
}else {
modelAndView = new ModelAndView("redirect:/check/process");
modelAndView.addObject("phone_number", phoneNumber);
modelAndView.addObject("amount",amount);
}
return modelAndView;
}
and if result != OK I redirect to new controller
#Controller
#RequestMapping("/check")
public class CheckController {
#RequestMapping(value = "process", method = RequestMethod.GET)
public ModelAndView process(HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView("check");
String phoneNumber = request.getParameter("phone_number");
int amount = Integer.parseInt(request.getParameter("amount"));
return modelAndView;
}
}
But I need pass parameters with RequestMethod.POST and it will not work. How do it?
You can return a ModelAndView with parameters as follow:
return new ModelAndView("redirect:/check/process?phone_number="+yourPhoneNumber+"&amount="+amount)
You can use forward to go to a new controller right?
"forward:/test2?param1=foo&param2=bar";
Please see below link for more details.
Spring forward with added parameters?

Signature of Methods Returning ModelAndView and Request Mapping by Method Name

Two beginner SpringMVC questions:
1) Are there required signature types in SpringMVC for ModelAndView-returning methods, or it's free-form, with whatever params/order you want? I've seen these examples:
public ModelAndView action1(HttpServletRequest request);
public ModelAndView action2(Model m);
public ModelAndView action2(HttpServletRequest request, Model m);
public ModelAndView action4();
//etc.
2) Is it possible to have a RequestMapping by method name, not the whole URL? We have a URL, /test, that can be either /test?method=action1 or /test?method=action2 (similar to Struts).
#RequestMapping("/test?method=action1")
public ModelAndView action1(Model m)
{
//...
}

Spring4 MVC ModelAndView Constructor

In Spring 4 MVC
In my Controller Class
#Controller
public class TesterController{
#RequestMapping(value = "/test", method = RequestMethod.GET)
public ModelAndView show(){
ModelAndView mav = new ModelAndView("Test");
mav.addObject("Test" , "TestObject");
return mav;
}
}
Can some one explain how is the use of the ModelAndView class in this controller.
What is use of addObject Method
and What is use of having constructor.
Thanks in Advance
Pavan
You can just look at the source as spring is open source.
The model is just a map. So the addObject, is just adding the string "TestObject", with a key of "Test".
A model and view is simply a string of the viewname, along with the associated map/model.
The view resolver will then find the appropriate view file based on viewname, and the map values can be resolved in the view using the key.

How to access a Spring MVC model attribute name that contain a dot in Freemarker

I have the following code snippet in Spring MVC (3.0).
#RequestMapping(value="/add", method = RequestMethod.POST)
public String handleAddResourceGroup(#Valid ResourceGroup resourceGroup, BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("flash.validationErrors", bindingResult.getAllErrors());
return "add";
}
//The rest of the code
}
How can access the model attribute with the name "flash.validationErrors" in Freemarker?
Try ${.data_model["flash.validationErrors"]}

Resources