SpringMVC 架构
-
HandleMapping:SpringMVC提供了不同的处理器映射器分别处理注解、配置文件、实现接口方式的映射方式。
-
Handler:后端控制器。
-
ViewResolver:视图解析器,View Resolver首先根据逻辑视图名解析成物理视图名即具体的页面地址,再生成View视图对象。
处理器映射器、处理器适配器、视图解析器称为springmvc的三大组件。
SpringMVC简单配置
- 在配置文件中配置注解扫描,扫描添加了Controller的类
- 在web.xml中配置SpringMVC前端控制器DispatcherServlet,该类执行的时候会加载配置文件。
注解映射器和适配器
-
注解映射器会把添加了@ResquestMapping的方法名和@ResquestMapping中提供的URL进行映射匹配,匹配成功,返回HandleMethod对象给前端控制器。
<!-- 配置处理器映射器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" /> <!-- 配置处理器适配器 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" /> -
注解驱动:可以使用
<mvc:annotation-driven/>代替前面两个类的配置。
视图解析器
InternalResourceViewResolver 支持JSP视图解析。
Spring、Mybatis整合
Dao
- SqlMapConfig,xml :Mybatis全局配置文件,整合后可以在里面配置别名
- applicationContext-dao.xml
- 数据源
- SQLSessionFactory 对象,Mybatis整合包下面的。
- 配置mapper扫描器MapperScannerConfigurer。
Service
- 配置扫描
- 配置事务管理器。
Controller
Springmvc.xml
-
包扫描器,扫描@Controller注解的类。
-
配置注解驱动(处理器映射器和处理器适配器)
-
配置视图解析器
Web.xml文件:
1、配置spring(通过contextLoadListener 监听context上下文的创建,读取contextConfigLocation上下文参数,加载指定的配置文件)
2、配置SpringMVC前端控制器,它会读取SpringMVC.xml配置文件(需要通过标签进行指定>)。
参数绑定
-
不管是Model还是ModelAndView,其本质都是使用Request对象向jsp传递数据。、
-
ModelMap:使用Model和ModelMap的效果一样,如果直接使用Model,springmvc会实例化ModelMap。
-
推荐使用包装数据类型,因为包装数据类型可以为null。
-
pojo绑定:表单参数和pojo属性对应可以实现绑定。
-
包装pojo绑定:表单参数为 pojo.属性。
自定义参数绑定
前端控制器接收到请求后,找到注解形式的处理器适配器,对RequestMapping标记的方法进行适配,并对方法中的**形参进行参数绑定。**可以在springmvc处理器适配器上自定义转换器Converter进行参数绑定。
-
编写转化器类
-
<!-- 配置注解驱动 --> <!-- 如果配置此标签,可以不用配置(处理器映射器和处理器适配器)... --> <mvc:annotation-driven conversion-service="conversionService" /> <!-- 转换器配置 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="cn.itcast.springmvc.converter.DateConverter" /> </set> </property> </bean>
Post乱码
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 设置编码参是UTF8 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Get请求乱码
修改tomcat配置文件添加编码与工程编码一致,如下:
<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/
或者对request参数重新编码
String userName new
String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")