Spring MVC配置使用入門

SpringMVC 應用開發html

1、Spring MVC介紹java

Spring MVC屬於SpringFrameWork的後續產品,已經融合在SpringWeb Flow裏面。Spring 框架提供了構建 Web 應用程序的全功能 MVC 模塊。jquery

 

2、在項目中引入Spring MVCweb

1Spring配置文件類別spring

若是你的項目是使用Spring框架進行構建開發的,並使用了Spring註解,那麼咱們在路徑…/WEB-INF下的配置文件會包含:web.xmlapplicationContext.xml,其中web.xml文件配置了Spring的字符集過濾器和默認的歡迎頁面;applicationContext.xml文件裏配置了須要掃描註解的包路徑以及jdbcTemplateBean之類的內容。apache

2、使用SpringMVC時需新增的配置文件json

若是要引入SpringMVC,咱們須要在web.xml裏面添加請求轉發控制器DispatcherServlet,用於接收前段頁面請求,將業務處理邏輯跳轉到指定的對象方法。另外,還須要添加一個配置文件,默認名稱是controller-servlet.xml,其中包括內部資源視圖跳轉的配置、待掃描註解的包路徑配置、啓動Spring MVC的註解功能以完成請求和註解POJO映射的配置、字符串處理配置等。spring-mvc

詳細的配置文件以及說明會在文檔最後給出。session

3web.xml重點配置內容mvc

1)字符串過濾器

<filter>

    <description>字符集過濾器</description>

    <filter-name>encodingFilter</filter-name>

    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

    <init-param>

      <description>字符集編碼</description>

      <param-name>encoding</param-name>

      <param-value>UTF-8</param-value>

    </init-param>

  </filter>

  <filter-mapping>

    <filter-name>encodingFilter</filter-name>

    <url-pattern>/*</url-pattern>

  </filter-mapping>

 

2DispatcherServlet配置

<!-- Controller 配置,相似於struts2中的action -->

  <servlet>

    <servlet-name>controller</servlet-name>

    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <load-on-startup>1</load-on-startup>

  </servlet>

  <servlet-mapping>

    <servlet-name>controller</servlet-name>

    <url-pattern>*.do</url-pattern>

  </servlet-mapping>

 

3ContextLoaderListener配置

<listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  </listener>

 

4applicationContext.xml重點配置

<!—啓用註解設置 -->   

     <context:annotation-config/>

<!--註解對象掃描設置 -->

     <context:component-scan base-package="comNaNcc.annotation"></context:component-scan>

 

5controller-servlet.xml重點配置

<!—啓用註解設置 -->   

     <context:annotation-config/>

<!--註解對象掃描設置 -->

     <context:component-scan base-package="comNaNcc.annotation.action"/>

<!--action頁面跳轉設置,設置view(視圖)文件的前綴和後綴 -->

     <bean

          class="org.springframework.web.servlet.view.InternalResourceViewResolver"

          p:prefix="/view/"p:suffix="" />

#說明:若是後綴是空,那麼在跳轉代碼邏輯裏面,須要寫完整的跳轉目標後綴,如return 「userPage/user.jsp」return 「userPage/user.html」return 「userPage/user」

<!-- 從請求和響應處讀取/編寫字符串 -->

     <bean id="stringHttpMessage"class="org.springframework.http.converter.StringHttpMessageConverter">

          <property name="supportedMediaTypes">

               <list>

                     <value>text/html;charset=UTF-8</value>

               </list>

          </property>

     </bean>

<!-- 將對象轉換成json -->

     <bean id="jsonConverter"class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>

<!-- 避免IE執行AJAX,返回JSON出現下載文件 -->

     <bean id="mappingJacksonHttpMessageConverter"

          class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">

          <property name="supportedMediaTypes">

               <list>

                     <value>text/html;charset=UTF-8</value>

                     <value>application/json</value>

               </list>

          </property>

     </bean>

 

<!-- 啓動Spring MVC的註解功能,完成請求和註解POJO的映射 -->

     <bean

          class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">

          <property name="messageConverters">

               <list>

<!--                 <refbean="mappingJacksonHttpMessageConverter" />json轉換器 -->

                     <ref bean="stringHttpMessage"/>

                     <ref bean="jsonConverter"/>

               </list>

          </property>

     </bean>

<!--攔截器配置-->

<mvc:interceptors> 

         <!-- 國際化操做攔截器若是採用基於(請求/Session/Cookie)則必需配置 -->

         <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>

     </mvc:interceptors>

3、代碼編寫

咱們設定項目默認頁面是index.jsp,並在頁面上調用業務邏輯處理的java類。

index.jsp頁面上添加代碼:

<h3>用戶信息操做:form提交add.do,傳遞表單參數</h3>

<form action="user/add.do"method="post">

姓名:<input type="text"name="userid"></input><br/>

號碼:<input type="text"name="phone"></input><br/>

生日:<input type="text"name="birth"></input><br/>

<input type="submit"value="提交"/>

</form>

 

點擊提交按鈕後,Spring容器會去尋找user類中的add.do對應的方法。所以咱們須要指定一個類的別名映射爲user,並指定其中一個方法映射是add.do

因爲在controller-servlet.xml文件中配置的註解掃描路徑是comNaNcc.annotation.action,咱們在該路徑下新增一個java文件,命名UserInfoController.java,新增方法public String add(params …){…}

而後對這個類進行註解:

 

@Controller

@RequestMapping("/user")

publicclassUserInfoController {

    

     private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    

     @RequestMapping("/add.do")

     public String add(User user , Map<String, Object> map){

          System.out.println("add finished !");

          System.out.println(user.toString());

          map.put("name", user.getUserid());

          map.put("phone", user.getPhone());

          map.put("birth", sdf.format(user.getBirth()));

          return"userinfo/user_add.jsp";

     }

須要說明的是,add()方法裏面有三個傳入參數:User,Date,Map。爲何要傳入這三個參數呢?由於SpringMVC在幫咱們作跳轉的時候,會將表單數據自動封裝給指定的對象bean。但若是對象屬性包含DateBoolean之類的類型,就沒法綁定,解決方法就是要在類中配置表單數據編輯器,好比日期編輯器CustomDateEditor等。編輯器須要用到註解@InitBinder寫法以下:

@InitBinder

     publicvoidinitBinder(ServletRequestDataBinder bin){

          CustomDateEditorcust = new CustomDateEditor(sdf,true);

          bin.registerCustomEditor(Date.class,cust);

     }

當頁面提交包含表單數據的請求時,SpringMVC會幫咱們把表單數據賦值給方法中的參數對象,前提是參數對象的屬性名與表單中的字段名一致。若是表單數據中包含日期等類型參數,須要經過參數編輯器進行解析。

而參數Map,則用於接收對象屬性值,並傳遞給跳轉的目的頁面userinfo/user_add.jsp,放到request中。頁面經過jquery獲取${paramName}獲取數據。該頁面的路徑是:

project---webContent---view---userinfo---user_add.jsp


 

說明:頁面跳轉設置,設置view(視圖)文件的前綴和後綴時,若是配置的是

     <bean

     class="org.springframework.web.servlet.view.InternalResourceViewResolver"

          p:prefix="/view/"p:suffix="" />

那麼待跳轉的視圖頁面都是放在view下面,若是在view路徑下再創建一個子類頁面路徑/userinfo,其中有user_add.jsp頁面,那麼經過return"userinfo/user_add.jsp";跳轉到該頁面中。

 

4、全部文件完整內容

1web.xml

<?xml version="1.0"encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

  <display-name>springAnnotation</display-name>

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

  <filter>

    <description>字符集過濾器</description>

    <filter-name>encodingFilter</filter-name>

    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

    <init-param>

      <description>字符集編碼</description>

      <param-name>encoding</param-name>

      <param-value>UTF-8</param-value>

    </init-param>

  </filter>

  <filter-mapping>

    <filter-name>encodingFilter</filter-name>

    <url-pattern>/*</url-pattern>

  </filter-mapping>

  <listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  </listener>

  <!-- Controller 配置,相似於struts2中的action -->

  <servlet>

    <servlet-name>controller</servlet-name>

    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <load-on-startup>1</load-on-startup>

  </servlet>

  <servlet-mapping>

    <servlet-name>controller</servlet-name>

    <url-pattern>*.do</url-pattern>

  </servlet-mapping>

  <session-config>

      <session-timeout>3000</session-timeout>

     </session-config>

</web-app>

 

2applicationContext.xml

<?xml version="1.0"encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

     xmlns:context="http://www.springframework.org/schema/context"

     xmlns:aop="http://www.springframework.org/schema/aop"

     xmlns:tx="http://www.springframework.org/schema/tx"

     xmlns:task="http://www.springframework.org/schema/task"

     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

     xsi:schemaLocation="http://www.springframework.org/schema/beans

   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

   http://www.springframework.org/schema/context 

    http://www.springframework.org/schema/context/spring-context-3.0.xsd 

   http://www.springframework.org/schema/aop

   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

   http://www.springframework.org/schema/tx 

   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

   http://www.springframework.org/schema/task 

   http://www.springframework.org/schema/task/spring-task-3.0.xsd ">

<!--Spring 配置 -->

     <!--註解設置 -->

     <context:annotation-config/>

     <!--註解對象掃描設置 -->

     <context:component-scan base-package="com.cmcc.annotation"></context:component-scan>

     <!--properties文件掃描地址 -->

     <context:property-placeholder location="classpath:conf.properties"/>

     <bean id="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">

          <property name="dataSource"ref="dataSource"></property>

     </bean>

     <bean id="dataSource"class="org.apache.commons.dbcp.BasicDataSource"

          destroy-method="close">

          <property name="driverClassName"value="${jdbc.driver}" />

          <property name="url"value="${jdbc.url}" />

          <property name="username"value="${jdbc.username}" />

          <property name="password"value="${jdbc.password}" />

     </bean>

</beans>

 

3controller-servlet.xml

<?xml version="1.0"encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

     xmlns:context="http://www.springframework.org/schema/context"

     xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"

     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"

     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.0.xsd

   http://www.springframework.org/schema/context

   http://www.springframework.org/schema/context/spring-context-3.0.xsd

   http://www.springframework.org/schema/aop

   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

   http://www.springframework.org/schema/tx

   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

   http://www.springframework.org/schema/mvc

   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">

<!-- Spring mvc配置 -->

     <!--註解對象掃描設置 -->

     <context:component-scan base-package="com.cmcc.annotation.action"/>

     <!--註解設置 -->

     <mvc:annotation-driven />

     <!--action頁面跳轉設置,設置view(視圖)文件的前綴和後綴 -->

     <bean

          class="org.springframework.web.servlet.view.InternalResourceViewResolver"

          p:prefix="/view/" p:suffix=""/>

<!-- 從請求和響應處讀取/編寫字符串 -->

     <bean id="stringHttpMessage"class="org.springframework.http.converter.StringHttpMessageConverter">

          <property name="supportedMediaTypes">

               <list>

                     <value>text/html;charset=UTF-8</value>

               </list>

          </property>

     </bean>

<!-- 將對象轉換成json -->

     <bean id="jsonConverter"class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>

     <!-- 避免IE執行AJAX,返回JSON出現下載文件 -->

     <bean id="mappingJacksonHttpMessageConverter"

          class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">

          <property name="supportedMediaTypes">

               <list>

                     <value>text/html;charset=UTF-8</value>

                     <value>application/json</value>

               </list>

          </property>

     </bean>

     <!-- 啓動Spring MVC的註解功能,完成請求和註解POJO的映射 -->

     <bean

          class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">

          <property name="messageConverters">

               <list>

<!--                 <refbean="mappingJacksonHttpMessageConverter" />json轉換器 -->

                     <ref bean="stringHttpMessage"/>

                     <ref bean="jsonConverter"/>

               </list>

          </property>

     </bean>

     <mvc:interceptors> 

         <!-- 國際化操做攔截器若是採用基於(請求/Session/Cookie)則必需配置 -->

         <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/> 

         <!-- 若是不定義 mvc:mapping path 將攔截全部的URL請求 -->

<!--      <beanclass="comNaNcc.ercs.eec.filter.AuthInterceptor"></bean>-->

     </mvc:interceptors>

     <!-- 上傳文件解析器 -->

    <bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

       <property name="maxUploadSize"value="100000000"/>

    </bean>

</beans>

 

4index.jsp

<%@ page language="java" contentType="text/html;charset=UTF-8"

    pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE htmlPUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type"content="text/html; charset=UTF-8">

<title>Index</title>

<script src="<%=basePath%>js/jquery-1.7.2.min.js"></script>

</head>

<body>

<h3>用戶信息操做:form提交add.do,傳遞表單參數</h3>

<form action="user/add.do"method="post">

姓名:<input type="text"name="userid"></input><br/>

號碼:<input type="text"name="phone"></input><br/>

生日:<input type="text"name="birth"></input><br/>

<input type="submit"value="提交"/>

</form>

<br></br>

</body>

</html>

 

5user_add.jsp

<%@ page language="java" contentType="text/html;charset=UTF-8"

    pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE htmlPUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type"content="text/html; charset=UTF-8">

<title>添加用戶</title>

<script src="<%=basePath%>js/jquery-1.7.2.min.js"></script>

</head>

<body>

<h1>完成用戶添加</h1>

${name }--${phone }--${birth}

</body>

</html>

 

 

 

下一篇會介紹SpringMVCAjax的結合使用。

相關文章
相關標籤/搜索