您的位置:首页 > 编程语言 > Java开发

spring MVC3.0.5搭建全程

2014-05-20 11:19 253 查看
简单写一个搭建Spring MVC3.0的流程(以Spring3.0.5为列),数据库交互使用SpringJdbcTemplate,附件有项目(没有jar包)。整个项目结构如下图所示:



 

 1、去官网下载3.0.5所有jar包,所需jar包,见附件图片,每个jar包得用处如下:

org.springframework.aop- 3.0.0.RELEASE--------------------Spring的面向切面编程,提供AOP(面向切面编程)实现

org.springframework.asm- 3.0.0.RELEASE--------------------Spring独立的asm程序,相遇Spring2.5.6的时候需要asmJar 包.3.0开始提供他自己独立的asmJar

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

org.springframework.beans- 3.0.0.RELEASE------------------SpringIoC(依赖注入)的基础实现

org.springframework.context.support- 3.0.0.RELEASE--------Spring-context的扩展支持,用于MVC方面

org.springframework.context- 3.0.0.RELEASE----------------Spring提供在基础IoC功能上的扩展服务,此外还提供许多企业级服务的支持,如邮件服务、任务调度、JNDI定位、EJB集成、远程访问、缓存以及各种视图层框架的封装等

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

org.springframework.expression- 3.0.0.RELEASE-------------Spring表达式语言

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下的工具包

  说明:jar包库使用官方提供的,无需全部加载到项目中。

 

2、借鉴spring官网写法,建立一个src-resources Source Folder,再新建目录META-INF,存放springmvc-servlet.xml和jdbc-context.xml文件(事务和数据库连接池的管理);以及database.properties和log4j.properties。

 

JDBC-context.xml文件:

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: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>  <!-- 当连接池中的连接用完时,C3P0一次性创建新连接的数目2 -->  
        <property name="initialPoolSize" value="10"></property>  <!-- 初始化时创建的连接数,必须在minPoolSize和maxPoolSize之间 -->  
        <property name="minPoolSize" value=
15a81
"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> <!-- 每60秒检查连接池中的空闲连接 -->  
        <property name="maxStatements" value="20"></property>  <!-- jdbc的标准参数  用以控制数据源内加载的PreparedStatement数量,但由于预缓存的Statement属 于单个Connection而不是整个连接 -->  
     </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>  
       
     <!-- 自动扫描组件,需要把controller去掉,否则影响事务管理 -->  
     <context:component-scan base-package="com.aokunsang">  
        <context:exclude-filter type="regex" expression="com.aokunsang.web.*"/>  
     </context:component-scan>  
</beans>  

 

 springmvc-servlet.xml文件:

 

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: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">  
      
    <!-- 启动扫描所有的controller -->  
    <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>  
    -->  
    <!-- 配置js,css等静态文件直接映射到对应的文件夹,不被DispatcherServlet处理   
    mapping --- WebRoot里面的静态文件位置目录  
    location --- 访问地址   
    -->  
    <mvc:resources location="/resources/**" mapping="/WEB-INF/resources/"/>  
  
    <!--  
       配置/WEB-INF/views/目录里面的jsp文件不被DispatcherServlet处理,可以直接通过浏览器访问。  
       view-name --- /WEB-INF/views/里面的jsp文件名(不许后缀即可)  
       path ---  访问地址  
    -->   
    <mvc:view-controller path="/header" view-name="header"/>  
  
    <!-- jsp页面解析器,当Controller返回XXX字符串时,先通过拦截器,然后该类就会在/WEB-INF/views/目录下,查找XXX.jsp文件-->  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/views/"></property>  
        <property name="suffix" value=".jsp"></property>  
    </bean>  
</beans>  

 3、修改web.xml文件如下:

 

Xml代码  


<!-- Log4j的配置(在同一容器中部署多个应用时,  
    不能使用默认的webAppRootKey,必须指定唯一KEY,以免冲突)   
-->    
<context-param>  
    <param-name>webAppRootKey</param-name>  
    <param-value>springmvc.root</param-value>  
</context-param>  
  
<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>  

 

 4、从springmvc-servlet.xml中可以知道,我把jsp页面放在WEB-INF/views目录中,静态文件(图片,js,css等)放在Resources目录中,便于管理。

 

5、以上配置文件基本完成,下面开始代码编写:

首先说几个常用的注解:

 

Java代码  


@Autowired和@Qualifier  自动注入[根据类型注入]  
  @Autowired 可以对成员变量、方法以及构造函数进行注释,  
  @Qualifier 的标注对象是成员变量、方法入参、构造函数入参。  
  ps:两者结合使用相当于@Resourcede效果。  
@Resource   自动注入[根据名称注入],可写参数name=""  
@Controller 表示控制器  
@Service    表示业务处理层[一般在serviceImpl]  
@Repository 表示持久层[一般在daoImpl]  
@Component  当你的类不清楚是哪一层的时候使用该注解  
@ResponseBody  异步返回数据类型为json  
@RequestMapping  路径,请求类型等设置  
@InitBinder   数据绑定  
@RequestBody、@ModeleAttributes、@SessionAttributes等  

 

 注解的详细介绍:http://blog.csdn.net/zhongxiucheng/article/details/6662300 

 也可以参考:https://www.ibm.com/developerworks/cn/java/j-lo-spring25-ioc/

 

<a>首先写一个BaseController,可做一些数据绑定之类的全局操作(如:把日期字符串转换为Date日期)。

 

Java代码  


@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>然后写一个拦截器,拦截器有两种实现方式,1、继承HandlerInterceptorAdapter类,2、实现HandlerInterceptor接口。

 

Java代码  


/** 
 * 自定义拦截器 
 * @author tushen 
 * @date Nov 5, 2011 
 */  
public class MyInterceptor extends HandlerInterceptorAdapter {  
  
    /** 
     * 最后执行,可用于释放资源 
     */  
    @Override  
    public void afterCompletion(HttpServletRequest request,  
            HttpServletResponse response, Object handler, Exception ex)  
            throws Exception {  
        // TODO Auto-generated method stub  
        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);  
    }  
  
    /** 
     * Controller之前执行 
     */  
    @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实现类,让所有模块共享使用(详见附件)。

 

Java代码  


/** 
 *  
 */  
package com.aokunsang.dao;  
  
import java.io.Serializable;  
import java.util.List;  
import java.util.Map;  
  
/** 
 * @author tushen 
 * @date Nov 5, 2011 
 */  
public interface BaseDao {  
  
    /** 
     * 保存或者更新实体 
     * @param sql 
     * @param entry 
     */  
    <T extends Serializable> void saveOrUpdateObject(String sql,T entry);  
      
    /** 
     * 查询实体列表 
     * @param sql 
     * @param className 
     * @param obj 
     * @return 
     */  
    <T extends Serializable> List<T> getObjList(String sql,Class<T> className,Object[] objs);  
      
    /** 
     * 查询实体 
     * @param <T> 
     * @param sql 
     * @param objs 
     * @return 
     */  
    <T extends Serializable> T getObject(String sql,Class<T> clazz,Object[] objs);  
      
    /** 
     * 查询一个Map集合 
     * @param sql 
     * @param objs 
     * @return 
     */  
    Map<String,?> find(String sql,Object[] objs);  
      
    /** 
     * 批量操作 
     * @param sql 
     * @param objLs 
     */  
    void batchOperate(String sql,List<?> objLs);  
      
    /** 
     * 判断实体是否存在 
     * @param sql 
     * @param obj 
     * @return 
     */  
    int isExist(String sql,Object[] obj);  
      
    /** 
     * 编辑操作 
     * @param sql 
     * @param obj 
     * @return 
     */  
    int editObject(String sql,Object[] obj);  
}  

 

 

6、一切就绪,启动tomcat,访问http://localhost:8080/springmvc,看是否访问到了WEB-INF中的index.jsp页面。

7、然后根据Controller中的路径配置,依次访问WEB-INF/views中的页面。

 

另外:再附上一张他人画得springMVC3.0的流程图,我感觉画得还是挺好的,收藏了。



 

 

springmvc.rar (28.9 KB)
下载次数: 2112
查看图片附件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java spring