SpringMVC+Spring+Mybatis整合應用(1)

以用戶管理系統的開發爲例,詳細介紹SpringMVC+Spring+Mybatis的整合,並在編寫controller的過程當中記錄SpringMVC中的一些高級應用(會特別標示)html

1. 項目整合搭建過程

    1. 項目需求:主要實現簡單的用戶登陸註冊,以及修改自身信息功能,額外擴展一個用戶管理系統,能夠查看全部用戶以及刪除用戶前端

    2. 搭建工程:建立Maven工程java

  • 首先準備環境,mysql數據庫、Spring的相關jar包、mybatis相關jar包,暫時只須要下圖中的這些jar包,後面會逐步添加相關功能所需的jar包
  • 整合SpringMVC+Spring+Mybatis,整合思路以下
    • 第一步:整合dao層

               mybatis和spring整合,經過spring管理mapper接口。mysql

               使用mapper的掃描器自動掃描mapper接口在spring中進行註冊。git

    • 第二步:整合service層github

               經過spring管理 service接口。web

               使用配置方式將service接口配置在spring配置文件中。spring

               實現事務控制。sql

    • 第三步:整合springmvc因爲springmvc是spring的模塊,不須要整合。數據庫

  • 整合dao層

    • 編寫mybatis的配置文件,sqlmapconfig.xml

      <?xml version="1.0" encoding="UTF-8"?>  
      <!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" 
      	"http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
      <configuration>
      <!-- 配置分頁插件,dialect指定使用的數據庫類型	 -->
       	<plugins>
      		<plugin interceptor="com.github.pagehelper.PageHelper">
      			<property name="dialect" value="mysql"/>
      		</plugin>
      	</plugins>
      </configuration>

       

    • 編寫applicationContext_dao.xml,將mybatis和spring進行整合:配置數據源、SqlSessionFactory、mapper掃描器
      <?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:jdbc="http://www.springframework.org/schema/jdbc"  
      	xmlns:jee="http://www.springframework.org/schema/jee" 
      	xmlns:tx="http://www.springframework.org/schema/tx"
      	xmlns:aop="http://www.springframework.org/schema/aop" 
      	xmlns:mvc="http://www.springframework.org/schema/mvc"
      	xmlns:util="http://www.springframework.org/schema/util"
      	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
      	xsi:schemaLocation="
      		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
      		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
      		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
      		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
      		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
      	
      	<!-- mybatis配置 -->
      	<context:property-placeholder location="classpath:db.properties"/>
      	<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
      		<property name="driverClassName" value="${jdbc.driver}"></property>
      		<property name="url" value="${jdbc.url}"></property>
      		<property name="password" value="${jdbc.password}"></property>
      		<property name="username" value="${jdbc.name}"></property>
      	</bean>
      	<bean id="ssf" class="org.mybatis.spring.SqlSessionFactoryBean">
      		<property name="dataSource" ref="datasource"></property>
      		<property name="configLocation" value="classpath:conf/SqlMapConfig.xml"></property>
      	</bean>
      	<bean id="mfc" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
      		<property name="basePackage" value="user_manage.mapper"></property>
      		<property name="sqlSessionFactoryBeanName" value="ssf"></property>
      	</bean>
      
      </beans>

       

    • 逆向工程生成po類及mapper:對於單表查詢使用mybatis逆向工程生成的mapper接口和對於的映射文件足夠使用,也能夠本身添加映射文件
      import java.util.List;
      import org.apache.ibatis.annotations.Param;
      import user_manage.pojo.User;
      import user_manage.pojo.UserExample;
      
      public interface UserMapper {
          long countByExample(UserExample example);
      
          int deleteByExample(UserExample example);
      
          int deleteByPrimaryKey(Integer userAccount);
      
          int insert(User record);
      
          int insertSelective(User record);
      
          List<User> selectByExample(UserExample example);
      
          User selectByPrimaryKey(Integer userAccount);
      
          int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);
      
          int updateByExample(@Param("record") User record, @Param("example") UserExample example);
      
          int updateByPrimaryKeySelective(User record);
      
          int updateByPrimaryKey(User record);
      }

       

  • 整合service層:service層即業務層,在這裏實現主要的處理邏輯代碼
    • 編寫service層接口,以及接口實現類
      import java.util.List;
      
      import user_manage.pojo.User;
      
      public interface UserService {
      	public void insertUser(User user);
      	public void deleteUser(int user_account);
      	public List<User> findUserList(int pageNumber,int rows);
      	public void updateUser(User user);
      }

       

    • 將接口實現類掃描進Spring容器中,經過Spring進行管理,並建立applicationContext-service.xml,文件中配置掃描service。
      <?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:jdbc="http://www.springframework.org/schema/jdbc"  
      	xmlns:jee="http://www.springframework.org/schema/jee" 
      	xmlns:tx="http://www.springframework.org/schema/tx"
      	xmlns:aop="http://www.springframework.org/schema/aop" 
      	xmlns:mvc="http://www.springframework.org/schema/mvc"
      	xmlns:util="http://www.springframework.org/schema/util"
      	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
      	xsi:schemaLocation="
      		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
      		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
      		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
      		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
      		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
      	
      	<context:component-scan base-package="user_manage.service"></context:component-scan>
      </beans>

       

    • 配置開啓事務管理:編寫applicationContext_tx.xml,對service層中的全部方法開啓事務管理

      <?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:jdbc="http://www.springframework.org/schema/jdbc"  
      	xmlns:jee="http://www.springframework.org/schema/jee" 
      	xmlns:tx="http://www.springframework.org/schema/tx"
      	xmlns:aop="http://www.springframework.org/schema/aop" 
      	xmlns:mvc="http://www.springframework.org/schema/mvc"
      	xmlns:util="http://www.springframework.org/schema/util"
      	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
      	xsi:schemaLocation="
      		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
      		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
      		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
      		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
      		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
      	
      	
      	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      		<property name="dataSource" ref="datasource"></property>
      	</bean>
      	<tx:advice id="txAdvice" transaction-manager="transactionManager">
      		<tx:attributes>
      		<!-- 傳播行爲 -->
      			<tx:method name="save*" propagation="REQUIRED"/>
      			<tx:method name="insert*" propagation="REQUIRED"/>
      			<tx:method name="add*" propagation="REQUIRED"/>
      			<tx:method name="update*" propagation="REQUIRED"/>
      			<tx:method name="delete*" propagation="REQUIRED"/>
      			<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
      			<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
      			<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
      		</tx:attributes>
      	</tx:advice>
      	
      	<!-- AOP配置 -->
      	<aop:config>
      		<aop:advisor advice-ref="txAdvice" pointcut="execution(* user_manage.service.*.*(..))"/>
      	</aop:config>
      </beans>
  • 整合Controller層,編寫SpringMVC配置文件:
    • 建立springmvc.xml文件,配置處理器映射器、適配器和視圖解析器,並配置掃描全部的controller類
      <?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:jdbc="http://www.springframework.org/schema/jdbc"  
      	xmlns:jee="http://www.springframework.org/schema/jee" 
      	xmlns:tx="http://www.springframework.org/schema/tx"
      	xmlns:aop="http://www.springframework.org/schema/aop" 
      	xmlns:mvc="http://www.springframework.org/schema/mvc"
      	xmlns:util="http://www.springframework.org/schema/util"
      	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
      	xsi:schemaLocation="
      		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
      		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
      		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
      		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
      		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
      	
      	<context:component-scan base-package="user_manage.controller"></context:component-scan>
      	<mvc:annotation-driven></mvc:annotation-driven>
      	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      		<property name="prefix" value="/WEB-INF/jsp/"></property>
      		<property name="suffix" value=".jsp"></property>
      	</bean>
      <!--該配置用於接收上傳的文件-->
      	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
      		<property name="maxUploadSize">
      			<value>1048576</value>
      		</property>
      		<property name="defaultEncoding">
      			<value>utf-8</value>
      		</property>
      	</bean>
      <!--該配置用於處理RESTful風格路徑所引發的訪問靜態資源路徑錯誤問題-->
      	<mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>
      	<mvc:resources location="/WEB-INF/html/" mapping="/html/**"/>
      </beans>
    • 編寫Controller類

    • 編寫jsp

    • 加載spring容器:在web.xml中,將mapper、service、controller層的配置文件加載到spring容器中。而且配置前端控制器。
      <?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"
      	id="WebApp_ID" version="3.1">
      	<display-name>user_manage</display-name>
      	<!-- 經過 controller、service、dao三層的配置文件加載spring容器,這裏是spring應用上下文-->
      	<context-param>
      		<param-name>contextConfigLocation</param-name>
      <!-- *表示通配符,以通配符的方式匹配加載配置文件-->
      		<param-value>classpath:conf/applicationContext_*.xml</param-value>
      	</context-param>
      	<listener>
      		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      	</listener>
      	
      	<!-- RESTful風格的路徑配置 -->
      	<servlet>
      		<servlet-name>RESTful</servlet-name>
      		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      		<!--SpringMVC加載的配置文件,這裏是springweb應用上下文 -->
      		<init-param>
      			<param-name>contextConfigLocation</param-name>
      			<param-value>classpath:conf/springMVC.xml</param-value>
      		</init-param>
      		<load-on-startup>1</load-on-startup>
      	</servlet>
      	<servlet-mapping>
      		<servlet-name>RESTful</servlet-name>
      		<url-pattern>/</url-pattern>
      	</servlet-mapping>
      	<!-- 以.do結尾的路徑也會接收 -->
      	<servlet>
      		<servlet-name>spring</servlet-name>
      		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      		<!-- 配置SpringMVC加載的配置文件 -->
      		<init-param>
      			<param-name>contextConfigLocation</param-name>
      			<param-value>classpath:conf/springMVC.xml</param-value>
      		</init-param>
      		<load-on-startup>1</load-on-startup>
      	</servlet>
      	<servlet-mapping>
      		<servlet-name>spring</servlet-name>
      		<url-pattern>*.do</url-pattern>
      	</servlet-mapping>
      
      	<!-- post請求編碼過濾器,將post中的請求參數統一轉爲utf-8編碼,/*表示攔截全部路徑請求 -->
      	<filter>
      		<filter-name>postEncode</filter-name>
      		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
      		<init-param>
      			<param-name>encoding</param-name>
      			<param-value>utf-8</param-value>
      		</init-param>
      	</filter>
      	<filter-mapping>
      		<filter-name>postEncode</filter-name>
      		<url-pattern>/*</url-pattern>
      	</filter-mapping>
      </web-app>

       

  • 源碼可在個人github上下載:user_manage

2. 用戶註冊功能開發

    1. 操做流程:首先進入註冊頁面,而後填寫註冊所需的數據,而後點擊註冊,發送請求

    2. 開發Mapper:

<insert id="insertSelective" parameterType="user_manage.pojo.User">
  <!-- 將自增主鍵生成的結果回寫到傳入的user_manage.pojo.User對象中 -->
  	<selectKey keyProperty="userAccount" keyColumn="user_account" order="AFTER" resultType="int">
  		select last_insert_id()
  	</selectKey>
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="userAccount != null">user_account,</if>
      <if test="userName != null">user_name,</if>
      <if test="userPassword != null">user_password,</if>
      <if test="userAge != null">user_age,</if>
      <if test="userAddress != null">user_address,</if>
      <if test="userTelephone != null">user_telephone,</if>
      <if test="userImage != null">user_image,</if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="userAccount != null">#{userAccount,jdbcType=INTEGER},</if>
      <if test="userName != null">#{userName,jdbcType=VARCHAR},</if>
      <if test="userPassword != null">#{userPassword,jdbcType=VARCHAR},</if>
      <if test="userAge != null">#{userAge,jdbcType=INTEGER},</if>
      <if test="userAddress != null">#{userAddress,jdbcType=VARCHAR}, </if>
      <if test="userTelephone != null">#{userTelephone,jdbcType=CHAR},</if>
      <if test="userImage != null">#{userImage,jdbcType=VARCHAR},</if>
    </trim>
  </insert>

    3. 開發service:實現insertUser方法

public void insertUser(User user) {
		userMapper.insertSelective(user);
	}

4. 開發Controller:經過該開發瞭解@RequestMapping註解的部分特性、controller方法的返回值、參數綁定

  • 關於@RequestMapping註解的部分特性:
    • url映射:定義controller類中方法對應的url,進行處理器映射使用。
    • 窄化請求映射路徑:若是controller類中的每一個方法都在同一級請求路徑之下(根路徑),那麼就能夠將根路徑寫在controller上,子路徑寫在方法上,最後匹配的路徑就是根路徑+子路徑,這樣作的好處就是若是controller中的方法不少,就不用重複的去相同的路徑部分,減小代碼量
      import org.springframework.stereotype.Controller;
      import org.springframework.web.bind.annotation.PathVariable;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.servlet.ModelAndView;
      /**
       * @ClassName:PageController
       * @Description:頁面跳轉,主要請求路徑爲/page/regist.do,不寫.do是由於在前端控制器中配置掃描以.do結尾的請求路徑
       * 因此在RequestMapping中就不須要寫.do
       */
      @Controller
      @RequestMapping("/page")
      public class PageController {
      	@RequestMapping("/regist")
      	public ModelAndView toRegist(){
      		ModelAndView mv=new ModelAndView();
      		mv.setViewName("regist");
      		return mv;
      	}	
      }

       

    • 限制http請求方法:出於安全性考慮,對http的請求方法限制。若是限制只接受post方式的請求,但進行get請求,則會報錯
      //限制只接受post和get方式的請求
      	@RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST})
  • 關於Controller方法的返回值:
    • 返回ModelAndView:定義ModelAndView,將model和view分別進行設置,返回給前端控制器進行渲染和處理。
      @RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST})
      	public ModelAndView toRegist(){
      		ModelAndView mv=new ModelAndView();
      		mv.setViewName("regist");
      		return mv;
      	}

       

    • 返回String:若是controller方法返回string,有多重含義
      • 表示返回邏輯視圖名,所寫值要考慮視圖解析器中是否配置了前綴和後綴。真正視圖(jsp路徑)=前綴+邏輯視圖名+後綴
        //若是返回的String表示邏輯視圖名,那麼,只須要在方法的形參中添加一個Model類型的參數,
        	//就會自動將Model對象和邏輯視圖名錶明的邏輯視圖傳給前端控制器進行處理,至關於返回ModelAndView
        	@RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST})
        	public String toRegist(Model model){
        		model.addAttribute("key", "value");
        		return "regist";
        	}

         

      • redirect重定向:redirect重定向特色就是瀏覽器地址欄中的url會變化。修改提交的request數據沒法傳到重定向的地址。由於重定向後從新進行request(request沒法共享)

        @Controller
        @RequestMapping("/page")
        public class PageController {
        //若是請求路徑爲/page,那麼主動重定向跳轉至註冊頁面
        	@RequestMapping("/")
        	public String toPage(){
        		return "redirect:regist.do";
        	}
        	@RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST})
        	public String toRegist(Model model){
        		model.addAttribute("key", "value");
        		return "regist";
        	}	
        }
      • forward頁面轉發:經過forward進行頁面轉發,瀏覽器地址欄url不變,request能夠共享。

        @Controller
        @RequestMapping("/page")
        public class PageController {
        //若是請求路徑爲/page,那麼主動重定向跳轉至註冊頁面
        	@RequestMapping("/")
        	public String toPage(){
        		return "forward:regist.do";
        	}
        	@RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST})
        	public String toRegist(Model model){
        		model.addAttribute("key", "value");
        		return "regist";
        	}	
        }

         

    • 若是返回void:在controller方法形參上能夠定義request和response,使用request或response指定響應結果
      • 經過request進行頁面轉發,並傳遞參數
        @RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST})
        	public void toRegist(HttpServletRequest req,HttpServletResponse res){
        		req.setAttribute("key", "value");
        		try {
        			req.getRequestDispatcher("path").forward(req, res);
        		} catch (ServletException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		} catch (IOException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
        	}

         

      • 經過response頁面重定向,沒法傳遞參數,response.sendRedirect("url")
      • 也能夠經過response指定響應結果,例如html等,響應json數據以下:

        response.setCharacterEncoding("utf-8");

        response.setContentType("application/json;charset=utf-8");

        response.getWriter().write("json串");

  • 參數綁定:從客戶端發送的請求中包括key/value數據,通過參數綁定,將key/value數據綁定到controller方法的形參上。
    • 參數綁定默認支持的類型:直接在controller方法形參中定義這些類型的對象,就可使用這些對象。由於在參數綁定過程當中,控制器適配器若是遇到這些類型直接進行參數綁定。類型有HttpServletRequest、HttpServletResponse、HttpSession、Model/ModelMap(model是一個接口,modelMap是一個接口實現 ,能夠將model數據填充到request域)
    • 參數綁定默認支持的類型還包括Java中的簡單類型(經常使用有String和8個基本類型):經過在形參前添加註解@RequestParam對簡單類型的參數進行綁定,若是不使用@RequestParam,要求request傳入參數名稱(名稱實際是key的值,request傳入參數都是key/value,並且value都是字符串格式,因此須要轉換器converters將字符串轉爲形參類型)和controller方法的形參名稱一致,方可綁定成功(此外還要必須保證value值可以轉換爲形參類型,不然就會出現錯誤)。若是使用@RequestParam,不用限制request傳入參數名稱和controller方法的形參名稱一致。經過required屬性指定參數是否必需要傳入,若是設置爲true,經過defaultValue指定若是傳入的值爲空,則設置一個默認值,value就表示指定參數中的key名稱
      @RequestMapping(value="/regist",method={RequestMethod.GET,RequestMethod.POST})
      	public String toRegist(Model model,@RequestParam(value="id",required=true,defaultValue="1") int id){
      		model.addAttribute("key", "value");
      		return "regist";
      	}

       

    • 綁定pojo參數類型:若是形參類型爲pojo類型,那麼就必須知足一個規範,請求中傳來的每個key/value數據,每一個數據的key都要與controller的pojo形參中的屬性名稱一致,那麼就會將數據綁定到pojo對應的屬性,若是不一致,那麼請求中的數據就沒法綁定到pojo對象的屬性中
    • 自定義一個converters轉換器:將請求中的日期字符串轉換爲日期類型數據,這樣就能夠實現日期類型的參數綁定,若是綁定爲pojo類型,即使pojo類型中包括非簡單類型的屬性,也須要對該屬性的類型定義一個轉換器,這樣才能完成對pojo類的參數綁定。以實現java.util.Date的轉換器爲例
      • 首先定義converters轉換器類
        import java.text.ParseException;
        import java.text.SimpleDateFormat;
        import java.util.Date;
        import org.springframework.core.convert.converter.Converter;
        //自定義轉換器必須實現org.springframework.core.convert.converter.Converter接口
        public class DateConvertor implements Converter<String,Date>{
        	@Override
        	public Date convert(String source) {
        		SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd HH:mm:ss");
        		Date date=null;
        		try {
        			date = sdf.parse(source);
        		} catch (ParseException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
        		return date;
        	}
        }

         

      • 將Converter配置裝載進入SpringMVC的轉換器集合中
        <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
        	<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        		<property name="converters">
        			<list>
        				<bean class="user_manage.convertor.DateConvertor"></bean>
        			</list>
        		</property>
        	</bean>
相關文章
相關標籤/搜索