Spring MVC框架---小案例


1.Spring MVC框架
 1)Spring MVC的体系结构
  Spring MVC主要构成组件如下:
   DispatcherServlet-->Filter
   Controller-->Action
   HandlerMapping-->ActionMapping
   ModelAndView-->ValueStack
   ViewResolver-->Result
   springmvc标签库-->struts标签库

 2)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 IOC和webMVC开发包
 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>




springMVC对ibatis,hibernate,aop,缓存等的配置 
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>


你可能感兴趣的:(spring,框架,mvc)