不得不承认好记性不如烂笔头,在SpringMvc我当时用得比较的好,但是现在感觉挺陌生的,准备一点一点的整理一下,Spring的入门案例中,有讲解Spring的一些基本配置,以及SpringMvc基于注解和配置文件两种方式进行添加Servlet,基于xml配置的方式,没有通过注解的方式灵活

Spring访问流程

官方的讲解
SpringMvc之入门案例-yellowcong_spring mvc

案例

目录结构

SpringMvc之入门案例-yellowcong_其他_02

pom.xml配置

pom配置文件中,需要导入Spring Mvc和Spring的配置文件,对于JSON和Junit的包,在入门案例中,没有用到,可以不用导入。

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>yellowcong</groupId>
    <artifactId>day11_13</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>day11_13 Maven Webapp</name>
    <url>http://maven.apache.org</url>


    <!-- 配置国内比较快的 阿里云的Maven仓库 -->
    <repositories>
        <repository>
            <id>aliyunmaven</id>
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
        </repository>
    </repositories>

    <!-- 共用的配置说明,比如spring版本, 项目名称, jdk版本等 -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.2.5.RELEASE</spring.version>
    </properties>

    <dependencies>
        <!-- Spring  BEGIN-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- 导入Spring的orm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Slf4j -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <!-- 配置切面 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!---aspectj 面向切向 -->
        <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.5</version>
        </dependency>
        <!-- Spring需要的注解 -->
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- Spring 的测试类 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Spring  END-->

        <!-- 配置Spring mvc -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- 文件上传 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>

        <!-- JSON解析 -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.11</version>
        </dependency>

        <!-- 日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>day11_13</finalName>
    </build>
</project>

web.xml配置文件

这个web.xml配置文件里面,配置了Spring容器和SpringMvc的视图控制器,也就是Springmvc的入口DispatcherServlet

<?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"
    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>demo</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!-- Spring mvc -->
    <servlet>
        <servlet-name>config</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置Spring mvc,如果不配置,就会默认在wWEB-INF/config-servlet.xml -->
        <init-param>
            <description>spring mvc 配置文件</description>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>config</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- 设定字符编码 -->
    <filter>
        <filter-name>CharacterFilter</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>
    </filter>
    <filter-mapping>
        <filter-name>CharacterFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- spring的监听器,可以通过上下文来获取参数 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>
</web-app>

spring.xml配置文件

spring配置是必须配置的,不然,我们的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" 
    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/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    ">
    <!-- 自动扫描(自动注入) -->
    <context:annotation-config/>
    <context:component-scan base-package="com.yellowcong.*"/>

    <!--导入mybatis的配置-->
    <!-- <import resource="spring-mybatis.xml"/>
    <import resource="spring-shiro.xml"/> -->
</beans>

基于注解的方式

spring-mvc.xml 配置文件

这个文件是SpringMvc的核心文件,所有的配置都走这个配置文件,这个地方,我是基于注解的方式

<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    <mvc:default-servlet-handler/>
    <!-- 通过Annotation 来控制Controller -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <context:component-scan base-package="com.yellowcong"></context:component-scan>

    <!-- 将静态文件夹制定到某个特别的文件夹中统一处理
        ** 表示的是文件夹中的子文件夹中的所有类容
        其中location 需要两个 正斜杠
     -->
    <mvc:resources location="/resources/" mapping="/resources/**"/>
        <!-- 配置权限拦截器 -->
        <!-- 当我们的数据访问到 amdin的时候,就会直接调用admin对象 -->
 <!--   <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/user/**"/>
            <mvc:mapping path="/role/**"/>
            <mvc:mapping path="/group/**"/>
            <mvc:mapping path="/attachment/**"/>
            <mvc:mapping path="/reply/**"/>
            <mvc:mapping path="/tabel/**"/>
            <mvc:mapping path="/image/**"/>
            <mvc:mapping path="/info/**"/>
            <mvc:mapping path="/login/stu"/>
            <mvc:mapping path="/admin/**"/>
            <bean class="com.yellowcong.interceptor.UserInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>  --> 
    <!-- 设定访问的名称 和对应的Servlet -->    
    <!-- 配置Multipart,只有设定了才能完成文件上传 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000"></property>
    </bean>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 3.0.5后默认加上了jstl的属性配置.这个就是默认的配置 -->
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
        <!-- 设定前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!-- 设定后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 配置全局异常 -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
            <!-- 
                <prop key="com.yellowcong.exception.UserException">error</prop>
                <prop key="java.lang.RuntimeExceptio">error</prop>
             -->
            </props>
        </property>
    </bean>
</beans>

控制器

这个里面,我使用的是ModelView进行参数的传递,参数传递到界面的方式
1、Map(Map集合,方式)
2、Model (只装参数,返回 String类型)
3、ModelView (Spring Mvc ,包含了视图和参数)
4、HttpServletResponse 直接写到浏览器

package com.yellowcong.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author yellowcong
 */
@Controller
@RequestMapping("/demo")
public class Demo {

    @RequestMapping(value="/index",method=RequestMethod.GET)
    public ModelAndView index(){

        ModelAndView view = new ModelAndView();
        view.setViewName("demo/index");
        view.addObject("name", "doubi");

        return view;
    }

}

jsp视图

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<title>xx文章</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
</head>
<body>
<h2>Hello World!${name}</h2>
</body>
</html>

访问结果
SpringMvc之入门案例-yellowcong_spring mvc_03

基于xml配置文件的方式

基于xml的方式,需要在Spring-mvc.xml配置文件中配置控制器(Controller),控制器需要继承AbstractController,实现里面的handleRequestInternal方法,这种方式没有主机灵活

Spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    <mvc:default-servlet-handler/>

    <!--访问的时候,会访问 我们的com.yellowcong.controller 中的对应的类 
    这是基于配置文件的方式
    -->
    <bean name="/demo/demo2" class="com.yellowcong.controller.Demo2Controller"></bean>

    <!-- 将静态文件夹制定到某个特别的文件夹中统一处理
        ** 表示的是文件夹中的子文件夹中的所有类容
        其中location 需要两个 正斜杠
     -->
    <mvc:resources location="/resources/" mapping="/resources/**"/>
        <!-- 配置权限拦截器 -->
        <!-- 当我们的数据访问到 amdin的时候,就会直接调用admin对象 -->
 <!--   <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/user/**"/>
            <mvc:mapping path="/role/**"/>
            <mvc:mapping path="/group/**"/>
            <mvc:mapping path="/attachment/**"/>
            <mvc:mapping path="/reply/**"/>
            <mvc:mapping path="/tabel/**"/>
            <mvc:mapping path="/image/**"/>
            <mvc:mapping path="/info/**"/>
            <mvc:mapping path="/login/stu"/>
            <mvc:mapping path="/admin/**"/>
            <bean class="com.yellowcong.interceptor.UserInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>  --> 
    <!-- 设定访问的名称 和对应的Servlet -->    
    <!-- 配置Multipart,只有设定了才能完成文件上传 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000"></property>
    </bean>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 3.0.5后默认加上了jstl的属性配置.这个就是默认的配置 -->
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
        <!-- 设定前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!-- 设定后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 配置全局异常 -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
            <!-- 
                <prop key="com.yellowcong.exception.UserException">error</prop>
                <prop key="java.lang.RuntimeExceptio">error</prop>
             -->
            </props>
        </property>
    </bean>
</beans>

控制器

控制器需要继承AbstractController 类,并实现方法handleRequestInternal,这种方式有点像struts的方式

package com.yellowcong.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

//其中这个继承的是AbstractController   Servlet
//这个类似于Struts 中的 Action
public class Demo2Controller extends AbstractController {

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ModelAndView view = new ModelAndView("demo/index");
        view.addObject("name", "AbstractController");
        return view;
    }

}

jsp视图

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<title>xx文章</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
</head>
<body>
<h2>Hello World!${name}</h2>
</body>
</html>

访问结果
SpringMvc之入门案例-yellowcong_spring mvc_04