Spring MVC框架

1.Spring MVC框架前端


 1)Spring MVC的體系結構java

  Spring MVC主要構成組件以下:web

   DispatcherServlet-->Filterspring

   Controller-->Actionsql

   HandlerMapping-->ActionMapping數據庫

   ModelAndView-->ValueStackexpress

   ViewResolver-->Resultbootstrap

   springmvc標籤庫-->struts標籤庫瀏覽器

 

 2)Spring MVC的處理流程spring-mvc

  a.瀏覽器發出spring mvc請求,

請求交給前端控制器DispatcherServlet

  b.前段控制器調用HandlerMapping

組件,根據請求和Controller映射信息

找到相應的Controller組件處理請求

  c.Controller組件能夠調用DAO

組件完成數據庫操做。Controller處理

完畢後,會返回一個ModelAndView對象

結果.

  d.控制器接收ModelAndView以後,

調用ViewResolver組件,定位View

傳遞Model信息,生成響應內容.

 

 3)Spring MVC基本應用

 hello.form-->HelloController

 -->hello.jsp

 a.首先引入Spring IOCwebMVC開發包

 b.引入src/applicationContext.xml配置

 c.web.xml中配置DispatcherServlet控制器

 d.編寫HelloController,實現Controller

 e.applicationContext.xml

   定義Controller組件

   定義HandlerMapping組件

   定義ViewResolver組件

 

 

toLogin.form-->ToLoginController

-->login.jsp

login.form-->LoginController

-->成功進入hello.jsp

   錯誤返回login.jsp

 

 

Springmvc實例代碼實現

 

配置前端控制器--------------------------------------------

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">
 
<!--配置前端控制器 DispathcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--指定Spring容器的位置-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
</servlet>
 
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


 

Spring主配置文件-------------------------------------------

applicationContext.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:tx="http://www.springframework.org/schema/tx" 
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
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/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
 
<!--開啓掃描技術-->
<context:component-scan base-package="com.tarena"/>
 
<!-- 定義請求處理映射HandlerMapping,直接在Controller組件方法前使用註解@RequestMapping指定請求 -->
<bean id="handlerMapping" 
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
</bean>
<!-- 定義視圖解析器ViewResolver -->
<bean id="viewResolver" 
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/">
</property>
<property name="suffix" value=".jsp">
</property>
</bean>
 
 
 
</beans>


 

 

實體類------------------------------

package com.tarena.entity;
 
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
 
}


 

Controller控制----------------------------------

 

package com.tarena.action;
 
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
 
@Controller
@Scope("prototype")
public class ToLoginController {
@RequestMapping("/toLogin.do")
public String execute(){
return "login";
}
 
}


 

package com.tarena.action;
 
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
import com.tarena.entity.User;
 
 
@Controller
@Scope("prototype")
public class LoginController {
@RequestMapping("/login.do")
public String execute(User user,Model m){
String username = user.getUsername();
String password = user.getPassword();
System.out.println(username );
if("kitty".equals(username)&&"123".equals(password)){
m.addAttribute("msg", username);
return "hello";
}
m.addAttribute("error","輸入不正確");
return "login<welcome-file>/index.do</welcome-file>
  </welcome-file-list>
</web-app>


 

 

springMVCibatishibernateaop,緩存等的配置 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>springmvc3</display-name>
   <servlet> 
        <servlet-name>dispatcher</servlet-name> 
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
        <init-param> 
         <description>指定配置文件路徑</description> 
         <param-name>contextConfigLocation</param-name> 
         <param-value>/WEB-INF/applicationContext.xml</param-value> 
        </init-param> 
        <load-on-startup>1</load-on-startup> 
    </servlet> 
    <servlet-mapping> 
        <servlet-name>dispatcher</servlet-name> 
        <url-pattern>*.do</url-pattern> 
    </servlet-mapping> 
   
    <filter> 
        <filter-name>encoding-filter</filter-name> 
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 
        <init-param> 
            <param-name>encoding</param-name> 
            <param-value>UTF-8</param-value> 
        </init-param> 
        <init-param> 
            <param-name>forceEncoding</param-name> 
            <param-value>true</param-value> 
        </init-param> 
    </filter> 
    <filter-mapping> 
        <filter-name>encoding-filter</filter-name> 
        <url-pattern>*.do</url-pattern> 
    </filter-mapping> 
    
  <error-page>
      <error-code>400</error-code>
      <location>/error.jsp</location>
  </error-page>
  <error-page>
      <error-code>404</error-code>
      <location>/error.jsp</location>
  </error-page>
  <error-page>
      <exception-type>java.lang.Exception</exception-type>
      <location>/error.jsp</location>
  </error-page>
  
  <welcome-file-list>
    <welcome-file>/index.do</welcome-file>
  </welcome-file-list>
</web-app>


applicationContext.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:aop="http://www.springframework.org/schema/aop" 
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" 
xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring" 
xsi:schemaLocation=" 
http://www.springframework.org/schema/aop 
classpath:/org/springframework/aop/config/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/beans
         classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd 
        http://www.springframework.org/schema/context 
         classpath:/org/springframework/context/config/spring-context-3.0.xsd 
        http://www.springframework.org/schema/mvc 
         classpath:/org/springframework/web/servlet/config/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/tx 
         classpath:/org/springframework/transaction/config/spring-tx-3.0.xsd 
        http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring 
         classpath:/com/googlecode/ehcache/annotations/ehcache-spring-1.1.xsd 
"> 
<!-- ===================================== 視圖配置 ===================================== --> 
     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
<property name="prefix" value="/WEB-INF/jsp/"/> 
<property name="suffix" value=".jsp"/> 
</bean> 
<!-- ===================================== 註解驅動的配置 ===================================== --> 
<!-- <mvc:annotation-driven />  -->
<context:component-scan base-package="com.gdie.forum" /> 
<!-- ===================================== 數據源和事務管理 ===================================== --> 
<bean id="dataSource" 
class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
<property name="driverClassName" value="dm.jdbc.driver.DmDriver" /> 
<property name="url" value="jdbc:dm://192.168.20.65:5236" /> 
<property name="username" value="user" /> 
<property name="password" value="user" /> 
</bean> 
 
<bean id="transactionManager" 
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
<property name="dataSource" ref="dataSource" /> 
</bean> 
 
<tx:annotation-driven transaction-manager="transactionManager" 
proxy-target-class="true" /> 
<!--使用方式:在須要進行事務管理的方法上添加@Transactional(rollbackFor = Exception.class)-->  
 
<!-- ===================================== mybatis ===================================== --> 
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
<property name="dataSource" ref="dataSource" /> 
<!--property name="configLocation" value="/WEB-INF/Mybatis-Configuration.xml" /--> 
<property name="mapperLocations"> 
<list> 
<value>classpath:com/gdie/forum/dataaccess/mybatis/dm/*.xml</value> 
</list> 
</property> 
</bean> 
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> 
<constructor-arg index="0" ref="sqlSessionFactory" /> 
</bean> 
 
<!-- ===================================== AOP設置 ===================================== >
<aop:config>
    <aop:aspect id="logAOP" ref="logAop">
        <aop:pointcut expression="execution(* com.gdie.mvcdemo.controllers.*.*(..))" id="target"/>
        <aop:before method="methodTrace" pointcut-ref="target"/>
        <aop:around method="timeCost" pointcut-ref="target"/>
    </aop:aspect>
</aop:config-->
<!-- ===================================== 攔截器 ===================================== -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/forum/*.do" />
<mvc:mapping path="/thread/*.do"/>
<mvc:mapping path="/index.do"/>
<bean class="com.gdie.forum.interceptors.LoginInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
 
<!-- ===================================== cache設置 ===================================== -->
<ehcache:annotation-driven />
<ehcache:config cache-manager="cacheManager">
<ehcache:evict-expired-elements interval="60" />
</ehcache:config>
<bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="/WEB-INF/ehcache.xml" />
</bean>
<!--使用方式:在獲得須要緩存數據的方法上:@Cacheable(cacheName=Const.FORUM_CACHE)
在進行添加、刪除、更新時,須要刪除緩存,不然顯示的結果沒有變化
@TriggersRemove(cacheName=Const.FORUM_CACHE, removeAll=true)
其中Const.FORUM_CACHE在緩存配置文件ehcache.xml中配置
Const爲自定義的存放靜態變量的類
-->
<!-- ===================================== Hibernate設置 ===================================== -->
<!-- 定義Hibernate的SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref local="dataSource" />
</property>
<property name="mappingDirectoryLocations">
<list>
<value>classpath:com/lzw/model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.SQLServerDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- 定義Hibernate的事務管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<!--定義一個事物通知txAdvice,配置事物的傳播特性-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--全部以browse\list\load\get\is開頭的業務邏輯方法均不須要事物控制且只讀-->
<tx:method name="browse*" propagation="NOT_SUPPORTED" read-only="true"/>
<tx:method name="list*" propagation="NOT_SUPPORTED" read-only="true"/>
<tx:method name="load*" propagation="NOT_SUPPORTED" read-only="true"/>
<tx:method name="get*" propagation="NOT_SUPPORTED" read-only="true"/>
<tx:method name="is*" propagation="NOT_SUPPORTED" read-only="true"/>
<!--設置全部方法均進行事物控制,若是當前沒有事物,則新建一個事物-->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--基於AOP技術的事物管理實現-->
<aop:config>
<!--定義一個事務切入點,攔截com.company.service.impl包中全部類的全部方法-->
<aop:pointcut id="transactionPointcut" expression="execution(* com.company.service.impl.*.*(..))"/>
<!--引用txAdvice事務通知-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
</aop:config>
</beans>


 

 

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true" monitoring="autodetect"
         dynamicConfig="true">
 
   <diskStore path="java.io.tmpdir"/>
       <transactionManagerLookup class="net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup"
                              properties="jndiName=java:/TransactionManager" propertySeparator=";"/>
 
  <cacheManagerEventListenerFactory class="" properties=""/>
     <cacheManagerPeerProviderFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
            properties="peerDiscovery=automatic,
                        multicastGroupAddress=230.0.0.1,
                        multicastGroupPort=4446, timeToLive=1"
            propertySeparator=","
            />
  <cacheManagerPeerListenerFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/>
 <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            diskSpoolBufferSizeMB="30"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
            statistics="false"
            />
    <cache name="forumCache"
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            diskSpoolBufferSizeMB="30"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
            statistics="false"
            />
      <cacheEventListenerFactory
                class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/>
        <bootstrapCacheLoaderFactory
                class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"/>
    </cache>
</ehcache>
相關文章
相關標籤/搜索