基於注解的Spring MVC的簡單入門——簡略版


網上關於此教程各種版本,太多太多了,因為我之前沒搭過框架,最近帶着兩個實習生,為了幫他們搭框架,我只好。。。慚愧啊。。。基本原理的話各位自己了解下,表示我自己從來沒研究過Spring的源碼,所以工作了一年多還是在寫代碼。。。

下面直接正題,怎么搭建

我的Project目錄結構,jsp在web-inf目錄,js之類的在webroot根目錄。

ssyy

1.配置web.xml  

SpringMVC是一個基於DispatcherServlet的MVC框架,每一個請求最先訪問的都是DispatcherServlet,DispatcherServlet負責轉發每一個Request請求給相應的Handler,Handler處理以后再返回相應的視圖(View)和模型(Model),返回的視圖和模型都可以不指定,即可以只返回Model或只返回View或都不返回。DispatcherServlet是繼承自HttpServlet的,既然SpringMVC是基於DispatcherServlet的,那么我們先來配置一下DispatcherServlet。

<?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">
    <display-name>sy</display-name>  
   <servlet>
     <servlet-name>dispatcherServlet</servlet-name>
     <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:/main/config/applicationContext.xml,classpath*:/main/config/springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

2.配置springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    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    
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
     
    <!-- 對web包中的Controller進行掃描,以完成Bean創建和自動依賴注入的功能 -->
    <context:component-scan base-package="main.java.com.sy.controller"/>

    <!-- 啟動Spring MVC的注解功能,完成請求和注解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

    <!--對模型視圖名稱的解析,即在模型視圖名稱添加前后綴 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/pages/" p:suffix=".jsp"/>
   
</beans>

3.配置applicationContext.xml,掃描entity,service,dao的注解,其他的就不需要掃描,解析數據庫properties文件,配置事務,和之前的Spring配置一樣

<?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/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  http://www.springframework.org/schema/context   
   http://www.springframework.org/schema/context/spring-context-3.0.xsd
">

  <context:component-scan base-package="main.java.com.sy.service"></context:component-scan>
  <context:component-scan base-package="main.java.com.sy.dao"></context:component-scan>
  <context:component-scan base-package="main.java.com.sy.bean"></context:component-scan>
  
  <context:property-placeholder location="classpath*:/main/config/application.properties" />
    <!-- 支持aop注解 -->
    <aop:aspectj-autoproxy />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
            <property name="driverClassName" value="${jdbc.driverClass}"></property>  
            <property name="url" value="${jdbc.url}"></property>  
            <property name="username" value="${jdbc.user}"></property>  
            <property name="password" value="${jdbc.password}"></property>
    </bean>  

   <bean id="sessionFactory"  
       class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
           <property name="dataSource">  
               <ref bean="dataSource" />  
           </property>
           <property name="hibernateProperties">  
               <props>
                   <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
                   <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                   <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
               </props>
           </property>
        <property name="packagesToScan">
            <value>main.java.com.sy.entity</value>
        </property>
   </bean>  

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" >
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>
 
<bean id="jdbcTemplate"  class="org.springframework.jdbc.core.JdbcTemplate">   
     <property name="dataSource" ref="dataSource"/>   
</bean>


<!-- 配置事務管理 -->
    <bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" >
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <tx:annotation-driven transaction-manager="hibernateTransactionManager" />
    <aop:config> 
        <aop:pointcut expression="execution(* main.java.com.sy.service.impl.*.*(..))" id="businessService"/> 
        <aop:advisor advice-ref="txAdvice" pointcut-ref="businessService" /> 
    </aop:config> 

    <tx:advice id="txAdvice" transaction-manager="hibernateTransactionManager">
        <tx:attributes>
            <tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="delet*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="save*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="add*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="create*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="merge*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="revoke*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="*" propagation="SUPPORTS"/>
        </tx:attributes>
    </tx:advice>

</beans>

4.配置application.properties

#jdbc
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sy
jdbc.user=root
jdbc.password=root

#hibernate
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update

5.默認是進index.jsp頁面,但是我們不可以直接訪問,所以呢,做點修改。

<html>
  <head>
  </head>  
  <body>
    <script type="text/javascript">   
             top.window.location.replace("login.html");
    </script>
  </body>
</html>

6.如何才能進入這個頁面呢,我們來寫個Controller方法

UserController.java

@Controller
public class UserController {
        
    @RequestMapping(value = "/login.html")
    public String login(HttpServletRequest request,HttpServletResponse reponse) throws Exception{
        return "user/login";
    }    
}

7.因為我們想默認進一個登錄頁面,方法有了跳轉,頁面建立一下。

<form action="success.html" name="loginform" accept-charset="utf-8" id="login_form" class="loginForm" method="post">
     <label class="input-tips" for="u">帳號:</label>    
     <input type="text" id="accounName" name="accounName" class="inputstyle" placeholder="輸入用戶名/登錄名"/>
     <label class="input-tips" for="p">密碼:</label>                
     <input type="password" id="loginPassword" name="loginPassword" class="inputstyle" placeholder="輸入密碼" autocomplete="off"/>             
     <input type="button" id="login_button" value="登 錄" style="width:150px;" class="button_blue"/>
</form>

8.進入頁面之后,我們需要判斷正確性咯,在UserController加個success方法。

@RequestMapping(value = "/success.html")
public String success(HttpServletRequest request,HttpServletResponse reponse){
    String msg ="add successfully";
    request.setAttribute("msg", msg);
    return "user/sucess";
}

9.測試msg頁面很簡單,一個el表達式搞定

<html>
  <head>
  </head>
  <body>
   msg=${msg }
  </body>
</html>

關於詳細的源碼,源碼下載地址(提取碼:48f0),可以直接運行,多余的jar包大家酌情刪除,由於完稿倉促,很多細節沒有寫好,源碼我最近也重新修改了,我會盡快完善的。

有問題的同學可以加我企鵝:8078687


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM