老黑讲Java之Spring核心技术SpringMVC
1、MVC模式 Mode(模型):主要负责业务逻辑,包括业务数据和业务处理逻辑。例如DAO、实体类、Servlet类属于模型层。 View(视图):主要负责显示页面,并与用户交互,“偷摸”采集用户数据。如JSP页面属于视图层。 Controller(控制器):管理Mode和View层,处理之间的业务关系,构建Mode和View的桥梁,控制整个流程。

2、Spring Web MVC的五大核心组件 Spring框架为了实现MVC模式,提供了实现组件: 1、DispatcherServlet(也称前端控制器); 2、HandlerMapping(处理请求与Controller类的映射关系); 3、Controller(处理器); 4、ViewResolver(视图解析器,根据视图名与JSP页面建立映射关系); 5、ModelAndView(封装数据与视图名)。这五大组件实现了MVC模式,掌握这五点,更好的理解用注解表达的MVC模式。
3、Spring Web MVC的组件工作流程图

4、搭建Spring Web MVC环境 1、用maven导入spring-webmvc所用的jar包; 2、添加springmvc的配置文件springmvc.xml; 3、web.xml配置DispatcherServlet; 4、写Controller组件; 5、写JSP页面; 6、在springmvc.xml中添加HandlerMapping和ViewResolver配置。
5、导入jar包 1、创建maven project项目,命名为springmvc 2、使用maven工具,下载spring-webmvc所有的jar包。

6、添加springmvc的配置文件springmvc.xml在src/main/resources下新建springmvc.xml文件,内容如下:<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"></beans>

7、web.xml配置DispatcherServlet<servlet> <servlet-name>springmvc</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>

8、编写Controller(处理器)public HelloController implements Controller{ public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response){ System.out.println("HelloWorld!"); return new ModelAndView("hello"); }}

9、写JSP页面<%@page pageEncoding='UTF-8' contentType="text/html;charset=UTF-8"%><html> <body> <h1>HelloWorld!</h1> </body></html>

10、在springmvc.xml中添加HandlerMapping和ViewResolver配置<!-- 配置HandlerMapping --> <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/hello.do">helloController</prop> </props> </property> </bean> <bean id="helloController" class="controller.HelloController"/> <!-- 配置视图解析器 --> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean>
