【spring springmvc】springmvc使用注解声明控制器与请求映射

概述

注解: 在Spring中尽管使用XML配置文件可以实现Bean的装配工作,但如果应用中Bean的数量较多,会导致XML配置文件过于臃肿,从而给维护和升级带来一定的困难。
从JDK 5开始提供了名为Annotation(注解)的功能,Spring正是利用这一特性,Spring逐步完善对Annotation注解技术的全面支持,使XML配置文件不再臃肿,向“零配置”迈进。

Spring框架也为表示层提供了一个优秀的Web框架,即Spring MVC。由于Spring MVC采用了松耦合可插拔组件结构,比其他MVC框架具有更大的扩展性和灵活性。通过注解,Spring MVC使得POJO成为处理用户请求的控制器,无需实现任何接口。

壹:注解说明

Spring中定义了一系列的Annotation注解,如下所示:

注解名称 说明
@Component注解 @Component 是一个泛化的概念,仅仅表示一个组件(Bean),可以作用在任何层次。
@Repository注解 @Repository 注解用于将数据访问层(DAO 层)的类标识为Spring的Bean。
@Service注解 @Service 通常作用在业务层,但是目前该功能与@Component相同。
@Controller注解 @Controller标识表示层组件,但是目前该功能与@Component相同
@Autowired注解 用于对Bean的属性变量、属性的set方法及构造函数进行标注,配合对应的注解处理器完成Bean的自动配置工作。@Autowired注解默认按照Bean类型进行装配。@Autowired注解加上@Qualifier注解,可直接指定一个Bean实例名称来进行装配。
@Resource注解 作用相当于@Autowired,配置对应的注解处理器完成Bean的自动配置工作。区别在于:①:@Autowired默认按照Bean类型进行装配,②:@Resource默认按照Bean实例名称进行装配。

贰:实现注解声明控制器与请求映射

一:使用controller

org.springframework.stereotype.Controller注解类型用于指示Spring类的实例是一个控制器,其注解形式为@Controller。该注解在使用时不需要再实现Controller接口,只需要将@Controller注解加入到控制器类上,然后通过Spring的扫描机制找到标注了该注解的控制器即可。

@Controller
public class SpringController {
    @GetMapping("/helloWorld")
    public String hello(){
        System.out.println("hello.....");
        return "hello";
    }
}

我们常用的rest 风格请求(REST : 即 Representational State Transfer 。(资源)表现层状态转化):

请求 说明 用于
@GetMapping 匹配GET方式的请求; 一般读取数据
@PostMapping 匹配POST方式的请求; 一般用于插入数据
@PutMapping 匹配PUT方式的请求; 一般用于更新数据
@DeleteMapping 匹配DELETE方式的请求; 一般用于删除数据

二:配置包扫描与视图解析器

1、配置包扫描

虽然哦我们已经i邪恶好了controller,但是直接这样写我们是不能用的,还需要在spring-mvc.xml配置文件中,用spring的包扫描将他注入到容器中,我们才能实现调用。

    <!--使用扫描机制 -->
    <context:annotation-config/>
    <context:component-scan base-package="com.lomtom.controller"/>
    当然,spring提供了很多种方法,我们是用最简单实现的就可以。

2、配置试图解析器

SpringMVC中的视图解析器的主要作用就是将逻辑视图转换成用户可以看到的物理视图。
spring-mvc.xml加入试图解析器,其中的前缀就是根据自己的文件存放目录来写,后缀就是你的文件的后缀名,你可以是.jsp、.html等等。

    <!--    配置视图解析器 prefix:前缀, suffix:后缀-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".html"></property>
    </bean>

三:配置部署描述符

Deployment Descriptors(描述符)是一个xml文件,用来描述如何部署一个模块或者应用(根据描述符中定义的配置和容器选项)。
在这里简单来说就是我们的web.xml

1、读取spring-mvc.xml文件

虽然,我们已经把controller通过spring-mvc.xml注入到容器中,相信这时你启动项目时,是访问不了的controller的请求的,也就是说,我们的我没在配置该文件,这时候在你的web.xml中加入。

如果我们不指定SpringMVC配置文件的路径,则会自动到WEB-INF下找 ‘‘前端控制器名-servlet.xml’’ 这个文件,如果找不到则会报错。

    <!--    配置Spring MVC配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>

2、配置匹配映射

servlet: 它提供静态资源。它处理所有未映射到其他带有servlet映射的servlet(在这里或在您自己的-web.xml文件)。

servlet-mapping: 当为静态资源提供服务时,Tomcat将自动生成基于资源文件扩展名的“Content Type”头,基于这些映射。可以在此处添加其他映射(到应用于所有web应用程序),或在您自己的应用程序的web.xml中部署描述符。

<!-- 配置DispatcherServlet -->
<servlet>
   <servlet-name>dispatcherServlet</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 </servlet>
 
 <!-- ServLet 匹配映射 -->
 <servlet-mapping>
   <servlet-name>dispatcherServlet</servlet-name>
   <url-pattern>/</url-pattern>
 </servlet-mapping>

四:建立html文件

新建两个文件,用于访问测试,一个index.html,写一个连接指向href=“helloWorld”,写另一个hello.html,用于访问成功后,跳转到该页面。

叁:配置tomcat

在这里,作者摸索到了两种配置tomcat的方法,一种就是本地自个的tomcat,还有一种就是maven提供的tomcat容器。

一:配置本地tomcat

基本上就是这几步,其中的选择tomcat目录省略了,不是很难,添加服务就可以,找不到入口就算了,请不要打我。如果你配置tomcat也不会,那么,现在放下电脑去打把王者荣耀吧,妲己可能会告诉你。


tomcat

二:配置maven内置tomcat

配置maven的tomcat相对会麻烦一点,不过也不是很麻烦,在你的pom.xml文件中加入一下插件依赖。

<plugins>
    <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
    </plugin>
</plugins>

然后,添加配置,需要注意的是,你需要配置你的maven,在下图的General里面,如果你已经使用了maven,就不用配了,可以查看General下配置是否正确。
安装与配置maven:传送门

maven-tomcat

接下来你就可以启动你的项目了,祝你能够一步成功,哈哈哈哈。

肆:结果及问题

一:tomcat启动示意图:

本地tomcat:


image

maven内置tomcat:


image

二:结果

首页:
首页

死案及后跳转:


hello

三:问题

1、解决SpringMVC不能访问html页面

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>

2、使用maven内置tomcat有时能跳转,有时不能跳转,不能跳转的时候他会卡在读取文件这里,这里对不起了,笔者没找到解决方法,如果你找到了,欢迎告诉笔者。

三月 21, 2020 1:02:09 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring-mvc.xml]

该问题追加:

根据csdn评论中大佬的解决方法,我重新试了一下,后来发现问题根源,发现项目根本找不到spring-context.xsd,导致spring-mvc.xml文件加载出错,并且造成通配符的匹配很全面, 但无法找到元素 'context:annotation-config' 的声明的错误,所以项目一直在加载spring-mvc.xml文件,这时我就意识到是我的spring-mvc.xml中的引入出问题了,经过修改,问题解决了。

修改前:
https://www.springframework.org/schema/context/spring-context.xsd
修改后:
http://www.springframework.org/schema/context/spring-context.xsd

伍:结构及源码

源码都放出来了,还不是ctrl+c,ctrl+v一顿乱搞。

一:目录结构

目录结构

二:源码

1、controller

package com.lomtom.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * @Author: LOMTOM
 * @Date: 2020/3/20
 * @Time: 18:40
 * @Email: lomtom@qq.com
 */
@Controller
public class SpringController {
    @GetMapping("/helloWorld")
    public String hello(){
        System.out.println("hello.....");
        return "hello";
    }
}

2、spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">

    <mvc:annotation-driven/>

    <!--使用扫描机制 -->
    <context:annotation-config/>
    <context:component-scan base-package="com.lomtom.controller"/>

    <!--    配置视图解析器 prefix:前缀, suffix:后缀-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".html"></property>
    </bean>
</beans>

3、web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <!-- 配置DispatcherServlet -->
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <!-- 指定spring mvc配置文件位置 不指定使用默认情况 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
  </servlet>
  <!-- ServLet 匹配映射 -->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
</web-app>

4、pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<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">
    <parent>
        <artifactId>spring</artifactId>
        <groupId>spring</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-8</artifactId>
    <packaging>war</packaging>

    <name>spring-8 Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.1.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>spring-8</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

5、html

1、index.html
<html>
<body>
<h2>Hello World!</h2>
<a href="helloWorld">hello</a>
</body>
</html>


2、hello.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>
<h2>你好啊,你成功了</h2>
</body>
</html>

作者有话

这篇文章,作者已经肝了很久了,如果对你有用的话,点个赞再走吧,不说了,作者要交作业去了。

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

推荐阅读更多精彩内容