以前公司用的是struts,换了家单位,要用spring的MVC框架,赶紧学习一下。
1 先看web.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>test</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
和struts一样,spring的MVC框架的核心也是一个Servlet,默认会加载/WEB-/INF/${servlet-name}-servlet.xml,也可以加入参数修改
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/myServlet.xml
</param-value>
</init-param>
2 dispatcher-servlet.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans default-autowire="byName" default-lazy-init="true">
<bean id="simpleUrlHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/helloWorld.do">helloWorldController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
<property name="contentType">
<value>text/html;charset=UTF8</value>
</property>
</bean>
<bean id="helloWorldController" class="action.HelloWorldController"></bean>
</beans>
DispatchServlet接收到请求后会交给SimpleUrlHandlerMapping控制,由哪个Controller处理,Controller类似于Struts的Action,例子中url为/helloWorld.do的请求由helloWorldController这个bean来处理。
3 java文件HelloWorldController.java
实现了Controller接口
public class HelloWorldController implements Controller {
public ModelAndView handleRequest(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
ModelAndView mv = new ModelAndView();
mv.setViewName("helloWorld");
mv.addObject("name", "linsong");
return mv;
}
}
返回一个ModelAndView对象,ViewName为展现层名字,根据viewResolver配置取得jsp。
4 helloWorld.jsp略
至此,一个简单的spring MVC的例子完成。
接下来深入了解spring MVC的各个组件Controller,HandlerMapping,ViewResolver