Spring4 MVC ModelAndView Constructor - spring-mvc

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.

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.

spring mvc application to navigate flow from controller to jsp or servlet of another application

I am using spring mvc application. I want to redirect from controller or jsp to my second application that was developed in plain servlet and jsps.
How can I navigate flow from one apps servlet/jsps to another apps jsp.
I have used following lines in my controller to navigate:
First:
return new ModelAndView("redirect:/http://localhost:9090/MarathiInput/test.jsp");
Second:
response.sendRedirect("http://localhost:9090/MarathiInput/test.jsp");
Currently my controller is :
#RequestMapping(value = "/transferCertificate", method = RequestMethod.GET)
public ModelAndView get(ModelMap map ,HttpServletResponse response) {
response.sendRedirect("localhost:9090/MarathiInput/test.jsp");
}
and in my jsp i am calling :
Generate TC this link
You have small errors in both tries, but both can be used.
Assuming method controller is declared to return a ModelAndView you can use :
return new ModelAndView("redirect:http://localhost:9090/MarathiInput/test.jsp");
If it is declared to return a String :
return "redirect:http://localhost:9090/MarathiInput/test.jsp";
Alternatively provided the controller method has the response as parameter, you can do the redirect in controller, but as you have already processed the response, the method must return null :
response.sendRedirect("http://localhost:9090/MarathiInput/test.jsp");
return null;
So you could use :
#RequestMapping(value = "/transferCertificate", method = RequestMethod.GET)
public ModelAndView get(ModelMap map ,HttpServletResponse response) {
response.sendRedirect("http://localhost:9090/MarathiInput/test.jsp");
return null;
}
or simply :
#RequestMapping(value = "/transferCertificate", method = RequestMethod.GET)
public String get(ModelMap map ,HttpServletResponse response) {
return "redirect:http://localhost:9090/MarathiInput/test.jsp");
}
But make sure that the link includes the servlet context and servlet path :
Generate TC this link

If I am using two #InitBinder in a one controller then how it belongs to two particular BindingResult?

Below code in my controller class.
#Controller
#RequestMapping("/library/*")
public class HelloController {
#Autowired
#Qualifier("booksValidator")
private Validator booksValidator;
#Autowired
#Qualifier("loginValidator")
private Validator loginValidator;
#InitBinder("login")
private void initUserBinder(WebDataBinder loginBinder) {
loginBinder.setValidator(loginValidator);
}
#InitBinder("book")
private void initBooksBinder(WebDataBinder booksBinder) {
booksBinder.setValidator(booksValidator);
}
#RequestMapping(value="welcome", method = RequestMethod.POST)
public String printWelcome(#Validated #ModelAttribute("user") User user, BindingResult login, ModelMap model) {
}
#RequestMapping(value="add", method = RequestMethod.POST)
public String addBooks(#Validated #ModelAttribute("books") Books books, BindingResult book, ModelMap model) {enter code here
}
}
#InitBinder("login") belongs to--> BindingResult login
#InitBinder("book") belongs to--> BindingResult book
How I can do?
Please suggest me...
:(
A Spring controller can have multiple #InitBinder methods. But you are not using correctly the value of the annotation. According to InitBinder javadoc about the value parameter, Specifying model attribute names or request parameter names here restricts the init-binder method to those specific attributes/parameters
So in your example, you should use ModelAttribute names and not BindingResult parameter names, that is #InitBinder("user") and #InitBinder("books") instead of (resp.) #InitBinder("login") and #InitBinder("book").
i would suggest you split this into two separate controllers. One that deals with your users/login and the other to deal with books. So, something like LoginController that has the init binder for login, and BooksController that has the book validator for validating books.

Mapping custom data type from URL to Spring MVC controller using #ModelAttribute

I am trying to send parameters from UI to Spring MVC controller. My parameter looks like
caseId=23951910&serviceProvided%5B0%5D.id=25989&serviceProvided%5B0%5D.desc=24-Hour+Service&serviceProvided%5B0%5D.duration=1&serviceProvided%5B0%5D.pages=--&serviceProvided%5B1%5D.id=25988&serviceProvided%5B1%5D.desc=3rd+Party+Contact&serviceProvided%5B1%5D.duration=2&serviceProvided%5B1%5D.pages=--&serviceProvided%5B2%5D.id=25980&serviceProvided%5B2%5D.desc=Advice&serviceProvided%5B2%5D.duration=3&serviceProvided%5B2%5D.pages=--&serviceProvided%5B3%5D.id=25982&serviceProvided%5B3%5D.desc=Document+Preparation&serviceProvided%5B3%5D.duration=4&serviceProvided%5B3%5D.pages=--&serviceProvided%5B4%5D.id=DOCREVIEW&serviceProvided%5B4%5D.desc=Document+Review&serviceProvided%5B4%5D.duration=5&serviceProvided%5B4%5D.pages=6
To match this parameter I am using custom class as
Class MyDto {
private Long caseId;
private List<ServiceProvided> serviceProvided;
//getter and setter
}
Class ServiceProvided {
private String id;
private String desc;
private Long duration;
private Long pages;
//getter and setter
}
I have controller as
#RequestMapping(value = "/cases/resolveClaim.htm", method = RequestMethod.POST)
public ModelAndView createClaim(#ModelAttribute("claimInfo") MyDto myDto, BindingResult result) { ... }
I am getting 404 error so I am guessing "serviceProvided" list couldn't match to myDto. So my questions are:
Is this a really a reason I am getting 404 error?
If yes I guess I have to solve with PropertyEditor or Converter? Am I correct?
Is there any example code that I can refer to?
Thanks

Binding a Backbone.js object to a Spring Controller while utilising #InitBinder

I am having trouble getting #InitBinder to work with Backbone.js
#InitBinder
public final void initBinder(final WebDataBinder binder) {
// Customer property editors
binder.registerCustomEditor(MyObjectChild.class, new MyObjectChildEditor());
}
I have a controller like this that accepts the object
#RequestMapping(
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.POST)
#ResponseBody
#ResponseStatus(value = HttpStatus.CREATED)
public final String create(#RequestBody final MyObject myobject) {
return "worked";
}
MyObject has a property of type MyObjectChild. I would like to pass the ID values of this object from the frontend to the controller because it does not make sense for the user to have the ability to modify it (they will select it from the drop down list).
I have read that #RequestBody does not work with #InitBinder so I tried #ModelAttribute instead, but I don't know what the #ModelAttribute name would be because it is created on the frontend in javascript using Backbone.js.
How do I get Backbone.js to work with Spring #InitBinder?

Resources