1.    背景介绍

  Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,可以选择是使用内置的 Spring Web 框架还是 Struts 这样的 Web 框架。通过策略接口,Spring 框架是高度可配置的,而且包含多种视图技术,例如 JavaServer Pages(JSP)技术、Velocity、Tiles、iText 和 POI。Spring MVC 框架并不知道使用的视图,所以不会强迫您只使用 JSP 技术。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

 

2.    常见MVC框架比较

  运行性能上

    Jsp+servlet>struts1>springmvc>struts2+freemarker>>struts2,ognl,值栈。

  开发效率上

    基本正好相反。值得强调的是,springmvc开发效率和struts2不相上下。

      Struts2的性能低的原因是因为OGNL和值栈造成的。所以,如果你的系统并发量高,可以使用freemaker进行显示,而不是采用OGNL和值栈。这样,在性能上会有相当大得提高。

 

3.    核心原理

  即调用过程如下:
 


 

4.    开发实战(Spring+SpringMVC+Hibernate)

  我们采用springMVC开发项目时,通常都会采用注解的方式(当然也可用配置文件方式),这样可以大大提高我们的开发效率。实现零配置。下面我们采用注解方式从零开始重新做一个spring MVC的配置。步骤如下:

  建立web项目,并建立整个项目的包结构和相关类。如下图所示:

      

 

 

  导入相关jar包,如下:(下载spring-framework-3.0.0.RELEASE,其它为Hibernate相关的jar)

      

 

 

  源码如下:

  web.xml

 

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.     <!-- 配置spring核心servlet -->   
  8.     <servlet>  
  9.         <servlet-name>springmvc</servlet-name>  
  10.         <servlet-class>  
  11.             org.springframework.web.servlet.DispatcherServlet  
  12.         </servlet-class>  
  13.         <!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如springmvc-servlet.xml-->   
  14.         <init-param>  
  15.             <param-name>contextConfigLocation</param-name>  
  16.             <param-value>/WEB-INF/hib-config.xml,/WEB-INF/springmvc-servlet.xml</param-value>  
  17.         </init-param>  
  18.         <load-on-startup>1</load-on-startup>  
  19.     </servlet>  
  20.     <!-- url-pattern配置为/,不带文件后缀,会造成其它静态文件(js,css等)不能访问。如配为*.do,则不影响静态文件的访问 -->    
  21.     <servlet-mapping>  
  22.         <servlet-name>springmvc</servlet-name>  
  23.         <url-pattern>*.do</url-pattern>  
  24.     </servlet-mapping>  
  25. </web-app>  

 

 

  springmvc-servlet.xml

 springmvc-servlet这个名字是因为上面web.xml中<servlet-name>标签配的值为springmvc(<servlet-name> springmvc </servlet-name>),再加上“-servlet”后缀而形成的springmvc-servlet.xml文件名,如果改为spring,对应的文件名则为spring-servlet.xml。

 

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. <?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:p="http://www.springframework.org/schema/p"      
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"      
  6.     xmlns:context="http://www.springframework.org/schema/context"      
  7.     xmlns:util="http://www.springframework.org/schema/util"      
  8.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd      
  9.             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd      
  10.             http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd      
  11.             http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">   
  12.        
  13.     <!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->  
  14.     <context:component-scan base-package="com.tgb.web"/>  
  15.   
  16.     <!-- 支持spring3.0新的mvc注解 -->  
  17.     <mvc:annotation-driven />    
  18.   
  19.     <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->  
  20.     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>  
  21.   
  22.     <!--对模型视图名称的解析,即在模型视图名称添加前后缀 -->  
  23.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"   
  24.         p:prefix="/WEB-INF/jsp/" p:suffix=".jsp">  
  25.          <!-- 如果使用jstl的话,配置下面的属性 -->  
  26.         <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />      
  27.     </bean>  
  28. </beans>  

 

 

  hib-config.xml(配置了spring集成hibernate)

 

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. <?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="http://www.springframework.org/schema/beans   
  8. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  9. http://www.springframework.org/schema/tx  
  10. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  11. http://www.springframework.org/schema/aop   
  12. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  13.   http://www.springframework.org/schema/context     
  14.    http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  15. ">  
  16.     <!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean -->    
  17.     <context:component-scan  base-package="com.tgb"/>     
  18.     <!-- 支持aop注解 -->  
  19.     <aop:aspectj-autoproxy />  
  20.           
  21.     <bean id="dataSource"    
  22.             class="org.apache.commons.dbcp.BasicDataSource">    
  23.             <property name="driverClassName"    
  24.                 value="com.mysql.jdbc.Driver">    
  25.             </property>    
  26.             <property name="url" value="jdbc:mysql://localhost:3306/myhib"></property>    
  27.             <property name="username" value="root"></property>    
  28.             <property name="password" value="123456"></property>  
  29.     </bean>    
  30.   
  31.    <bean id="sessionFactory"    
  32.        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">    
  33.            <property name="dataSource">    
  34.                <ref bean="dataSource" />    
  35.            </property>  
  36.            <property name="hibernateProperties">    
  37.                <props>    
  38.                 <!-- key的名字前面都要加hibernate. -->  
  39.                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>    
  40.                    <prop key="hibernate.show_sql">true</prop>  
  41.                    <prop key="hibernate.hbm2ddl.auto">update</prop>  
  42.                </props>  
  43.            </property>  
  44.         <property name="packagesToScan">  
  45.             <value>com.tgb.po</value>  
  46.         </property>  
  47.    </bean>    
  48.   
  49.     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" >  
  50.         <property name="sessionFactory" ref="sessionFactory"></property>  
  51.     </bean>  
  52.       
  53.     <!--配置一个JdbcTemplate实例-->    
  54.     <bean id="jdbcTemplate"  class="org.springframework.jdbc.core.JdbcTemplate">     
  55.          <property name="dataSource" ref="dataSource"/>     
  56.     </bean>    
  57.       
  58.       
  59.     <!-- 配置事务管理 -->  
  60.     <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" >  
  61.         <property name="sessionFactory" ref="sessionFactory"></property>  
  62.     </bean>  
  63.     <tx:annotation-driven transaction-manager="txManager" />  
  64.       
  65.     <aop:config>   
  66.         <aop:pointcut expression="execution(public * com.tgb.service.impl.*.*(..))" id="businessService"/>   
  67.         <aop:advisor advice-ref="txAdvice" pointcut-ref="businessService" />   
  68.     </aop:config>   
  69.     <tx:advice id="txAdvice" transaction-manager="txManager" >   
  70.         <tx:attributes>   
  71.             <tx:method name="find*"  read-only="true" propagation="NOT_SUPPORTED"  />   
  72.             <!-- get开头的方法不需要在事务中运行 。 有些情况是没有必要使用事务的,比如获取数据。开启事务本身对性能是有一定的影响的-->   
  73.             <tx:method name="*"/>    <!-- 其他方法在实务中运行 -->   
  74.         </tx:attributes>   
  75.     </tx:advice>   
  76. </beans>  

 

 

  index.jsp

 

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'index.jsp' starting page</title>  
  13.     <meta http-equiv="pragma" content="no-cache">  
  14.     <meta http-equiv="cache-control" content="no-cache">  
  15.     <meta http-equiv="expires" content="0">      
  16.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  17.     <meta http-equiv="description" content="This is my page">  
  18.     <!-- 
  19.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  20.     -->  
  21.   </head>  
  22.     
  23.   <body>  
  24.    <h1>**********${params.uname}</h1>  
  25.    <h1>**********${requestScope.u}</h1>  
  26.    <h1>**********${requestScope.user}</h1>  
  27.   </body>  
  28. </html>  

 

 

  User.java

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. package com.tgb.po;  
  2. import javax.persistence.Entity;  
  3. import javax.persistence.GeneratedValue;  
  4. import javax.persistence.GenerationType;  
  5. import javax.persistence.Id;  
  6.   
  7. @Entity  
  8. public class User {  
  9.     @Id  
  10.     @GeneratedValue(strategy=GenerationType.AUTO)  
  11.     private int id;  
  12.     private String uname;  
  13.     private String pwd;  
  14.       
  15.       
  16.     public String getPwd() {  
  17.         return pwd;  
  18.     }  
  19.     public void setPwd(String pwd) {  
  20.         this.pwd = pwd;  
  21.     }  
  22.     public int getId() {  
  23.         return id;  
  24.     }  
  25.     public void setId(int id) {  
  26.         this.id = id;  
  27.     }  
  28.     public String getUname() {  
  29.         return uname;  
  30.     }  
  31.     public void setUname(String uname) {  
  32.         this.uname = uname;  
  33.     }  
  34.       
  35.       
  36. }  

 

 

  UserDao.java

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. package com.tgb.dao;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.orm.hibernate3.HibernateTemplate;  
  6. import org.springframework.stereotype.Repository;  
  7.   
  8. import com.tgb.po.User;  
  9.   
  10. @Repository("userDao")  
  11. public class UserDao {  
  12.     @Resource  
  13.     private HibernateTemplate hibernateTemplate;  
  14.   
  15.     public void add(User u) {  
  16.   
  17.         System.out.println("UserDao.add()");  
  18.         hibernateTemplate.save(u);  
  19.     }  
  20.   
  21.     public HibernateTemplate getHibernateTemplate() {  
  22.         return hibernateTemplate;  
  23.     }  
  24.   
  25.     public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {  
  26.         this.hibernateTemplate = hibernateTemplate;  
  27.     }  
  28.   
  29. }  

 

 

  UserService.java

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. package com.tgb.service;  
  2.   
  3. import javax.annotation.Resource;  
  4. import org.springframework.stereotype.Service;  
  5. import com.tgb.dao.UserDao;  
  6. import com.tgb.po.User;  
  7.   
  8. @Service("userService")  
  9. public class UserService {  
  10.     @Resource  
  11.     private UserDao userDao;  
  12.       
  13.     public void add(String uname){  
  14.         System.out.println("UserService.add()");  
  15.         User u = new User();  
  16.         u.setUname(uname);  
  17.         userDao.add(u);  
  18.     }  
  19.   
  20.     public UserDao getUserDao() {  
  21.         return userDao;  
  22.     }  
  23.   
  24.     public void setUserDao(UserDao userDao) {  
  25.         this.userDao = userDao;  
  26.     }  
  27.       
  28. }  

 

 

  UserController.java

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. package com.tgb.web;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.ui.ModelMap;  
  7. import org.springframework.web.bind.annotation.RequestMapping;  
  8. import org.springframework.web.bind.annotation.RequestParam;  
  9. import org.springframework.web.bind.annotation.SessionAttributes;  
  10.   
  11. import com.tgb.po.User;  
  12. import com.tgb.service.UserService;  
  13.   
  14.   
  15. @Controller("userController")  
  16. @RequestMapping("/user.do")       
  17. public class UserController  {  
  18.   
  19.     @Resource  
  20.     private UserService userService;  
  21.       
  22.     @RequestMapping(params="method=reg")   
  23.     public String reg(String uname) {  
  24.         System.out.println("HelloController.handleRequest()");  
  25.         userService.add(uname);   
  26.         return "index";  
  27.     }  
  28.       
  29.     public UserService getUserService() {  
  30.         return userService;  
  31.     }  
  32.   
  33.     public void setUserService(UserService userService) {  
  34.         this.userService = userService;  
  35.     }  
  36. }  

 

 

 

运行测试:

http://localhost:8080/ SpringMVCTest /user.do?method=reg&uname=kobe

则会调用userController的reg方法,从而将数据内容插入到数据库中。

 

5.    总结

        现在主流的Web MVC框架除了Struts这个主力外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了。不过要想灵活运用Spring MVC来应对大多数的Web开发,就必须要掌握它的配置及原理。

Spring MVC与Struts从原理上很相似(都是基于MVC架构),都有一个控制页面请求的Servlet,处理完后跳转页面。

posted on 2015-08-24 17:23  风魂樱之花  阅读(124)  评论(0)    收藏  举报