springMvc3.0.5搭建全程

   用了大半年的Spring MVC3.0,用着感受不錯。簡單寫一個搭建Spring MVC3.0的流程(以Spring3.0.5爲列),數據庫交互使用spring JDBC Template,附件有項目(沒有jar包)。整個項目架構以下圖所示:css

 

一、去官網下載3.0.5全部jar包,所需jar包,見附件圖片,每一個jar包得用處以下:java

org.springframework.aop- 3.0.0.RELEASE--------------------Spring的面向切面編程,提供AOP(面向切面編程)實現mysql

org.springframework.asm- 3.0.0.RELEASE--------------------Spring獨立的asm程序,相遇Spring2.5.6的時候須要asmJar 包.3.0開始提供他本身獨立的asmJarweb

org.springframework.aspects- 3.0.0.RELEASE----------------Spring提供對AspectJ框架的整合\spring

org.springframework.beans- 3.0.0.RELEASE------------------SpringIoC(依賴注入)的基礎實現sql

org.springframework.context.support- 3.0.0.RELEASE--------Spring-context的擴展支持,用於MVC方面數據庫

org.springframework.context- 3.0.0.RELEASE----------------Spring提供在基礎IoC功能上的擴展服務,此外還提供許多企業級服務的支持,如郵件服務、任務調度、JNDI定位、EJB集成、遠程訪問、緩存以及各類視圖層框架的封裝等express

org.springframework.core- 3.0.0.RELEASE-------------------Spring3.0的核心工具包編程

org.springframework.expression- 3.0.0.RELEASE-------------Spring表達式語言json

org.springframework.instrument.tomcat- 3.0.0.RELEASE------Spring3.0對Tomcat的鏈接池的集成

org.springframework.instrument- 3.0.0.RELEASE-------------Spring3.0對服務器的代理接口

org.springframework.jdbc- 3.0.0.RELEASE-------------------對JDBC的簡單封裝

org.springframework.jms- 3.0.0.RELEASE--------------------爲簡化JMS API的使用而做的簡單封裝

org.springframework.orm- 3.0.0.RELEASE--------------------整合第三方的ORM框架,如hibernate,ibatis,jdo,以及spring的JPA實現

org.springframework.oxm-3.0.0.RELEASE--------------------Spring 對Object/XMl的映射支持,可讓Java與XML之間來回切

org.springframework.test- 3.0.0.RELEASE--------------------對Junit等測試框架的簡單封裝

org.springframework.transaction- 3.0.0.RELEASE-------------爲JDBC、Hibernate、JDO、JPA等提供的一致的聲明式和編程式事務管理

org.springframework.web.portlet- 3.0.0.RELEASE-------------SpringMVC的加強

org.springframework.web.servlet- 3.0.0.RELEASE-------------對JEE6.0 Servlet3.0的支持

org.springframework.web.struts- 3.0.0.RELEASE--------------整合Struts的時候的支持

org.springframework.web- 3.0.0.RELEASE--------------------SpringWeb下的工具包



 

二、借鑑spring官網寫法,創建一個src-resources Source Folder,再新建目錄META-INF,存放springmvc-servlet.xml和jdbc-context.xml文件(事務和數據庫鏈接池的管理);以及database.properties和log4j.properties。

 

JDBC-context.xml文件:

 

Xml代碼   收藏代碼
  1. <span style="font-size: x-small;"><?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     
  4.     xmlns:aop="http://www.springframework.org/schema/aop"    
  5.     xmlns:tx="http://www.springframework.org/schema/tx"    
  6.     xmlns:context="http://www.springframework.org/schema/context"    
  7.     xsi:schemaLocation="     
  8.           http://www.springframework.org/schema/beans     
  9.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     
  10.           http://www.springframework.org/schema/tx     
  11.           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd    
  12.           http://www.springframework.org/schema/context     
  13.           http://www.springframework.org/schema/context/spring-context-3.0.xsd     
  14.           http://www.springframework.org/schema/aop     
  15.           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" default-autowire="byName">  
  16.   
  17.      <context:property-placeholder location="classpath:database.properties"/>  
  18.        
  19.      <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">  
  20.         <property name="driverClass" value="${mysql.driverclass}"></property>  
  21.         <property name="jdbcUrl" value="${mysql.jdbcurl}"></property>  
  22.         <property name="user" value="${mysql.user}"></property>  
  23.         <property name="password" value="${mysql.password}"></property>  
  24.         <property name="acquireIncrement" value="5"></property>  <!-- 當鏈接池中的鏈接用完時,C3P0一次性建立新鏈接的數目2 -->  
  25.         <property name="initialPoolSize" value="10"></property>  <!-- 初始化時建立的鏈接數,必須在minPoolSize和maxPoolSize之間 -->  
  26.         <property name="minPoolSize" value="5"></property>  
  27.         <property name="maxPoolSize" value="20"></property>  
  28.         <!-- 最大空閒時間,超過空閒時間的鏈接將被丟棄  
  29.         [須要注意:mysql默認的鏈接時長爲8小時(28800)【可在my.ini中添加 wait_timeout=30(單位秒)設置鏈接超時】,這裏設置c3p0的超時必須<28800]   
  30.         -->  
  31.         <property name="maxIdleTime" value="300"></property>    
  32.         <property name="idleConnectionTestPeriod" value="60"></property> <!-- 每60秒檢查鏈接池中的空閒鏈接 -->  
  33.         <property name="maxStatements" value="20"></property>  <!-- jdbc的標準參數  用以控制數據源內加載的PreparedStatement數量,但因爲預緩存的Statement屬 於單個Connection而不是整個鏈接 -->  
  34.      </bean>  
  35.        
  36.      <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  37.         <property name="dataSource" ref="dataSource"></property>  
  38.      </bean>  
  39.        
  40.      <!-- 聲明式事務管理 -->  
  41.      <aop:config>  
  42.         <aop:advisor pointcut="execution(* com.aokunsang.service.impl.*ServiceImpl.*(..))" advice-ref="myAdvice"/>  
  43.      </aop:config>  
  44.      <tx:advice id="myAdvice" transaction-manager="txManager">  
  45.         <tx:attributes>  
  46.             <tx:method name="add*" propagation="REQUIRED"/>  
  47.             <tx:method name="update*" propagation="REQUIRED"/>  
  48.             <tx:method name="*" read-only="true" rollback-for="com.aokunsang.util.DaoException"/>  
  49.         </tx:attributes>  
  50.      </tx:advice>  
  51.        
  52.      <!-- 自動掃描組件,須要把controller去掉,不然影響事務管理 -->  
  53.      <context:component-scan base-package="com.aokunsang">  
  54.         <context:exclude-filter type="regex" expression="com.aokunsang.web.*"/>  
  55.      </context:component-scan>  
  56.        
  57. </beans></span>  

 springmvc-servlet.xml文件:

 

Xml代碼   收藏代碼
  1. <span style="font-size: x-small;"><?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"    
  4.     xmlns:context="http://www.springframework.org/schema/context"    
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"    
  6.     xsi:schemaLocation="     
  7.            http://www.springframework.org/schema/beans     
  8.            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     
  9.            http://www.springframework.org/schema/context     
  10.            http://www.springframework.org/schema/context/spring-context-3.0.xsd    
  11.            http://www.springframework.org/schema/mvc     
  12.            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
  13.       
  14.     <!-- 啓動掃描全部的controller -->  
  15.     <context:component-scan base-package="com.aokunsang.web"/>  
  16.       
  17.     <!--  主要做用於@Controller,激活該模式  
  18.           
  19.         下面是一種簡寫形式,徹底能夠手動配置替代這種簡寫形式;  
  20.          它會自動註冊DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個bean,  
  21.            是spring MVC爲@Controllers分發請求所必須的  
  22.      -->  
  23.     <mvc:annotation-driven/>  
  24.       
  25.     <!-- 這裏攔截器還有一種配置方法【針對路徑進行配置】 推薦使用這個,方便直觀-->  
  26.     <mvc:interceptors>  
  27.         <mvc:interceptor>  
  28.             <mvc:mapping path="/user/MyHome"/>  
  29.             <mvc:mapping path="/usermanager/*"/>  
  30.             <bean  class="com.aokunsang.web.interceptor.MyInterceptor"></bean>  
  31.         </mvc:interceptor>  
  32.     </mvc:interceptors>  
  33.       
  34.      <!-- 全局配置   
  35.     <mvc:interceptors>  
  36.         <bean class="com.aokunsang.web.interceptor.MyInterceptor"></bean>  
  37.     </mvc:interceptors>  
  38.     -->  
  39.     <!-- 配置js,css等靜態文件直接映射到對應的文件夾,不被DispatcherServlet處理 -->  
  40.     <mvc:resources location="/WEB-INF/resources/**" mapping="/resources"/>  
  41.       
  42.     <!-- jsp頁面解析器,當Controller返回XXX字符串時,先經過攔截器,而後該類就會在/WEB-INF/views/目錄下,查找XXX.jsp文件-->  
  43.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  44.         <property name="prefix" value="/WEB-INF/views/"></property>  
  45.         <property name="suffix" value=".jsp"></property>  
  46.     </bean>  
  47.       
  48. </beans></span>  

 三、修改web.xml文件以下:

 

Xml代碼   收藏代碼
  1. <span style="font-size: x-small;"><context-param>  
  2.     <param-name>contextConfigLocation</param-name>  
  3.     <param-value>classpath:/META-INF/jdbc-context.xml</param-value>  
  4.   </context-param>    
  5.     
  6.   <listener>  
  7.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  8.   </listener>  
  9.   
  10.   <servlet>  
  11.     <servlet-name>spring-mvc</servlet-name>  
  12.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  13.     <init-param>  
  14.         <param-name>contextConfigLocation</param-name>  
  15.         <param-value>classpath:/META-INF/springmvc-servlet.xml</param-value>  
  16.     </init-param>  
  17.     <load-on-startup>1</load-on-startup>  
  18.   </servlet>  
  19.     
  20.   <servlet-mapping>  
  21.     <servlet-name>spring-mvc</servlet-name>  
  22.     <url-pattern>/</url-pattern>  
  23.   </servlet-mapping>  
  24.     
  25.   <filter>  
  26.     <filter-name>encodingFilter</filter-name>  
  27.     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  28.   </filter>  
  29.     
  30.   <filter-mapping>  
  31.     <filter-name>encodingFilter</filter-name>  
  32.     <url-pattern>/*</url-pattern>  
  33.   </filter-mapping></span>  

 四、從springmvc-servlet.xml中能夠知道,我把jsp頁面放在WEB-INF/views目錄中,靜態文件(圖片,js,css等)放在Resources目錄中,便於管理。

 

五、以上配置文件基本完成,下面開始代碼編寫:

首先說幾個經常使用的註解:

 

Java代碼   收藏代碼
  1. <span style="font-size: x-small;">@Autowired  自動注入[根據類型注入]<span style="font-size: 12px; white-space: normal;"><code style="font-size: small !important;">@Autowired</code> 能夠對成員變量、方法以及構造函數進行註釋,而 <code style="font-size: small !important;">@Qualifier</code> 的標註對象是成員變量、方法入參、構造函數入參。</span>  
  2. @Resource   自動注入[根據名稱注入],可寫參數name=""  
  3. @Controller 表示控制器  
  4. @Service    表示業務處理層[通常在serviceImpl]  
  5. @Repository 表示持久層[通常在daoImpl]  
  6. @Component  當你的類不清楚是哪一層的時候使用該註解  
  7. @ResponseBody  異步返回數據類型爲json  
  8. @RequestMapping  路徑,請求類型等設置  
  9. @InitBinder   數據綁定</span>  

 註解的詳細介紹:http://blog.csdn.net/zhongxiucheng/article/details/6662300 

 也能夠參考:https://www.ibm.com/developerworks/cn/java/j-lo-spring25-ioc/

 

<a>首先寫一個BaseController,可作一些數據綁定之類的全局操做(如:把日期字符串轉換爲Date日期)。

 

Java代碼   收藏代碼
  1. @Controller  
  2. public class BaseController {  
  3.   
  4.     @InitBinder  
  5.     protected void ininBinder(WebDataBinder binder){  
  6.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
  7.         binder.registerCustomEditor(Date.classnew CustomDateEditor(sdf,true));  
  8.     }  
  9. }  

 

<b>而後寫一個攔截器,攔截器有兩種實現方式,一、繼承HandlerInterceptorAdapter類,二、實現HandlerInterceptor接口。

 

Java代碼   收藏代碼
  1. /** 
  2.  * 自定義攔截器 
  3.  * @author tushen 
  4.  * @date Nov 5, 2011 
  5.  */  
  6. public class MyInterceptor extends HandlerInterceptorAdapter {  
  7.   
  8.     /** 
  9.      * 最後執行,可用於釋放資源 
  10.      */  
  11.     @Override  
  12.     public void afterCompletion(HttpServletRequest request,  
  13.             HttpServletResponse response, Object handler, Exception ex)  
  14.             throws Exception {  
  15.         // TODO Auto-generated method stub  
  16.         super.afterCompletion(request, response, handler, ex);  
  17.     }  
  18.   
  19.     /** 
  20.      * 顯示視圖前執行 
  21.      */  
  22.     @Override  
  23.     public void postHandle(HttpServletRequest request,  
  24.             HttpServletResponse response, Object handler,  
  25.             ModelAndView modelAndView) throws Exception {  
  26.           
  27.         System.out.println(request.getContentType()+"-----"+request.getCharacterEncoding()+"------"+request.getContextPath());  
  28.         System.out.println("MyInterceptor.postHandle()---viewName:"+modelAndView.getViewName());  
  29.         super.postHandle(request, response, handler, modelAndView);  
  30.     }  
  31.   
  32.     /** 
  33.      * Controller以前執行 
  34.      */  
  35.     @Override  
  36.     public boolean preHandle(HttpServletRequest request,  
  37.             HttpServletResponse response, Object handler) throws Exception {  
  38.           
  39.         String url = request.getRequestURI();  
  40.           
  41.         System.out.println("MyInterceptor.preHandle()"+url);  
  42.           
  43.         return super.preHandle(request, response, handler);  
  44.     }  
  45. }  

 

<c>在Util包中DBUtil.java中實現Spring JDBC Template的封裝,操做數據庫;寫一個DaoException繼承spring的運行時異常類NestedRuntimeException,在數據庫操做異常時拋出該異常,在controller層進行處理。

<d>寫一個抽象的BaseDao接口和BaseDaoImpl實現類,讓全部模塊共享使用(詳見附件)。

 

Java代碼   收藏代碼
  1. /** 
  2.  *  
  3.  */  
  4. package com.aokunsang.dao;  
  5.   
  6. import java.io.Serializable;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9.   
  10. /** 
  11.  * @author tushen 
  12.  * @date Nov 5, 2011 
  13.  */  
  14. public interface BaseDao {  
  15.   
  16.     /** 
  17.      * 保存或者更新實體 
  18.      * @param sql 
  19.      * @param entry 
  20.      */  
  21.     <T extends Serializable> void saveOrUpdateObject(String sql,T entry);  
  22.       
  23.     /** 
  24.      * 查詢實體列表 
  25.      * @param sql 
  26.      * @param className 
  27.      * @param obj 
  28.      * @return 
  29.      */  
  30.     <T extends Serializable> List<T> getObjList(String sql,Class<T> className,Object[] objs);  
  31.       
  32.     /** 
  33.      * 查詢實體 
  34.      * @param <T> 
  35.      * @param sql 
  36.      * @param objs 
  37.      * @return 
  38.      */  
  39.     <T extends Serializable> T getObject(String sql,Class<T> clazz,Object[] objs);  
  40.       
  41.     /** 
  42.      * 查詢一個Map集合 
  43.      * @param sql 
  44.      * @param objs 
  45.      * @return 
  46.      */  
  47.     Map<String,?> find(String sql,Object[] objs);  
  48.       
  49.     /** 
  50.      * 批量操做 
  51.      * @param sql 
  52.      * @param objLs 
  53.      */  
  54.     void batchOperate(String sql,List<?> objLs);  
  55.       
  56.     /** 
  57.      * 判斷實體是否存在 
  58.      * @param sql 
  59.      * @param obj 
  60.      * @return 
  61.      */  
  62.     int isExist(String sql,Object[] obj);  
  63.       
  64.     /** 
  65.      * 編輯操做 
  66.      * @param sql 
  67.      * @param obj 
  68.      * @return 
  69.      */  
  70.     int editObject(String sql,Object[] obj);  
  71. }  

 

 

六、一切就緒,啓動tomcat,訪問http://localhost:8080/springmvc,看是否訪問到了WEB-INF中的index.jsp頁面。

七、而後根據Controller中的路徑配置,依次訪問WEB-INF/views中的頁面。

相關文章
相關標籤/搜索