1. 程式人生 > >基於spring2.5的采用XML配置的spring MVC項目

基於spring2.5的采用XML配置的spring MVC項目

ont encoding cte default 尚學堂 rri 導入jar包 request 事務

Spring MVC 背景介紹

Spring 框架提供了構建 Web 應用程序的全功能 MVC 模塊。使用 Spring 可插入的 MVC 架構,可以選擇是使用內置的 Spring Web 框架還是 Struts 這樣的 Web 框架。通過策略接口,Spring 框架是高度可配置的,而且包含多種視圖技術,例如 JavaServer Pages(JSP)技術、Velocity、Tiles、iText 和 POI。Spring MVC 框架並不知道使用的視圖,所以不會強迫您只使用 JSP 技術。Spring MVC 分離了控制器、模型對象、分派器以及處理程序對象的角色,這種分離讓它們更容易進行定制。

註:本項目全部基於XML配置。同時,集成了hibernate。采用的是:spring MVC+hibernate+spring的開發架構。 技術分享圖片

:轉載為尚學堂資料。

  1. 建立web項目
  2. 導入jar包(spring.jar, spring-webmvc.jar, commons-logging.jar。其他jar包為hibernate相關jar包)
  3. 修改web.xml如下:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
        xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet
    </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/hib-config.xml,/WEB-INF/web-config.xml,/WEB-INF/service-config.xml,/WEB-INF/dao-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
  4. 增加web-config.xml(這裏包含spring mvc相關的相關配置)
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        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-2.5.xsd">
        
        <!-- Controller方法調用規則定義 -->
        <bean id="paraMethodResolver"
            class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
            <property name="paramName" value="action"/>
            <property name="defaultMethodName" value="list"/>
        </bean>
      
       <!-- 頁面View層基本信息設定 -->
        <bean id="viewResolver"
              class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="viewClass"
                value="org.springframework.web.servlet.view.JstlView"/>
            <!--<property name="prefix" value="/myjsp/"/>-->
            <property name="suffix" value=".jsp"/>
        </bean>
    
    <!-- servlet映射列表,所有控制層Controller的servlet在這裏定義 -->
        <bean id="urlMapping"
              class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
            <property name="mappings">
                <props>
                    <prop key="user.do">userController</prop>
                </props>
            </property>
        </bean>
    
    <bean id="userController" class="com.sxt.action.UserController">
        <property name="userService" ref="userService"></property>
    </bean>
    </beans>
  5. 在WEB-INF下增加service-config.xml(這裏包含service層類的相關配置)
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        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-2.5.xsd">
    
        <bean id="userService" class="com.sxt.service.UserService">
            <property name="userDao" ref="userDao"></property>
        </bean>
        
    </beans>

  6. 在WEB-INF下增加hib-config.xml(這裏包含spring集成hibernate相關的配置)
    <?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-2.5.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
      http://www.springframework.org/schema/context   
       http://www.springframework.org/schema/context/spring-context-2.5.xsd
    ">
        <context:component-scan  base-package="com.sxt"/>   
        <!-- 支持aop註解 -->
        <aop:aspectj-autoproxy />
        
            
        <bean id="dataSource"  
                class="org.apache.commons.dbcp.BasicDataSource">  
                <property name="driverClassName"  
                    value="com.mysql.jdbc.Driver">  
                </property>  
                <property name="url" value="jdbc:mysql://localhost:3306/myhib"></property>  
                <property name="username" value="root"></property>  
                <property name="password" value="123456"></property>
        </bean>  
    
       <bean id="sessionFactory"  
           class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
               <property name="dataSource">  
                   <ref bean="dataSource" />  
               </property>
               <property name="hibernateProperties">  
                   <props>  
                       <!-- key的名字前面都要加hibernate. -->
                       <prop key="hibernate.dialect">  
                           org.hibernate.dialect.MySQLDialect  
                       </prop>  
                       <prop key="hibernate.show_sql">true</prop>
                       <prop key="hibernate.hbm2ddl.auto">update</prop>
                   </props>
               </property>
            <property name="packagesToScan">
                <value>com.sxt.po</value>
            </property>
       </bean>  
    
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" >
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    
    <!--配置一個JdbcTemplate實例-->  
    <bean id="jdbcTemplate"  class="org.springframework.jdbc.core.JdbcTemplate">   
         <property name="dataSource" ref="dataSource"/>   
    </bean>  
    
    
    <!-- 配置事務管理 -->
    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" >
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <tx:annotation-driven transaction-manager="txManager" />
    <aop:config> 
        <aop:pointcut expression="execution(public * com.sxt.service.impl.*.*(..))" id="businessService"/> 
        <aop:advisor advice-ref="txAdvice" pointcut-ref="businessService" /> 
    </aop:config> 
    <tx:advice id="txAdvice" transaction-manager="txManager" > 
        <tx:attributes> 
            <tx:method name="find*"  read-only="true" propagation="NOT_SUPPORTED"  /> 
            <!-- get開頭的方法不需要在事務中運行 。 
            有些情況是沒有必要使用事務的,比如獲取數據。開啟事務本身對性能是有一定的影響的--> 
            <tx:method name="*"/>    <!-- 其他方法在實務中運行 --> 
        </tx:attributes> 
    </tx:advice> 
    
    </beans>

  7. 在WEB-INF下增加dao-config.xml(這裏包含dao層類的相關配置)
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        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-2.5.xsd">
        
        <bean id="userDao" class="com.sxt.dao.UserDao">
          <property name="hibernateTemplate" ref="hibernateTemplate"></property>
        </bean>
    </beans>

  8. 建立相關類和包結構,如下圖所示:技術分享圖片

  9. 各類代碼:
    package com.sxt.po;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    
    @Entity
    public class User {
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private int id;
        private String uname;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getUname() {
            return uname;
        }
        public void setUname(String uname) {
            this.uname = uname;
        }
    }
    package com.sxt.dao;
    
    import org.springframework.orm.hibernate3.HibernateTemplate;
    
    import com.sxt.po.User;
    
    public class UserDao {
        private HibernateTemplate hibernateTemplate;
        
        public void add(User u){
            System.out.println("UserDao.add()");
            hibernateTemplate.save(u);
        }
    
        public HibernateTemplate getHibernateTemplate() {
            return hibernateTemplate;
        }
    
        public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
            this.hibernateTemplate = hibernateTemplate;
        }
        
    }
    package com.sxt.service;
    
    import com.sxt.dao.UserDao;
    import com.sxt.po.User;
    
    public class UserService {
        
        private UserDao userDao;
        
        public void add(String uname){
            System.out.println("UserService.add()");
            User u = new User();
            u.setUname(uname);
            userDao.add(u);
        }
    
        public UserDao getUserDao() {
            return userDao;
        }
    
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }
        
    }
    package com.sxt.action;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.Controller;
    
    import com.sxt.service.UserService;
    
    public class UserController implements Controller {
    
        private UserService userService;
        
        @Override
        public ModelAndView handleRequest(HttpServletRequest req,
                HttpServletResponse resp) throws Exception {
            System.out.println("HelloController.handleRequest()");
            req.setAttribute("a", "aaaa");
            userService.add(req.getParameter("uname")); 
            return new ModelAndView("index");
        }
    
        public UserService getUserService() {
            return userService;
        }
    
        public void setUserService(UserService userService) {
            this.userService = userService;
        }
    
        
    }

    1. 運行測試:

    http://locahost:8080/springmvc01/user.do?uname=zhangsan

    結果:數據庫中增加zhangsan的記錄。頁面跳轉到index.jsp上,顯示

基於spring2.5的采用XML配置的spring MVC項目