<web-app>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
Now, in your /WEB-INF folder, create a file springmvc-servlet.xml to declare how to wire the MVC, like this:
Note that the name of the file is based on the Servlet name in web.xml (springmvc).
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean name="/register.do" class="org.confucius.HelloWorldController"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
Here we are directing all the /register.do requests to the HelloWorldCOntroller.
All Views returned by the controllers will be directed to the /jsp/
In your /src/org/confucius folder, create a class HelloWorldController.java, like this:
package org.confucius;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class HelloWorldController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String aMessage = "Welcome to Spring MVC, " + firstName + " " + lastName + "!";
ModelAndView modelAndView = new ModelAndView("hello_world");
modelAndView.addObject("message", aMessage);
return modelAndView;
}
}
We get the first and last names from the request, and create a message from it.
We create a view "hello_world" and pass it the message.
Note that Spring MVC will redirect to the view /jsp/hello_world.jsp - based on our prefix and suffix configuration in springmvc-servlet.xml.
In your /jsp folder, create a file hello_world.jsp, like this:
<html>
<body>
<p>${message}</p>
</body>
</html>
Build and deploy HelloWorld.war, then point your browser to:
http://localhost:8080/HelloWorld/jsp/registerForm.jsp
to see Spring MVC in action.
No comments:
Post a Comment