Spring 4 MVC Example
The Spring MVC framework makes it very elegant to create a web applicaton, the following is the points to remember when going through the embedded video.
- The dispatcher servlet examines the incoming request URL and invokes the right controller method to handle the Request. Here we are simply starting the servlet on load, and asking it to handle incoming request.
- <servlet>
- <servlet-name>dispatcher</servlet-name>
- <servlet-class>
- org.springframework.web.servlet.DispatcherServlet
- </servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>dispatcher</servlet-name>
- <url-pattern>*.html</url-pattern>
- </servlet-mapping>
2. But how will the servlet know where to find the controllers and the Views to forward, this is configured in the dispatcher-servlet, the component scan and Mvc annotations take care of finding the beans and the viewresolver of getting the Views.
- <context:component-scan base-package="com.bot.controller" />
- <mvc:annotation-driven />
- <bean id="viewResolver"
- class="org.springframework.web.servlet.view.UrlBasedViewResolver">
- <property name="viewClass"
- value="org.springframework.web.servlet.view.JstlView" />
- <property name="prefix" value="/WEB-INF/jsp/" />
- <property name="suffix" value=".jsp" />
- </bean>
3. Once the request reaches the Controller the @RequestMapping is used to map a request to method, there is a method attribute with the @RequestMapping called method, GET is default hence we are not using it here. Its useful when using forms to POST data to server.
- @Controller
- public class AccessController {
- public AccessController(){
- System.out.println("Hit Me");
- }
- @RequestMapping("/welcome")
- public ModelAndView helloWorld() {
- System.out.println(">>>Hit Me");
- String message = "<h1>Hi, Welcome to Spring MVC<h1/>";
- return new ModelAndView("welcome", "message", message);
- }
- }
Check out the Video:
Comments
Post a Comment