10 Spring MVC 的一次访问(基础入门篇)

转载请注明来源 赖赖的博客

导语

了解一下起因经过,你才能明白世事的真正含义。

Spring的基础都了解了一些,这一篇就来看看Spring应用MVC会是怎么样的吧,轻松简单,本章讲述的是一次访问开始到返回Spring MVC是如何应对的(基础版)

实例

项目工程目录结构和代码获取地址

获取地址(版本Log将会注明每一个版本对应的课程)

https://github.com/laiyijie/SpringLearning

目录结构

目录结构

如图所示,虽然目录结构看起来复杂了一些(就是文件夹深度深了一点儿而已),其实最源文件只有四个。所以不要紧张,这非常简单

运行工程

运行方式
  • 右键整个项目
  • Run as
  • Run On Server
  • 选择STS默认的 Pivotal Server(有tomcat也一样)并确认
  • 在浏览器里输入 http://localhost:8080/demo/hi (demo是工程的名称,依照你的来替换)
运行结果
运行结果

我用的是 chrome浏览器,输出了hello

OK,这次从浏览器输入这个链接到返回这个hello来讲解!

项目详解

我们不妨直接找找这个输出的 hello来自哪一段代码

UserController.java

package me.laiyijie.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
    
    @RequestMapping("/hi")
    @ResponseBody
    public String hello(){
        return "hello";
    }
    
}

是不是很短,简洁明了!

我们一眼看到的就是 hello!没错,就是这个函数里面处理了刚才的请求,并且返回了一个hello的字符串!
这里有三个注解含义分别如下:

  • @Controller 将一个类变成一个特殊的java bean作为控制器使用,可以认为是特殊的@Service
  • @RequestMapping 这里面就是针对URL的控制,我们可以看到访问的URL/demo为项目名称,而/hi就代表的是访问由这个函数来控制!
  • @ResponseBody 将hello这个字符串直接返回给浏览器(不增加这个注解的情况下是返回一个对应的jsp页面-例如hello.jsp)

进入到/demo以后是由@RequestMapping控制这个访问,那么一个访问是怎么被引到如到demo这个工程中的呢?Spring Context又是怎么生效的呢?(我们并没有用new ClassPathXmlApplicationContext("root-context.xml");来初始化一个Spring Context,为何注解就用了起来?)

浏览器中输入 http://localhost:8080/demo/hi 并访问

  • 浏览器访问 localhost8080 端口
  • localhost的8080端口由Pivotal Server(或者tomcat,刚才你运行的时候开启的一个程序)监听
  • Server 接收到浏览器的请求并查看到路径为/demo,转交到demo工程来管理
  • 访问进入demo 这个工程后会先根据 web.xml 来确认入口是哪儿(这是tomcat等web容器一个通用的标准)

那让我们详细看一下web.xml是怎样的!

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
                http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee">

    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
</web-app>

如果你不熟悉web.xml的配置,也请不要紧张,因为这部分的配置已经非常成熟,一次配置完毕会很少改动,即使你不太了解也不会影响你的使用,这里摆出只是为了让你了解一个访问是如何进入Spring MVC进行管理的。

我们看关键一点:

<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>  

这里载入了一个配置文件,这个配置文件的名称是 servlet-context.xml 这么熟悉的名称,正是SpringContext的配置文件!

是的,正是通过web.xml我们初始化了一个SpringContext,也就是tomcat(或者Pivotal Server)帮助我们初始化了这个SpringContext代替掉我们再main函数中使用的:

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("root-context.xml"); 

Spring 容器初始化完毕,访问完全转入Spring MVC 中由我们进行控制!

为了让注解生效必然要配置一下 servlet-context.xml

servlet-context.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"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.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-4.3.xsd">


    <context:component-scan base-package="me.laiyijie.demo" />

    <mvc:annotation-driven />

    <bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"
        p:messageConverters-ref="stringHttpMessageConverter" />

    <bean id="stringHttpMessageConverter"
        class="org.springframework.http.converter.StringHttpMessageConverter" />

</beans>

重点只有四句话:

  • 开启注解,扫描所有注解的组件(使得@Controller可以被实例化)

<context:component-scan base-package="me.laiyijie.demo" />

  • 开启mvc注解驱动,使得@RequestMapping有效

<mvc:annotation-driven />

  • 最后两句配置适配器使得返回的hello正常输出

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.0</modelVersion>

    <groupId>me.laiyijie</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
    </properties>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

依赖新增一个:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency> 

小结:

输入 http://localhost:8080/demo/hi 访问全程:

  • 访问 localhost服务器的8080端口
  • 服务器监听8080端口的webserver接收到请求
  • 通过URL发现请求应该转入/demo这个工程处理
  • 请求通过标准配置web.xml确认了接受请求的程序为 appServelet
  • appServelet启动了一个由servlet-context.xml配置的Spring Context
  • servlet-context.xml配置了由注解驱动,也就是通过@RequestMapping来确认访问应该分配到哪儿
  • UserController 中的 hello方法配置了@RequestMapping("/hi") 也就是说,该请求由这个函数处理,函数处理请求完毕返回hello,hello这个字符串通过servlet-context.xml中配置的转换器转换后输出到浏览器
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,367评论 6 343
  • 1、Spring MVC请求流程 (1)初始化:(对DispatcherServlet和ContextLoderL...
    拾壹北阅读 1,916评论 0 12
  • spring官方文档:http://docs.spring.io/spring/docs/current/spri...
    牛马风情阅读 1,580评论 0 3
  • 1 (2005年,一个人徒步山西内长城) 终于看过了鞠庆的《一个人走》,文字很漂亮,尤其是这样一个小女人,小小的身...
    bb8681647e6c阅读 176评论 0 0