1.以前搭建Spring MVC 框架一般都使用配置文件的方式进行,相对比较繁琐。spring 提供了使用注解方式搭建Spring MVC 框架的方式,方便简洁。使用Spring IOC 作为根容器管理service、dao、datasource,使用spring MVC 容器作为子容器管理controller、视图解析器

spring 官方文档中有相关示例

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {@Overrideprotected Class<?>[] getRootConfigClasses() {return new Class<?>[] { RootConfig.class };}@Overrideprotected Class<?>[] getServletConfigClasses() {return new Class<?>[] { App1Config.class };}@Overrideprotected String[] getServletMappings() {return new String[] { "/app1/*" };}
}

使用继承 AbstractAnnotationConfigDispatcherServletInitializer 的方式创建启动类,其中 getRootConfigClasses 指定父容器的配置类,相当于在web.xml 配置文件中配置监听器加载spring的配置文件,getServletConfigClasses指定spring MVC 的配置文件,相当于在web.xml配置DispatcherServlet,getServletMappings 执行拦截路径。

2.首先创建一个Maven 工程,packaging 为war类型,并在插件中指定忽略web.xml,否则会报错

<build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-war-plugin</artifactId><version>3.1.0</version><configuration><failOnMissingWebXml>false</failOnMissingWebXml></configuration></plugin></plugins></build>

3.创建spring IOC 的配置类,管理除了Controller 以外的组件

package com.spring.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.stereotype.Controller;/*** spring 配置文件,构建父容器,扫描service、dao 等,但是controller交给spring mvc 来管理* @author Administrator**/
@ComponentScan(value="com.spring",excludeFilters= {@Filter(type=FilterType.ANNOTATION,classes= {Controller.class})
})
public class SpringContextConfig {}

4.创建Spring MVC 配置类,管理Controller,注意此时需要关闭compentscan 默认的扫描规则,否则会扫描到所有的组件。这样这个容器的就形成了一种互补关系。

@ComponentScan(value = "com.spring",includeFilters= {@Filter(type = FilterType.ANNOTATION,classes= {Controller.class})
},useDefaultFilters=false)
public class AppConfig extends WebMvcConfigurerAdapter{}

5.创建初始化类,指定两个容器的配置类,并指定拦截路径

package com.spring;import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;import com.spring.config.AppConfig;
import com.spring.config.SpringContextConfig;public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {//获取父容器的配置文件(spring IOC ,类似于spring 配置文件)
    @Overrideprotected Class<?>[] getRootConfigClasses() {// TODO Auto-generated method stubreturn new Class<?>[] {SpringContextConfig.class};}//获取父容器的配置文件(springMVC IOC ,类似于spring MVC  配置文件,获取DispatcherServlet)
    @Overrideprotected Class<?>[] getServletConfigClasses() {// TODO Auto-generated method stubreturn new Class<?>[] {AppConfig.class};}//获取DispatcherServlet 的映射路径
    @Overrideprotected String[] getServletMappings() {// TODO Auto-generated method stubreturn new String[]{"/"};}}

6.编写测试controller ,services,启动并测试

package com.spring.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import com.spring.service.HelloService;@Controller
public class HelloController {@AutowiredHelloService helloService;@ResponseBody@RequestMapping("/hello")public String sayHello() {String sayHello = helloService.sayHello("World");return sayHello;}}

7.之前采用配置文件的方式,我们可以需要在spring MVC 的配置文件中使用 <mvc:annotation-driven/> 去开始MVC 配置,并且配置如视图解析器,拦截器等组件,在采用注解方式后同样可以完成在配置文件中完成的东西,官方文档中给出的示例,需要我们编写一个配置类,然后开启mvc注解,实现 WebMvcConfigurer  接口,这个接口定义了一系列方法对应 在spring MVC 配置文件中配置组件的方法。

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {// Implement configuration methods...
}

8.直接在spring MVC 容器的配置类似,实现以上功能,并配视图解析器,静态资源拦截,添加拦截器等。WebMvcConfigurerAdapter 这个抽象类实现了 WebMvcConfigurer ,我们直接继承它,从而避免去挨个实现 WebMvcConfigurer 里面所有的方法

package com.spring.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import com.spring.intercepter.MyIntercepter;/*** Spring mvc 配置文件,只扫描Controller* @author Administrator**/
@ComponentScan(value = "com.spring",includeFilters= {@Filter(type = FilterType.ANNOTATION,classes= {Controller.class})
},useDefaultFilters=false)
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter{@Overridepublic void configureViewResolvers(ViewResolverRegistry registry) {registry.jsp("/WEB-INF/views/", ".jsp");}@Overridepublic void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {configurer.enable();}@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new  MyIntercepter()).addPathPatterns("/**");}
}

下面是自定义的拦截器

package com.spring.intercepter;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;public class MyIntercepter implements HandlerInterceptor{public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {System.out.println("----------目标方法执行前-------------");return true;}public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {System.out.println("----------目标方法执行后-------------");}public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {System.out.println("----------页面响应前-------------");}}

测试controller 如下:

package com.spring.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import com.spring.service.HelloService;@Controller
public class HelloController {@AutowiredHelloService helloService;@ResponseBody@RequestMapping("/hello")public String sayHello() {String sayHello = helloService.sayHello("World");return sayHello;}@RequestMapping("/helloworld")public String helloWorld() {return "hello";}
}

测试结果如下,成功跳转到jsp,并且显示了图片,拦截器也做了相应的输出

至此基本完成Spring MVC 注解版搭建,其余的功能组件可以在通过编写配置类的方式进行注册。

转载于:https://www.cnblogs.com/li-zhi-long/p/10641755.html

使用注解方式搭建SpringMVC相关推荐

  1. JAVA配置注解方式搭建简单的SpringMVC前后台交互系统

    前面两篇文章介绍了 基于XML方式搭建SpringMVC前后台交互系统的方法,博文链接如下: http://www.cnblogs.com/hunterCecil/p/8252060.html htt ...

  2. SpringBoot+Mybatis 框架之 @Select注解方式搭建

    最近两天在帮同学搭建SpringBoot框架,我以往使用的是xml映射文件的方式,这次我的同学要我使用@Select注解的方式搭建的一次.感觉挺有意思的,分享给大家. 1.创建SpringBoot项目 ...

  3. mysql selectprovider_SpringBoot+Mybatis 框架之 @SelectProvider注解方式搭建

    之前搭建了@Select标签来做SringBoot+Mybatis的集成.这次使用@SelectProvider标签的方式搭建一次. 一.搭建SpringBoot的项目 https://start.s ...

  4. SpringBoot+Mybatis 框架之 @SelectProvider注解方式搭建

    之前搭建了@Select标签来做SringBoot+Mybatis的集成.这次使用@SelectProvider标签的方式搭建一次. 一.搭建SpringBoot的项目 https://start.s ...

  5. SpringMVC学习(二)——快速搭建SpringMVC开发环境(注解方式)

    文章目录 说明 1.工程搭建 2.注解配置 2.1.context:annotation-config说明 2.2.context:component-scan配置说明 2.3.mvc:annotat ...

  6. 零配置简单搭建SpringMVC 项目

    SpringMVC是比较常用的JavaWeb框架,非常轻便强悍,能简化Web开发,大大提高开发效率,在各种Web程序中广泛应用.本文采用Java Config的方式搭建SpringMVC项目,并对Sp ...

  7. SSM整合之纯注解方式,注解实现事务,异常,与拦截器

    SSM整合之纯注解方式Spring,SpringMVC,Mybatis 使用纯注解的方式,整合ssm, sql语句与数据表 在上一篇SSM整合之XML方式中有, 创建maven项目(代码中注释为详细解 ...

  8. SpringMVC学习(一)——快速搭建SpringMVC开发环境(非注解方式)

    目录 1.开发环境准备 1.1.首先电脑需要安装JDK环境(略) 1.2.准备一个以供开发的tomcat 1.3.准备Maven工具 1.4.准备IDE编译器 1.5.准备一个本地的数据库, 2.搭建 ...

  9. SpringMVC全注解环境搭建

    源代码: 链接:https://pan.baidu.com/s/1Lxb-riH–YQNIy3c0i8pFA 提取码:y3aq 文档地址:https://shphuang_aliyun.gitee.i ...

  10. 搭建 springMVC 框架

    搭建的框架是包含 common(bean),data(DAO层),service层和controller层. 如下: common(bean),data(DAO层),service和controlle ...

最新文章

  1. 学习python需要什么基础-学习python需要什么基础吗?老男孩Python
  2. quick-cocos2d-x开发环境Lua for IntelliJ IDEA的安装
  3. 在路由器使用ACL防止IP地址欺骗
  4. VTK:IO之GLTFImporter
  5. 【Java】split()和java.util.StringTokenizer分割字符串的性能比较
  6. 【Flink】Flink Kafka 消费卡死 消费组卡死 topic无写入 实际有数据 topic正常
  7. SPSS统计功能与模块对照表
  8. java createcustomcursor,CustomCursor插件:自定义你的鼠标光标
  9. ArcGIS三种方式打断相交线------拓扑法
  10. 用友文件服务器设置,u8文件服务器如何设置
  11. HDFS教程(06)- HDFS纠删码
  12. 下拉列表dropdown取消默认点击隐藏及修复需要二次点击的方法
  13. 眼图观测实验报告_通信原理实验报告 -
  14. 我对八种常见数据结构的理解
  15. Vue + TypeScript + Element 搭建简洁时尚的博客网站及踩坑记
  16. 阿里数据中台演进四个阶段
  17. 高速公路ETC卡签之我见1-概述
  18. procmon符号配置
  19. SaaS二月寒冬、传统IT厂商逆袭与重新定义云计算
  20. C# - Entity Framework 对一个或多个实体的验证失败。有关详细信息,请参阅“EntityValidationErrors”属性

热门文章

  1. 理解 position:relative 与 position:absolute
  2. R语言data manipulation学习笔记之创建变量、重命名、数据融合
  3. 9、kubernetes之statefulset控制器
  4. 安装mysql-server之后,root用户不能登录问题
  5. leetcode 617. 合并二叉树(Merge Two Binary Trees)
  6. Java 并发编程(二)对象的公布逸出和线程封闭
  7. python模拟登录人人
  8. 实践篇(1)--QPG之“打狗棍法”
  9. 非常使用的mongodb的聚合函数(使用SpringDataMongoDb)
  10. ERC20代币合约详解,附实现代码