用了大半年的Spring MVC3.0,用着感受不錯。簡單寫一個搭建Spring MVC3.0的流程(以Spring3.0.5爲列),數據庫交互使用spring JDBC Template,附件有項目(沒有jar包)。整個項目架構以下圖所示:css
![](http://static.javashuo.com/static/loading.gif)
一、去官網下載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下的工具包
![](http://static.javashuo.com/static/loading.gif)
二、借鑑spring官網寫法,創建一個src-resources Source Folder,再新建目錄META-INF,存放springmvc-servlet.xml和jdbc-context.xml文件(事務和數據庫鏈接池的管理);以及database.properties和log4j.properties。
JDBC-context.xml文件:
- <span style="font-size: x-small;"><?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:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-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/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" default-autowire="byName">
-
- <context:property-placeholder location="classpath:database.properties"/>
-
- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
- <property name="driverClass" value="${mysql.driverclass}"></property>
- <property name="jdbcUrl" value="${mysql.jdbcurl}"></property>
- <property name="user" value="${mysql.user}"></property>
- <property name="password" value="${mysql.password}"></property>
- <property name="acquireIncrement" value="5"></property>
- <property name="initialPoolSize" value="10"></property>
- <property name="minPoolSize" value="5"></property>
- <property name="maxPoolSize" value="20"></property>
- <!-- 最大空閒時間,超過空閒時間的鏈接將被丟棄
- [須要注意:mysql默認的鏈接時長爲8小時(28800)【可在my.ini中添加 wait_timeout=30(單位秒)設置鏈接超時】,這裏設置c3p0的超時必須<28800]
- -->
- <property name="maxIdleTime" value="300"></property>
- <property name="idleConnectionTestPeriod" value="60"></property>
- <property name="maxStatements" value="20"></property>
- </bean>
-
- <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource"></property>
- </bean>
-
-
- <aop:config>
- <aop:advisor pointcut="execution(* com.aokunsang.service.impl.*ServiceImpl.*(..))" advice-ref="myAdvice"/>
- </aop:config>
- <tx:advice id="myAdvice" transaction-manager="txManager">
- <tx:attributes>
- <tx:method name="add*" propagation="REQUIRED"/>
- <tx:method name="update*" propagation="REQUIRED"/>
- <tx:method name="*" read-only="true" rollback-for="com.aokunsang.util.DaoException"/>
- </tx:attributes>
- </tx:advice>
-
-
- <context:component-scan base-package="com.aokunsang">
- <context:exclude-filter type="regex" expression="com.aokunsang.web.*"/>
- </context:component-scan>
-
- </beans></span>
springmvc-servlet.xml文件:
- <span style="font-size: x-small;"><?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:p="http://www.springframework.org/schema/p"
- 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-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/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
-
-
- <context:component-scan base-package="com.aokunsang.web"/>
-
- <!-- 主要做用於@Controller,激活該模式
-
- 下面是一種簡寫形式,徹底能夠手動配置替代這種簡寫形式;
- 它會自動註冊DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個bean,
- 是spring MVC爲@Controllers分發請求所必須的
- -->
- <mvc:annotation-driven/>
-
-
- <mvc:interceptors>
- <mvc:interceptor>
- <mvc:mapping path="/user/MyHome"/>
- <mvc:mapping path="/usermanager/*"/>
- <bean class="com.aokunsang.web.interceptor.MyInterceptor"></bean>
- </mvc:interceptor>
- </mvc:interceptors>
-
- <!-- 全局配置
- <mvc:interceptors>
- <bean class="com.aokunsang.web.interceptor.MyInterceptor"></bean>
- </mvc:interceptors>
- -->
-
- <mvc:resources location="/WEB-INF/resources/**" mapping="/resources"/>
-
-
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/WEB-INF/views/"></property>
- <property name="suffix" value=".jsp"></property>
- </bean>
-
- </beans></span>
三、修改web.xml文件以下:
- <span style="font-size: x-small;"><context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:/META-INF/jdbc-context.xml</param-value>
- </context-param>
-
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
-
- <servlet>
- <servlet-name>spring-mvc</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:/META-INF/springmvc-servlet.xml</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>spring-mvc</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
-
- <filter>
- <filter-name>encodingFilter</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- </filter>
-
- <filter-mapping>
- <filter-name>encodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping></span>
四、從springmvc-servlet.xml中能夠知道,我把jsp頁面放在WEB-INF/views目錄中,靜態文件(圖片,js,css等)放在Resources目錄中,便於管理。
五、以上配置文件基本完成,下面開始代碼編寫:
首先說幾個經常使用的註解:
- <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>
- @Resource 自動注入[根據名稱注入],可寫參數name=""
- @Controller 表示控制器
- @Service 表示業務處理層[通常在serviceImpl]
- @Repository 表示持久層[通常在daoImpl]
- @Component 當你的類不清楚是哪一層的時候使用該註解
- @ResponseBody 異步返回數據類型爲json
- @RequestMapping 路徑,請求類型等設置
- @InitBinder 數據綁定</span>
註解的詳細介紹:http://blog.csdn.net/zhongxiucheng/article/details/6662300
也能夠參考:https://www.ibm.com/developerworks/cn/java/j-lo-spring25-ioc/
<a>首先寫一個BaseController,可作一些數據綁定之類的全局操做(如:把日期字符串轉換爲Date日期)。
- @Controller
- public class BaseController {
-
- @InitBinder
- protected void ininBinder(WebDataBinder binder){
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
- binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf,true));
- }
- }
<b>而後寫一個攔截器,攔截器有兩種實現方式,一、繼承HandlerInterceptorAdapter類,二、實現HandlerInterceptor接口。
-
-
-
-
-
- public class MyInterceptor extends HandlerInterceptorAdapter {
-
-
-
-
- @Override
- public void afterCompletion(HttpServletRequest request,
- HttpServletResponse response, Object handler, Exception ex)
- throws Exception {
-
- super.afterCompletion(request, response, handler, ex);
- }
-
-
-
-
- @Override
- public void postHandle(HttpServletRequest request,
- HttpServletResponse response, Object handler,
- ModelAndView modelAndView) throws Exception {
-
- System.out.println(request.getContentType()+"-----"+request.getCharacterEncoding()+"------"+request.getContextPath());
- System.out.println("MyInterceptor.postHandle()---viewName:"+modelAndView.getViewName());
- super.postHandle(request, response, handler, modelAndView);
- }
-
-
-
-
- @Override
- public boolean preHandle(HttpServletRequest request,
- HttpServletResponse response, Object handler) throws Exception {
-
- String url = request.getRequestURI();
-
- System.out.println("MyInterceptor.preHandle()"+url);
-
- return super.preHandle(request, response, handler);
- }
- }
<c>在Util包中DBUtil.java中實現Spring JDBC Template的封裝,操做數據庫;寫一個DaoException繼承spring的運行時異常類NestedRuntimeException,在數據庫操做異常時拋出該異常,在controller層進行處理。
<d>寫一個抽象的BaseDao接口和BaseDaoImpl實現類,讓全部模塊共享使用(詳見附件)。
-
-
-
- package com.aokunsang.dao;
-
- import java.io.Serializable;
- import java.util.List;
- import java.util.Map;
-
-
-
-
-
- public interface BaseDao {
-
-
-
-
-
-
- <T extends Serializable> void saveOrUpdateObject(String sql,T entry);
-
-
-
-
-
-
-
-
- <T extends Serializable> List<T> getObjList(String sql,Class<T> className,Object[] objs);
-
-
-
-
-
-
-
-
- <T extends Serializable> T getObject(String sql,Class<T> clazz,Object[] objs);
-
-
-
-
-
-
-
- Map<String,?> find(String sql,Object[] objs);
-
-
-
-
-
-
- void batchOperate(String sql,List<?> objLs);
-
-
-
-
-
-
-
- int isExist(String sql,Object[] obj);
-
-
-
-
-
-
-
- int editObject(String sql,Object[] obj);
- }
六、一切就緒,啓動tomcat,訪問http://localhost:8080/springmvc,看是否訪問到了WEB-INF中的index.jsp頁面。
七、而後根據Controller中的路徑配置,依次訪問WEB-INF/views中的頁面。