Hi Friends , My today's post is on usage of Multiple Controller in one application . Till the examples I have shown use only one controller .If you haven't gone through simple examples like Hello World Example in Spring MVC, Spring MVC validations and Spring Flow please first go through them otherwise it ll be difficult for you to understand .
In the example below I am going to create 2 controllers with different @RequestMapping to show how the request ll flow:
Step 1: Controller classes:
package com.javainhouse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloWorldController {
@RequestMapping("/hello")
public ModelAndView helloWorld() {
String message = "Inside Hello Controller";
return new ModelAndView("hellopage", "message", message);
}
}
and the other controller
package com.javainhouse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class WelcomeController {
@RequestMapping("/welcome")
public ModelAndView helloWorld() {
String message = "Inside Welcome Controller";
return new ModelAndView("welcomepage", "message", message);
}
}
Step 2: Views of application
index.jsp
<a href="hello.html">Hello World Controller</a>
<a href="welcome.html">Welcome Controller</a>
hellopage.jsp
Message is: ${message}
welcomepage.jsp
Message is: ${message}
Note : These views should be located under WEB/INF folder and hellopage.jsp and welcomepage.jsp should be under jsp folder under WEB/INF folder as we have given /jsp in view resolver .For proper servlet.xml ,spring .xml please go through Hello World tutorial.
Explanation :
This is very simple program ,If you have already gone through my previous programs . As in -servlet.xml we have given the basic package in which we have defined both controllers in package com.javainhouse. Request with hello.html link ll go to HelloWorldController and welcome ll go to Welcome Controller .
Thats it for this program .Please provide suggestions and errors in the comments below :)
Thats it for this program .Please provide suggestions and errors in the comments below :)
Post a Comment