SpringMvc.md

SpringMVC


1 SpringMVC 介绍

​ 解析 :Spring mvc 是Spring框架的一部分,基于mvc 的表现层框架 , 用于web项目开发

SpringMvc.md_第1张图片

1.1 mvc 设计模式

​ 简单来说就是 m(model) 模型- v(view) 视图 - c(controller) 控制器 , 三次架构设计模式 。 主要用于前端页面的展示和后端业务数据处理逻辑分离

​ 模式优点:分层设计 , 实现我们业务系统各个组件之间的解耦 , 有利于业务系统的可拓展性 , 维护性 , 有利于并行开发,提升开发效率

SpringMvc.md_第2张图片

1.2 入门案例
1.2.1 准备主配置文件
  • 创建一个web 项目

  • 加入pom.xml的依赖

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0modelVersion>
    
    	<groupId>com.dsdd.weyougroupId>
    	<artifactId>springmvc-firstartifactId>
    	<version>0.0.1-SNAPSHOTversion>
    
    	<packaging>warpackaging>
    
    	<name>springmvc-first Maven Webappname>
    	<url>http://maven.apache.orgurl>
    
    	<properties>
    		
    		<spring.version>4.3.8.RELEASEspring.version>
    		
    		<jstl.version>1.2jstl.version>
    	properties>
    
    	<dependencies>
    		
    		<dependency>
    			<groupId>org.springframeworkgroupId>
    			<artifactId>spring-coreartifactId>
    			<version>${spring.version}version>
    		dependency>
    		<dependency>
    			<groupId>org.springframeworkgroupId>
    			<artifactId>spring-webartifactId>
    			<version>${spring.version}version>
    		dependency>
    		<dependency>
    			<groupId>org.springframeworkgroupId>
    			<artifactId>spring-txartifactId>
    			<version>${spring.version}version>
    		dependency>
    		<dependency>
    			<groupId>org.springframeworkgroupId>
    			<artifactId>spring-jdbcartifactId>
    			<version>${spring.version}version>
    		dependency>
    		<dependency>
    			<groupId>org.springframeworkgroupId>
    			<artifactId>spring-webmvcartifactId>
    			<version>${spring.version}version>
    		dependency>
    		<dependency>
    			<groupId>org.springframeworkgroupId>
    			<artifactId>spring-aopartifactId>
    			<version>${spring.version}version>
    		dependency>
    		<dependency>
    			<groupId>org.springframeworkgroupId>
    			<artifactId>spring-context-supportartifactId>
    			<version>${spring.version}version>
    		dependency>
    		
    		<dependency>
    			<groupId>jstlgroupId>
    			<artifactId>jstlartifactId>
    			<version>${jstl.version}version>
    		dependency>
    		<dependency>
    			<groupId>junitgroupId>
    			<artifactId>junitartifactId>
    			<version>4.12version>
    			<scope>testscope>
    		dependency>
    	dependencies>
    
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.apache.tomcat.mavengroupId>
    				<artifactId>tomcat7-maven-pluginartifactId>
    				<version>2.1version>
    				<configuration>
    					
    					<port>8080port>
    					
    					<path>/springmvc-firstpath>
    					
    					<uriEncoding>UTF-8uriEncoding>
    					
    					<server>tomcat7server>
    				configuration>
    			plugin>
    		plugins>
    	build>
    project>
    
  • 加入SpringMvc.xml

    
    <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:mvc="http://www.springframework.org/schema/mvc"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans 
    	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    
    beans> 
    
1.2.2 web.xml配置前端控制器

<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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>springmvc-firstdisplay-name>
  
  
  <servlet>
  	<servlet-name>springmvc-firstservlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
  	
  	
  	<init-param>
  		<param-name>contextConfigLocationparam-name>
  		<param-value>classpath:springmvc.xmlparam-value>
  	init-param>
  	
  	
  	<load-on-startup>1load-on-startup>
  servlet>
  
  <servlet-mapping>
  	<servlet-name>springmvc-firstservlet-name>
  	
  	<url-pattern>*.dourl-pattern>
  servlet-mapping>
  
  
  <welcome-file-list>
    <welcome-file>index.htmlwelcome-file>
    <welcome-file>index.htmwelcome-file>
    <welcome-file>index.jspwelcome-file>
    <welcome-file>default.htmlwelcome-file>
    <welcome-file>default.htmwelcome-file>
    <welcome-file>default.jspwelcome-file>
  welcome-file-list>
web-app>
1.2.3 准备jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




springmvc入门程序


	你好,世界。${hello}


1.2.4 准备控制器controller
// @Controller注解:用于标记普通的java类,作为控制器
@Controller
public class HelloController {
	
	// ModelAndView:模型和视图,用于设置响应的模型数据,用于设置响应的视图
	// @RequestMapping注解:配置请求的url
	@RequestMapping("/hello.do")
	public ModelAndView hello(){
		
		// 1.创建ModelAndView对象
		ModelAndView mav = new ModelAndView();
		
		// 2.设置响应的模型数据
		// addObject方法:设置响应的模型数据
		// attributeName参数:模型的名称(hello)
		// attributeValue参数:模型的数据
		mav.addObject("hello", "springmvc!!!");
		
		// 3.设置响应的视图
		// setViewName方法:设置视图名称
		// viewName参数:视图名称(jsp页面的物理路径)
		mav.setViewName("/WEB-INF/jsp/hello.jsp");
		
		return mav;
		
	}

}
1.2.5 配置扫描controller

<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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
        
        
        <context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>

beans> 

2 SpringMVC 三大组件

2.1 处理器映射器

​ 解析 : 根据请求的url , 查找处理器

2.1.1 默认处理器映射器(已过时)
org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
2.1.2 配置处理器映射器

​ 在springmvc.xml中加入配置处理器映射器


<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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
        
        
        <context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
        
        
        <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">bean>
beans> 
2.2 处理器适配器

​ 解析:执行处理器方法

2.2.1 默认处理器适配器(已过时)
org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,
	org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,
	org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
2.2.2 配置处理器适配器

<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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
        
        
        <context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
        
        
        <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">bean>
        
        
        <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">bean>

beans> 
2.3 实际开发中配置映射器和适配器

<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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
        
        
        <context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
        
        
        
        
        
       
       
       
       <mvc:annotation-driven>mvc:annotation-driven>

beans> 
2.3 视图解析器

​ 解析 :把逻辑视图(在controller设置的视图名称)解析成物理视图(在浏览器看到的页面)。

2.3.1 默认视图解析器
org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver
2.3.2 配置视图解析器

<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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
        
        
        <context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
        
        
        
        
        
       
       
       
       <mvc:annotation-driven>mvc:annotation-driven>
       
       
       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       		
       		<property name="prefix" value="/WEB-INF/jsp/">property>
       		
       		
       		<property name="suffix" value=".jsp">property>
       bean>

beans> 

3 框架原理

3.1 spring mvc 流程

​ 解析 :

  • 1 用户页面请求 , 前端控制器接受用户请求***(DispatcherServlet 为springMvc的核心类)***

  • 2 请求处理器映射器 , 查找处理器(处理器映射器:HandlerMapping查找处理器)

  • 3 根据请求的url , 查找处理器(处理器Controller)

  • 4 返回处理器到前端控制器

  • 5 请求处理器适配器 , 执行处理器(处理器适配器:HandlerAdapter执行处理器)

  • 6 执行处理器 ,返回模型和视图

  • 7 请求解析视图 , 视图解析器(ViewResolve解析视图)

  • 8 解析视图:jsp

  • 9 返回视图 , 响应用户

SpringMvc.md_第3张图片

3.2 项目分层

SpringMvc.md_第4张图片

3.3 spring mvc 整合
3.3.1 pom.xml 加入依赖(mybatis框架包,spring框架包(包括springmvc), myabtis-spring整合包,数据库驱动包,数据源连接池包)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0modelVersion>

	<groupId>com.dsdd.weyougroupId>
	<artifactId>ssmartifactId>
	<version>0.0.1-SNAPSHOTversion>

	<packaging>warpackaging>

	<name>ssm Maven Webappname>
	<url>http://maven.apache.orgurl>

	<properties>
		
		<spring.version>4.3.8.RELEASEspring.version>
		
		<aspectj.version>1.6.12aspectj.version>
		
		<jstl.version>1.2jstl.version>
		
		<mybatis.version>3.4.5mybatis.version>
		
		<mybatis.spring.version>1.3.1mybatis.spring.version>
		
		<mysql.version>5.1.30mysql.version>
		
		<dbcp.version>1.2.2dbcp.version>
		
		<slf4j.version>1.7.7slf4j.version>
		<log4j.version>1.2.17log4j.version>
		
		<commons.lang.version>2.6commons.lang.version>
	properties>

	<dependencies>
		
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-coreartifactId>
			<version>${spring.version}version>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-webartifactId>
			<version>${spring.version}version>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-txartifactId>
			<version>${spring.version}version>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-jdbcartifactId>
			<version>${spring.version}version>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-webmvcartifactId>
			<version>${spring.version}version>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-aopartifactId>
			<version>${spring.version}version>
		dependency>
		<dependency>
			<groupId>org.springframeworkgroupId>
			<artifactId>spring-context-supportartifactId>
			<version>${spring.version}version>
		dependency>
		<dependency>
			<groupId>org.aspectjgroupId>
			<artifactId>aspectjweaverartifactId>
			<version>${aspectj.version}version>
		dependency>
		
		<dependency>
			<groupId>jstlgroupId>
			<artifactId>jstlartifactId>
			<version>${jstl.version}version>
		dependency>
		
		<dependency>
			<groupId>org.mybatisgroupId>
			<artifactId>mybatisartifactId>
			<version>${mybatis.version}version>
		dependency>
		
		<dependency>
			<groupId>org.mybatisgroupId>
			<artifactId>mybatis-springartifactId>
			<version>${mybatis.spring.version}version>
		dependency>
		
		<dependency>
			<groupId>mysqlgroupId>
			<artifactId>mysql-connector-javaartifactId>
			<version>${mysql.version}version>
		dependency>
		
		<dependency>
			<groupId>commons-dbcpgroupId>
			<artifactId>commons-dbcpartifactId>
			<version>${dbcp.version}version>
		dependency>
		
		<dependency>
			<groupId>log4jgroupId>
			<artifactId>log4jartifactId>
			<version>${log4j.version}version>
		dependency>
		<dependency>
			<groupId>org.slf4jgroupId>
			<artifactId>slf4j-apiartifactId>
			<version>${slf4j.version}version>
		dependency>
		<dependency>
			<groupId>org.slf4jgroupId>
			<artifactId>slf4j-log4j12artifactId>
			<version>${slf4j.version}version>
		dependency>
		<dependency>
			<groupId>commons-langgroupId>
			<artifactId>commons-langartifactId>
			<version>${commons.lang.version}version>
		dependency>

		
		<dependency>
			<groupId>javax.servletgroupId>
			<artifactId>jsp-apiartifactId>
			<version>2.0version>
			<scope>providedscope>
		dependency>
	dependencies>
	<build>
		<finalName>ssmfinalName>
		<plugins>
			<plugin>
				<groupId>org.apache.tomcat.mavengroupId>
				<artifactId>tomcat7-maven-pluginartifactId>
				<version>2.1version>
				<configuration>
					
					<port>8080port>
					
					<path>/ssmpath>
					
					<uriEncoding>UTF-8uriEncoding>
					
					<server>tomcat7server>
				configuration>
			plugin>
		plugins>
	build>
project>
3.3.2 准备配置文件(配置别名)


<configuration>

	
	<typeAliases>
		
		<package name="com.dsdd.weyou.po"/>
	typeAliases>
	

configuration>
3.3.3 springMvc.xml(配置组件扫描controller,处理器映射器,处理器适配器,视图解析器)

<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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
        
        
        <context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
        
        
        <mvc:annotation-driven>mvc:annotation-driven>
        
        
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        	
        	<property name="prefix" value="/WEB-INF/jsp/">property>
        	
        	
        	<property name="suffix" value=".jsp">property>
        bean>

beans>  
3.3.4 applicationContext-dao.xml(配置数据源对象,mybatis核心对象SqlSessionFactory,mapper扫描器)

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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-4.0.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util 
	http://www.springframework.org/schema/util/spring-util-4.0.xsd">
	
	
	<context:property-placeholder location="classpath:db.properties"/>
	
	
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
		destroy-method="close">
		
		<property name="driverClassName" value="${db.driverClassName}"/>
		<property name="url" value="${db.url}" />
		<property name="username" value="${db.username}" />
		<property name="password" value="${db.password}" />
		
		
		<property name="maxActive" value="${db.maxActive}"/>
		
		<property name="minIdle" value="${db.minIdle}"/>
		
		<property name="maxIdle" value="${db.maxIdle}"/>
		
		<property name="initialSize" value="${db.initialSize}"/>
		
		<property name="maxWait" value="${db.maxWait}"/>
	bean>
	
	
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		
		<property name="dataSource" ref="dataSource">property>
		
		
		<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml">property>
	bean>
	
	
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		
		 <property name="basePackage" value="com.dsdd.weyou.mapper">property>
	bean>
	
beans>
3.3.5 applicationContext-service.xml(配置组件扫描 service)

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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-4.0.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util 
	http://www.springframework.org/schema/util/spring-util-4.0.xsd">
	
	
	<context:component-scan base-package="com.dsdd.weyou.service"/>

beans>
3.3.6 applicationContext-trans.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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-4.0.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util 
	http://www.springframework.org/schema/util/spring-util-4.0.xsd">
	
	
	<bean id="transactionManager" 
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		
		<property name="dataSource" ref="dataSource"/>
	bean>
	
	
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			
			<tx:method name="add*" propagation="REQUIRED"/>
			<tx:method name="insert*" propagation="REQUIRED"/>
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="delete*" propagation="REQUIRED"/>
			
			<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="query*" propagation="SUPPORTS" read-only="true"/>
		tx:attributes>
	tx:advice>
	
	
	<aop:config>
		
		<aop:advisor advice-ref="txAdvice" 
			pointcut="execution(* com.dsdd.weyou.service..*.*(..))"/>
	aop:config>
	
beans>
3.3.7 db.properties
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/springmvc?characterEncoding=utf-8
db.username=root
db.password=admin

db.maxActive=10
db.minIdle=2
db.maxIdle=5
db.initialSize=5
db.maxWait=6000
3.3.8 log4j.properties
# Global logging configuration
log4j.rootLogger=INFO, stdout

# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
3.3.9 web.xml(配置spring监听器 , springmvc的前端控制器 DispacherServlet)

<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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>ssmdisplay-name>
  
  
  <context-param>
  	<param-name>contextConfigLocationparam-name>
  	<param-value>classpath:spring/applicationContext-*.xmlparam-value>
  context-param>
  
  
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
  
  
  <servlet>
  	<servlet-name>ssmservlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
  	
  	
  	<init-param>
  		<param-name>contextConfigLocationparam-name>
  		<param-value>classpath:spring/springmvc.xmlparam-value>
  	init-param>
  	
  	
  	<load-on-startup>1load-on-startup>
  servlet>
  
  <servlet-mapping>
  	<servlet-name>ssmservlet-name>
  	
  	<url-pattern>*.dourl-pattern>
  servlet-mapping>
  
  
  <welcome-file-list>
    <welcome-file>index.htmlwelcome-file>
    <welcome-file>index.htmwelcome-file>
    <welcome-file>index.jspwelcome-file>
    <welcome-file>default.htmlwelcome-file>
    <welcome-file>default.htmwelcome-file>
    <welcome-file>default.jspwelcome-file>
  welcome-file-list>
web-app>

4 SpringMVC 参数绑定

4.1 默认支持的参数类型
4.1.1 HttpServletRequest

​ 通过HttpServletRequest对象,获取请求的参数 , 使用getParameter方法

4.1.2 HttpServletResponse

​ 通过response对象设置数据响应

4.1.3 HttpSession

​ 通过session对象,获取到会话中的数据

4.1.4 Model/ModelMap

​ Model是模型,用于设置响应的模型数据 ,ModelMap是Model接口的实现,使用ModelMap和使用Model是一样,如果使用Model,springmvc实例化成ModelMap ,使用Model响应模型数据,就可以不使用ModelAndView,使用字符串String响应视图。

// 使用Model设置响应模型数据,使用字符串响应视图
	@RequestMapping("/queryItemById.do")
	public String queryItemById(Model model,HttpServletRequest request){
		
		// 1.获取参数
		String id = request.getParameter("id");
		
		// 2.根据商品Id查询商品
		Item item = this.itemService.queryItemById(Integer.parseInt(id));
		
		// 3.响应商品数据
		// addAttribute方法:设置响应的模型数据
		model.addAttribute("item", item);
		
		
		return "item/itemEdit";
		
	}
4.2 基本数据和包装类型的绑定

​ 使用简单类型接收请求的参数,推荐使用简单类型的包装类型(Integer),不建议使用简单类型的基础类型(int)。原因是基础类型不能为null值,如果不传递会报异常。

​ 常用注解:@RequestParam注解 ,设置请求的参数名称,与方法形参的名称匹配 。 属性value:设置请求的参数名称 。 属性required:设置请求的参数名称是否必须要传递。true:必须要传递;false:可以传递,可以不传递。默认是true。属性defaultValue:设置参数的默认值。如果传递参数,使用实际的参数值;如果没有传递,使用默认值

4.3 pojo参数属性

​ 将传递的参数名和接收参数的类的字段名保持一致既可以接收参数 (Data数据类型 , 字符串类型乱码)

post 字符串乱码 :


  <filter>
  	<filter-name>encodingFilterfilter-name>
  	<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
  	
  	
  	<init-param>
  		<param-name>encodingparam-name>
  		<param-value>UTF-8param-value>
  	init-param>
  filter>

get 字符串乱码 :

<build>
		<finalName>ssmfinalName>
		<plugins>
			<plugin>
				<groupId>org.apache.tomcat.mavengroupId>
				<artifactId>tomcat7-maven-pluginartifactId>
				<version>2.1version>
				<configuration>
					
					<port>8080port>
					
					<path>/ssmpath>
					
					<uriEncoding>UTF-8uriEncoding>
					
					<server>tomcat7server>
				configuration>
			plugin>
		plugins>
	build>

部署阶段 字符串乱码: tomcat 安装目录下conf中的server.xml

<connector URIEncoding="UTF-8" port="8080" protocol=""/>

解决日期字符串类型问题:

  • 1 自定义日期类型转换器
// Converter 
//S,Source,源,转换之前的数据,这里是字符串类型的商品生产日期
//T,Targert,目标,转换之后的数据,这里是Date类型的日期
public class DateConverter implements Converter<String, Date> {

	/* (non-Javadoc)
	 * @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object)
	 */
	@Override
	// 实现转换逻辑
	public Date convert(String source) {
		// TODO Auto-generated method stub
		// 1.日期格式对象
		// 2016-02-03 13:22:53
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		try {
			// 转换成功,直接返回
			return format.parse(source);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 转换失败,返回null
		return null;
	}
}
  • 2 springmvc.xml 文件

<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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
        
        
        <context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
        
        
        <mvc:annotation-driven conversion-service="conversionService">mvc:annotation-driven>
        
        
        <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        	<property name="converters">
        		<set>
        			<bean class="com.dsdd.weyou.converter.DateConverter">bean>
        		set>
        	property>
        bean>
        
        
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        	
        	<property name="prefix" value="/WEB-INF/jsp/">property>
        	
        	
        	<property name="suffix" value=".jsp">property>
        bean>

beans>  
4.4 复合类型pojo的绑定
  • 接收的对象中包含了对象,例如:用户中包含有工人,传递表单对象中包含work.name!
4.5 数组类型的绑定
  • 接收的时候参数名称保持一致即可
4.6 List类型的绑定
  • 定义一个pojo,将list作为pojo的属性

    
    	
    	
    	
    	
    	
    	
        
    	
    	
    
4.7 json数据类型交互
  • pom.xml 引入json数据支持
  • jackson 依赖包

5 常用注解解析

  • @RequestParam注解 ,设置请求的参数名称,与方法形参的名称匹配 。

    • 属性value:设置请求的参数名称 。
    • 属性required:设置请求的参数名称是否必须要传递。true:必须要传递;false:可以传递,可以不传递。默认是true。
    • 属性defaultValue:设置参数的默认值。如果传递参数,使用实际的参数值;如果没有传递,使用默认值
  • @RequestMapping注解 , 设置请求的url , 限制http请求方法,在类上加上注解可以做分类管理,窄化请求

    • 属性value:一个数组,可以配置多个请求
    • 属性method:一个数组 , 可以配置多个http请求的方法
  • @RequestBady 注解 , 在处理器方法的形参上使用 , 把请求json格式的数据,转换成java对象

  • @ResponseBody注解 ,在方法的返回值上,或者方法上面使用,把响应的java对象,转换json格式的数据


6 Controller 方法返回值

  • ModelAndView

    • 用于设置响应的模型数据,用于设置响应的视图。
    • 设置数据 mav.addObject(“itemList” , itemList) ;
    • 设置视图 mav.setViewName();
  • void 返回void,使用request对象和response对象响应。

    • request 转发是原来的请求,可以获取到旧的request对象中的参数数据 ,转发浏览器的url不会发生改变,转发只能在项目内部转发,getRequestDispatcher方法:获得转发器对象 ,path参数:转发的目标url

      request.getRequestDispatcher("queryItem.do").forward(request, response);
      
    • response 重定向是产生新的请求 , 旧的request的参数数据获取不到 , 浏览器的url会变成目标的url ,可以重定向内部也可重定向外部 , sendRedirest方法,重定向

      response.sendRedirect("https://www.cnblogs.com");
      
    • response 响应数据

      response.setCharacterEncoding("utf-8");
      response.setContentType("application/json;charset=utf-8");
      response.getWriter().write("json数据");
      
  • String 返回

    • 返回响应视图
    • forward转发 return “forward:queryItem.do”;
    • redriect重定向 return “redirect:queryItem.do”;

7 异常处理

7.1 异常处理流程

​ 解析 : 请求处理流程 : 客户端(浏览器)-> 前端控制器(dispatcherServlet)->表现层(controller)->业务层(service)->持久层(dao)

​ 解决方案 : 从dao开始,每一层发生异常,都向上一层抛出,一直抛到前端控制器,前端控制器需要调用异常处理器包装异常,返回一个友好的提示页面给用户。

![img](file:///C:\Users\Administrator\AppData\Local\Temp\ksohtml\wps6C4C.tmp.png)

​ 自定义异常处理系统 : 处理步骤

  • 1 自定义异常类继承异常Exception
public class SsmException extends Exception {
	
	// 异常消息
	private String message;
	
	/**
	 * 
	 */
	public SsmException() {
		super();
	}

	/**
	 * @param message
	 */
	public SsmException(String message) {
		super();
		this.message = message;
	}

	/**
	 * @return the message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message the message to set
	 */
	public void setMessage(String message) {
		this.message = message;
	}

}
  • 2 自定义异常处理器
public class SsmExceptionResolver implements HandlerExceptionResolver {

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerExceptionResolver#resolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		// TODO Auto-generated method stub
		// 包装异常
		// 定义系统异常
		SsmException sse = null;
		
		// 判断是否是系统异常
		if(ex instanceof SsmException){
			sse = (SsmException) ex;
		}else{
			// 创建一个未知异常
			sse = new SsmException("未知异常!");
		}
		
		// 创建ModelAndView对象
		ModelAndView mav = new ModelAndView();
		mav.addObject("message", sse.getMessage());
		
		mav.setViewName("error/error");
		
		return mav;
	}

}
  • 3 在springmvc.xml文件,配置异常处理器

<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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
        
        
        <context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
        
        
        <mvc:annotation-driven conversion-service="conversionService">mvc:annotation-driven>
        
        
        <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        	<property name="converters">
        		<set>
        			<bean class="com.dsdd.weyou.converter.DateConverter">bean>
        		set>
        	property>
        bean>
        
        
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        	
        	<property name="prefix" value="/WEB-INF/jsp/">property>
        	
        	
        	<property name="suffix" value=".jsp">property>
        bean>
        
        
        <bean class="com.dsdd.weyou.exception.SsmExceptionResolver">bean>

beans>  
  • 4 测试异常信息
// 使用简单类型Integer,接收请求的商品参数id
	// 形参id的名称,要与请求参数的名称一致
	@RequestMapping("/queryItemById.do")
	public String queryItemById(Model model,Integer id) throws SsmException{

		// 1.根据商品Id查询商品
		Item item = this.itemService.queryItemById(id);
		
		// 增加异常测试======================start
		if(item == null){
			throw new SsmException("商品不存在!");
		}
		
		// 测试运行时异常
		//int i = 1/0;
		// 增加异常测试======================end
		// 2.响应商品数据
		// addAttribute方法:设置响应的模型数据
		model.addAttribute("item", item);
		
		return "item/itemEdit";
		
	}

8 Strusts 2 与SpringMVC

区别 :

8.1 前端控制器不一样 。
  • 1 spring MVC 前端控制器servlet(DispatcherServlet) , Struts2前端控制器flter(StrutsPrePareAndExecutorFilter)
8.2 请求参数的接收方式不一样。
  • 1 springmvc是使用处理器方法的形参来接收请求的参数,是基于方法的开发,线程安全,可以设计为单例或者多例模式开发,推荐使用单例模式开发(执行效率更高),默认就是单例模式。
  • 2 struts2是使用类成员变量接收请求的参数数据,是基于类的开发,线程不安全,只能设计为多例模式开发。
8.3 spring mvc框架是spring一部分,不需要整合。

9 拦截器

9.1 拦截器介绍

​ 拦截器相当于servlet中过滤器,可以对处理器方法执行预处理(在处理器方法执行前执行);对处理器方法执行后处理(在处理器方法执行后执行)。自定义拦截器需要实现接口(HandlerInterceptor)接口

  • 1 自定义拦截器
public class FirstInterceptor implements HandlerInterceptor {

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("FirstInterceptor--preHandle方法执行中......");
		
		return true;
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
	 */
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("FirstInterceptor--postHandle方法执行中......");
		
		modelAndView.addObject("message", "我是postHandle方法......");

	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("FirstInterceptor--afterCompletion方法执行中......");

	}

}
  • 2 配置拦截器
  
  <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:mvc="http://www.springframework.org/schema/mvc"
  	xsi:schemaLocation="http://www.springframework.org/schema/beans 
  	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
          http://www.springframework.org/schema/mvc 
          http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
          http://www.springframework.org/schema/context 
          http://www.springframework.org/schema/context/spring-context-4.0.xsd">
          
          
          <context:component-scan base-package="com.dsdd.weyou.controller">context:component-scan>
          
          
          <mvc:annotation-driven conversion-service="conversionService">mvc:annotation-driven>
          
          
          <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
          	<property name="converters">
          		<set>
          			<bean class="com.dsdd.weyou.converter.DateConverter">bean>
          		set>
          	property>
          bean>
          
          
          <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          	
          	<property name="prefix" value="/WEB-INF/jsp/">property>
          	
          	
          	<property name="suffix" value=".jsp">property>
          bean>
          
          
          <bean class="com.dsdd.weyou.exception.SsmExceptionResolver">bean>
          
          
          <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
          	
   			
   			
   			<property name="maxUploadSize" value="10485760">property>
   			
   			
   			<property name="maxInMemorySize" value="4096">property>
   			
   			
   			<property name="defaultEncoding" value="UTF-8">property>
          bean>
          
          
          <mvc:interceptors>
          	
          	<mvc:interceptor>
          		
          		<mvc:mapping path="/interceptor.do"/>
          		
          		<bean class="com.dsdd.weyou.interceptor.FirstInterceptor">bean>
          	mvc:interceptor>
          	
          mvc:interceptors>
  
  beans>  
  • 3 测试拦截器
// 拦截器讲解专用
	@RequestMapping("/interceptor.do")
	public String testInterceptor(Model model){
		
		System.out.println("ItemController--testInterceptor方法执行中......");
		
		model.addAttribute("message1", "我是处理器testInterceptor方法......");
		
		return "inter/interceptor";
		
	}
  • 使用场景

    ​ preHandle方法:在处理器方法执行前执行,在jsp响应前执行。执行预处理,返回布尔类型值,返回true继续执行;返回false,终止执行。在企业项目中,通常在这个方法执行用户登录校验,权限菜单校验业务功能。

    ​ postHandle方法:在处理器方法执行后,在jsp响应前执行。执行后处理。在企业项目中,通常在这个方法执行公共的模型数据设置,比如页面的头部信息,尾部信息。

    ​ afterCompletion方法:在处理器方法执行后,在jsp页面响应后执行。执行后处理。在企业项目中,通常在这个方法执行操作日志的记录。

你可能感兴趣的:(框架知识总结)