SpringMVC
Spring Web MVC需要使用SpringIOC功能
用于开发MVC结构的web程序。
1.MVC思想
将程序组件分为模型,视图,控制器三部分
SpringMVC工作流程:
- 浏览器发出一个Http请求
- 请求首先进入DispatcherServlet主控制器
- 主控制器调用HandlerMapping组件根据请求找映射的Controller处理
- 执行Controller处理方法,将返回结果给ViewResolver组件
- ViewResolver组件根据Controller返回结果定位视图JSP,将模型数据传递给JSP
- 由JSP生成响应结果,给浏览器输出
注意:
dispatcherServlet:接受指定的请求,类似一个大的主控制器(大boss)
HanlerMapping:根据不同请求类型找寻Controller
ViewResolver:寻找视图,生成详细信息
2.SpringMVC编写程序的具体流程
/hello.do
--->DispatcherServlet(配置)
--->HandlerMapping(配置)
--->HelloController(编写+配置)
--->ViewResolver(配置)
--->/WEB-INF/hello.jsp(编写)
3.Spring Web MVC简单程序实现
实例:一个SpringMVC的helloword案例
(1)搭建Spring Web MVC开发环境,引入IOC,webmvc开发包,在src下添加applicationContext.xml
(2)编写HelloController实现
package com.controller; 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 HelloController implements Controller{ public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav=new ModelAndView(); mav.setViewName("hello");//设置视图名字 mav.getModel().put("msg", "模型数据");//等价于request.setAttribute("msg","模型数据"); return mav; } }
(3)在web.xml配置DispatcherServlet(配置)
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <servlet> <servlet-name>exam</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <!-- 启动服务器的时候,优先级是1 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>exam</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
(4)在applicationContext.xml中配置相关组件
A.定义Handlermapping(配置)
<!-- 配置handlermapping --> <bean id="handlermapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <!-- 指定请求和controller对应关系 --> <property name="mappings"> <props> <prop key="/hello.do">helloController</prop> <prop key="/login.do">loginController</prop> </props> </property> </bean>
B.Controller配置、
<!-- 配置Controller --> <bean id="helloController" class="com.controller.HelloController"> </bean> <bean id="loginController" class="com.controller.LoginController"></bean>
C.配置ViewResolver
<!-- 配置ViewResolver --> <bean id="viewresolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/"></property> <property name="suffix" value=".jsp"></property> </bean>