1、步骤:
①建立对应的bean和dao
②建立form表单
③建立handler(①handler的参数需要更表单控件name值一样 ②要用@RequestParam修饰方法的参数)
④建立converter类,且继承org.springframework.core.convert.converter.Converter
⑤实现org.springframework.core.convert.converter.Converter的方法(添加操作数据需要的逻辑,记得return对应的Bean)
⑥到Spring配置文件中配置conversionService,而且使用ref标签指定转换器类名
2、作用:
配置之后就能对指定的Bean的类型转换起到统一作用,凡是有关该bean的类型转换都会调用对应的类型转换类,这样能简化类型转换方面的代码
3、注意事项:
①bean和dao类都需要使用@Repository修饰
②handler类里面需要用@Autowired修饰dao类
③在springmvc配置文件中配置”conversionService”
4、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>SpringMVC_8_Converter</display-name>
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<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>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
5、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: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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<!-- 配置自动扫描包 -->
<context:component-scan base-package="com.test.springmvc"></context:component-scan>
<!-- 配置视图解析器,把handler返回值解析为实际视图 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<mvc:annotation-driven conversion-service="conversionService" />
<!--
<bean id="conversionSe