SpringMVC基础知识(一)

SpringMVC

SpringMVC是基于Web MVC设计模式的请求驱动类型的轻量级Web框架;

SpringMVC在Web应用中充当控制层Controller的角色

MVC模式:(Model-View-Controller):为了解决页面代码和后台代码的分离
  • 0x01.SpringMVC请求流程
  • 0x02.SpringMVC组件
  • 0x03.SpringMVC核心
  • 0x04.SpringMVC启动
  • 0x05.SpringMVC方法

0x01.SpringMVC请求流程

0x02.SpringMVC组件

  • DispatcherServlet 前端控制器-框架提供,在web.xml中配置,用于接收请求,响应结果,相当于转发器,中央处理器
  • HandlerMapping 请求处理器-框架提供,根据请求uri查找处理器(controller),可以用XML或注解来映射
  • HandlerAdapter 处理器适配器-框架提供,按照特定规则(HandlerAdapter要求的规则)去执行Handler
  • Handler 处理器- 开发,也叫后端控制器Controller
  • ViewResolver 视图解析器- 框架提供,进行视图解析,把逻辑视图名解析成真正的物理视图
  • View 视图- 开发,数据展现给用户的页面,View是一个接口,实现类支持不同的View技术(jsp、freemarker)
#spring-webmvc-4.3.5.RELEASE.jar
#/org/springframework/web/servlet/DispatcherServlet.properties 的相关配置

# Default implementation classes for DispatcherServlet's strategy interfaces.
# Used as fallback when no matching beans are found in the DispatcherServlet context.
# Not meant to be customized by application developers.

org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver

org.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolver

org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,
	org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping

org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,
	org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,
	org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter

org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver,
	org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,
	org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver

org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator

org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver

org.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager

0x03.SpringMVC核心-DispatcherServlet

DispatcherServlet

web.xml文件用来初始化配置信息

web.xml有多项标签,在其加载的过程中顺序依次为:
context-param >> listener >> fileter >> servlet

SpringMVC的启动过程:

  • 1.ContextLoaderListener初始化

实例化IoC容器,并将此容器实例注册到ServletContext中

  • 2.DispactherServlet初始化

ContextLoaderListener

ContextLoaderListener implements ServletContextListener
<!-- 配置contextConfigLocation初始化参数 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<!-- 配置ContextLoaderListerner -->
<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> 

DispactherServlet

<!-- servlet定义 -->
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 读取SpringMVC的配置文件 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<!-- 初始化容器 -->
		<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

0x04.SpringMVC的启动

  • JavaConfig
  • XML

JavaConfig

WebApplicationInitializer

public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) {

        // Load Spring web application configuration
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(AppConfig.class);

        // Create and register the DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(context);
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/app/*");
    }
}
  • web容器(tomcat)启动的时候会调用onStartup方法

Servlet 3.0以后,提出一个新的规范SPI

当项目中存在某些类(方法),需要在启动的时候被Tomcat(web容器)调用的时候
在项目的根目录需要有:META-INF/services/javax.servlet.ServletContainerInitializer

spring-web的包中

META-INF/services/javax.servlet.ServletContainerInitializer

org.springframework.web.SpringServletContainerInitializer

@HandlesTypes(WebApplicationInitializer.class)

实现WebApplicationInitializer 接口的类,都通过这个方法实现并调用onStartup方法

@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
	@Override
	public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
			throws ServletException {

		List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>();

		if (webAppInitializerClasses != null) {
			for (Class<?> waiClass : webAppInitializerClasses) {
				// Be defensive: Some servlet containers provide us with invalid classes,
				// no matter what @HandlesTypes says...
				if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
						WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
					try {
						initializers.add((WebApplicationInitializer) waiClass.newInstance());
					}
					catch (Throwable ex) {
						throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
					}
				}
			}
		}

		if (initializers.isEmpty()) {
			servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
			return;
		}

		servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
		AnnotationAwareOrderComparator.sort(initializers);
		for (WebApplicationInitializer initializer : initializers) {
			initializer.onStartup(servletContext);
		}
	}

}

0x05.SpringMVC方法

@ReuqestMapping

  • SpringMVC映射配置文件
    <!-- 扫描web相关的bean -->
    <context:component-scan base-package="com.dengshuo.tmall.controller"/>

    <!-- 开启SpringMVC注解模式 -->
    <mvc:annotation-driven/>

    <!-- 静态资源默认servlet配置 -->
    <mvc:default-servlet-handler/>

    <!-- 配置jsp 显示ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 支持上传文件 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
  • 开发步骤
(1)	引入相关依赖jar包
(2)	在web.xml中配置SpringMVC的前端控制器
①	DispatcherServlet
(3)	在springmvc.xml配置文件配置包扫描,开启Springmvc的注解驱动
①	<context:component-sacn basePackage=’cn.zj.springmvc’>
②	<mvc:annotation-driven>
(4)	新建一个普通类型
①	在类上面贴上 @Controller注解,就是SpringMVC的控制器了
(5)	在类中新建一个方法,并且在方法上面贴上一个注解
①	@RequestMapping(“url地址访问路径”)
(6)	在浏览器输入地址即可访问
  • 请求
(1)	请求方法的限定  GET/POST 
(2)	请求参数的限定 ,必须有什么参数,必须没有什么参数,参数值必须是什么,参数值必须不是什么
(3)	数据绑定(接受请求参数)
①	表单提交参数名和方法参数名相同 -最常见
②	表单提交参数名和方法参数名不相同
1)	在方法参数前面写上@RequestParam("和表单参数名相同")
③	数组类型(多值)
④	接受多个参数封装成 pojo对象
1)	必须保证表单参数名称和pojo对象属性名称相同
⑤	将接受参数封装成map集合
(4)	支持 RestFul风格
①	@PathVariables()
(5)	SpringMVC中文参数乱码的问题
①	Post方式 设置过滤器
②	Get方式 修改tomcat 配置
  • 响应
(1)	ModelAndView 共享模型数据并且设置视图地址
(2)	方法直接返回 String 使用 Model 模型对象共享
(3)	自定义页面跳转
①	redirect: 重定向
②	forward:请求转发
(4)	配置视图解析器(配置视图的前缀和后缀)
(5)	返回对象类型
(6)	返回json数据
①	Jackson+@ResponseBody

SpringMVC入门
SpringMVC基础篇

不要用狭隘的眼光看待不了解的事物,自己没有涉及到的领域不要急于否定. 每天学习一点,努力过好平凡的生活.
原文地址:https://www.cnblogs.com/GeekDanny/p/14761950.html