springmvc全注解配置

SpringMVC纯注解配置 通过注解配置完全代替web.xml、Spring的xml文件配置,jquery递归遍历后台返回的json对象并进行拼接 立即下载

快速搭建web项目

  1. 创建maven项目
    添加依赖:
    注意spring和jackson的版本兼容问题
<!--spring-->
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>${spring-version}</version>
   </dependency>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-core</artifactId>
     <version>${spring-version}</version>
   </dependency>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-beans</artifactId>
     <version>${spring-version}</version>
   </dependency>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-expression</artifactId>
     <version>${spring-version}</version>
   </dependency>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-aop</artifactId>
     <version>${spring-version}</version>
   </dependency>
<!--spring-web-->
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-web</artifactId>
     <version>${spring-version}</version>
   </dependency>
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-webmvc</artifactId>
     <version>${spring-version}</version>
   </dependency>
   <!--tomcat-->
   <dependency>
     <groupId>org.apache.tomcat</groupId>
     <artifactId>tomcat-servlet-api</artifactId>
     <version>8.5.38</version>
   </dependency>
   <!--jackson-->
   <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.9.5</version>
   </dependency>
   <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-core</artifactId>
     <version>2.9.5</version>
   </dependency>
   <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-annotations</artifactId>
     <version>2.9.5</version>
   </dependency>

新建配置类extend AbstractAnnotationConfigDispatcherServletInitializer的注解快速配置类,
将DispatcherServlet和Spring应用上下文配置到Servlet容器中,

package com.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebInitilaizer extends AbstractAnnotationConfigDispatcherServletInitializer{
	/**根上下文中添加配置,定义分层ApplicationContext共享bean,如数据源配置,
	*某个DispatcherServlet上下文找不到的配置会从根上下文中去寻找
	*/
   @Override
   protected Class<?>[] getRootConfigClasses() {
       return new Class[]{};//空
   }
   /**
   *DispatcherServlet上下文配置类,未分层就一个上下文
   */
   @Override
   protected Class<?>[] getServletConfigClasses() {
       return new Class[]{WebConfig.class};//配置类
   }
   //相当于DispatcherServlet,servlet-mapping的url-pattern
   @Override
   protected String[] getServletMappings() {
       return new String[]{"/"};
   }

}

原理方面:如果Servlet容器遵循的是Servlet3.0接口,那么Servlet容器加载遵循javax.servlet.ServletContainerInitializer接口的规范,然而spring已经提供了该接口的实现类SpringServletContainerInitializer,方法会寻找WebApplicationInitializer接口实现类添加进初始化集合中

@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {

   @Override
   public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) throws ServletException {
   
       List<WebApplicationInitializer> initializers = new LinkedList<>();

                           ......//寻找WebApplicationInitializer的实现类,然后放入initializers中

       AnnotationAwareOrderComparator.sort(initializers);
   for (WebApplicationInitializer initializer : initializers) {
       initializer.onStartup(servletContext);
   }
   }
}

然而我们配置的抽象类继承关系如下:
WebApplicationInitializer —> AbstractContextLoaderInitializer —> AbstractDispatcherServletInitializer —> AbstractAnnotationConfigDispatcherServletInitializer
好了,继续我们的全注解配置,再写一个配置类,刚刚getServletConfigClasses()的WebConfig,
1、@Configuration表明配置类
2、@EnableWebMvc启用MVC Java config相当于<mvc:annotation-driven/>(加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter)
3、@ComponentScan扫描识别我们的controller
4、配置一个视图解析器和handler适配器

package com.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableWebMvc
@ComponentScan(value = "com.*",includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,
       value = Controller.class)})
public class WebConfig {
   @Bean(name = "internalResourceViewResolver")
   public ViewResolver viewResolver(){
       InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
       viewResolver.setPrefix("/WEB-INF/jsp/");
       viewResolver.setSuffix(".jsp");
       return  viewResolver;
   }
   @Bean(name = "requestMappingHandlerAdapter")
   public HandlerAdapter mappingHandlerAdapter(){
       RequestMappingHandlerAdapter handlerAdapter = new RequestMappingHandlerAdapter();
       MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
       List<MediaType> mediaTypelist = new ArrayList<>();
       mediaTypelist.add(MediaType.APPLICATION_JSON_UTF8);
       jackson2HttpMessageConverter.setSupportedMediaTypes(mediaTypelist);
       handlerAdapter.getMessageConverters().add(jackson2HttpMessageConverter);
       return handlerAdapter;
   }
}

有了这两个配置类,接下来就可以写controller(忽略@Api、@ApiOperation注解)

@Controller
@Api(value = "Test User 测试",tags={"用户操作接口"})
public class TestController {

   @Autowired
   private TestService testService;
   
   @ApiOperation(value="/map",notes="map返回json测试")
   @RequestMapping("/map")
   @ResponseBody
   public Map<String,String> map(){
       Map<String,String> map = new HashMap<>();
       map.put("key","value");
       return map;
   }
   @RequestMapping("/hello")
   public ModelAndView hello(){
       ModelAndView mav = new ModelAndView();
       mav.setViewName("hello");
       return mav;
   }
}

配置tomcat服务启动
在这里插入图片描述
在这里插入图片描述至此基本的控制器层访问已经可以了,无需xml配置,根据需要可适当增添以下配置类(引入相关的jar包)
配置项:数据源、jdbc、flyway(数据库本版管理,自动刷入sql脚本,默认脚本路径如图,sql命名V+版本+双下划线)

 <dependency>
  <groupId>org.flywaydb</groupId>
  <artifactId>flyway-core</artifactId>
  <version>4.2.0</version>
</dependency>![在这里插入图片描述](https://img-blog.csdnimg.cn/20190321235101105.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpbmhhb19vYmo=,size_16,color_FFFFFF,t_70)
package com.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.flywaydb.core.Flyway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
public class ServiceConfig {
   @Autowired
   private SystemPropertiesConfig systemPropertiesConfig;
   @Bean
   public DataSource dataSource(){
       DruidDataSource dataSource = new DruidDataSource();
       dataSource.setUrl(systemPropertiesConfig.getJdbcUrl());
       dataSource.setUsername(systemPropertiesConfig.getJdbcUserName());
       dataSource.setPassword(systemPropertiesConfig.getJdbcPassword());
       dataSource.setDriverClassName(systemPropertiesConfig.getJdbcDriver());
       return dataSource;
   }

   @Bean
   public JdbcTemplate jdbcTemplate(DataSource dataSource){
       JdbcTemplate jdbcTemplate = new JdbcTemplate();
       jdbcTemplate.setDataSource(dataSource);
       return jdbcTemplate;
   }

   @Bean
   public Flyway flyway(DataSource dataSource){
       Flyway flyway = new Flyway();
       flyway.setDataSource(dataSource);
       flyway.setBaselineOnMigrate(true);
       flyway.setLocations(systemPropertiesConfig.getFlywayDir());
       flyway.migrate();
       return flyway;
   }
}

配置项:swagger(好用的网页端在线接口api文档)

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.7.0</version>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.7.0</version>
</dependency>
package com.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration
@EnableSwagger2
@EnableWebMvc
public class Swagger2Config {

   @Autowired
   private SystemPropertiesConfig systemPropertiesConfig;
   private boolean swaggerEnabled ;

   @Bean
   public Docket createRestApi() {
       swaggerEnabled = Boolean.parseBoolean(systemPropertiesConfig.getSwaggerEnabled());
       return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
               // 是否开启
               .enable(swaggerEnabled).select()
               // 扫描的路径包
               .apis(RequestHandlerSelectors.basePackage("com.*"))
               // 指定路径处理PathSelectors.any()代表所有的路径
               .paths(PathSelectors.any()).build().pathMapping("/");
   }

   private ApiInfo apiInfo() {
       return new ApiInfoBuilder()
               .title("SpringMvc-Swagger2集成和使用-test示例")
               .description("SpringMvc | swagger")
               .contact(new Contact("varCode", "http://localhost:8080/test/", "1375354959@qq.com"))
               .version("1.0.0")
               .build();
   }
}

swagger应用顺带引出mvc对静态资源的配置
1、 configureDefaultServletHandling的configurer.enable();相当于<mvc:default-servet-handler>将静态资源交给tomcat处理(只能读取webapp下的资源,WEB-INF下的资源还得2);
2、addResourceHandlers看结构就和<mvc:resources mapping="xxx" location="xxx">一致

package com.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class ResourceHandlerConfig implements WebMvcConfigurer {

   @Override
   public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
       configurer.enable();
   }

   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
       registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
   }
}

还有注解整合整合mybatis、说起mg,开源代码生成器持久层基本都是生成mapper文件,需要一套前台页面、js+后端jdbc持久层,下次来个freemarker督促学习共同分享!

ensp企业网综合实验(课程设计) 使用MSTP+VRRP技术实现负载均衡以及增加网络的可靠性;出口配置napt;所有用户均为自动获取IP地址; 阅读详情

相关推荐

《玩儿起来吧》MATLAB 实时图像处理系列(一二三四)

大家学了图像处理之后,是不是就想学以致用。而要用于生活中,最好的方式就是和摄像头搭配,实现实时图像处理。今天就给大家分享MATLAB实时图像处理的基础方法,希望能帮你快速入门。

HPC_ZY 1万+

注解配置SpringMVC

使用配置类和注解代替web.xml和SpringMVC配置文件的功能

博客的博客 1097

信息学奥赛一本通高手训练1680:序列

题目 代码 #include<cstdio> #include<iostream> #include<cmath> #define LL long long using namespace std; const LL N = 1400000+7; const LL mod = 1e9+7; int n, t; LL pos[N], sum[N], ans[N]; struct node{ LL ll, rr; }a[N]; int main(){ p

qingfeixueyue的博客 468

SpringMVC学习(十一):注解配置SpringMVC

使用配置类和注解代替web.xml和SpringMVC配置文件的功能 1、创建初始化类,代替web.xml 在Servlet3.0环境中,容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果找到的话就用它来配置Servlet容器。 Spring提供了这个接口的实现,名为SpringServletContainerInitializer,这个类反过来又会查找实现WebApplicationInitializer的类并将配置的任务交给它

m0_49499183的博客 543

BERT之提取特征向量 及 bert-as-server的使用

本文内容列表提取句向量1、句向量简介1-1传统句向量1-2、BERT句向量2、 extract_features.py源码分析2-1 main函数 前一篇文章 BERT介绍及中文文本相似度任务实践 简单介绍了使用BERT进行中文文本相似度计算的方法,这篇文章着重对特征提取方法进行讲述。 提取句向量 1、句向量简介 1-1传统句向量 更多采用word embedding的方式取加权平均,该方法的一大...

ling620的专栏 1万+

【DRAM存储器四十三】LPDDR5介绍--寻址

简要说明LPDDR5 X16、x8 die的寻址

highman110的博客 967

SpringMVC中的注解配置

Override/***///加载spring配置类@Override//加载springmvc配置类@Override//设置DispatcherServlet的url-pattern@Override@Override// 创建编码过滤器// 设置编码格式// 设置强制编码// 创建请求方式的过滤器。

ning的博客 1515

【机器学习系列】一文搞懂 零知识机器学习(zkML)

位串行乘法器:实现了Booth编码优化,将乘法分解为移位-加法序列,减少部分积数量50%:模拟脉动阵列的2D网格计算,支持分块(tiling)策略优化内存层次卷积映射:提供直接卷积(行缓冲+滑动窗口)和im2col+GEMM两种硬件映射策略。

VectorShift的博客 156

一文搞懂:SpringMVC全注解方式及原理

上面的MvcConfig配置类中,我们定义了一个拦截器,这个类的代码如下@Component@OverrideSystem.out.println(“这是MyInterceptor拦截器”);看完美团、字节、腾讯这三家的一二三面试问题,是不是感觉问的特别多,可能咱们真的又得开启面试造火箭、工作拧螺丝的模式去准备下一次的面试了。开篇有提及我可是足足背下了Java互联网工程师面试1000题,多少还是有点用的呢,换汤不换药,不管面试官怎么问你,抓住本质即可!能读到此处的都是真爱。

2301_76348171的博客 1070

从入门到精通:Cursor使用全攻略

Cursor是一款基于VSCode深度定制的AI编程工具,由Anysphere公司开发。它将AI技术与代码开发深度融合,能够理解自然语言指令并生成高质量代码,支持代码补全、跨文件上下文理解等功能。本文详细介绍了Cursor的安装设置、界面导航、基本操作和Composer模式等核心功能,并提供了高效提示词写作技巧和实际应用案例(如浏览器插件开发、复杂表单组件构建等)。文章还总结了使用注意事项和常见问题解决方案,展望了AI编程工具的发展前景。Cursor通过智能代码生成和项目理解能力,显著提升了开发效率,适合各

远程部署调试 运行安装 项目调试 二次开发 项目技术新 持续迭代 部分源码免费分享 6457

Python实现FFT、小波变换和数据压缩

小波变换是一种分析信号的方法,可以分解信号成为多个尺度和频率的分量,从而更好地理解和处理信号。在Python中,我们可以使用pywt库来实现小波变换。在Python中,我们可以使用numpy库中的fft模块来实现FFT。数据压缩是一种将数据表示成更紧凑的形式的方法,可以减少存储空间和传输带宽。综上所述,Python提供了很多方便的工具来实现各种信号处理和数据压缩的方法。本文将介绍Python中如何实现傅里叶变换(FFT)、小波变换以及如何使用它们来进行数据压缩。Python实现FFT、小波变换和数据压缩。

学习使你进步。 691

Spring MVC学习 | 注解配置Spring MVC&总结

常用组件组件的实现和使用作用前端控制器(中心控制器) DispatcherServlet由框架提供类型,开发人员只需在配置文件或配置类进行配置对请求和相应进行统一处理,是整个控制层的中心,调用其他组件对请求进行处理处理器映射器 HandlerMapping直接由框架提供,无需创建和配置根据请求路径、请求方式等信息查找对应的处理器Handler,即控制器方法,然后获取控制器方法中所有相关对象(包括控制器对象及其对应的拦截器对象等),最后返回一个对象(处理执行链)处理器 Handler。

CV工程师的博客 1545

流媒体之LL-HLS 低延时HLS协议

LL-HLS协议通过扩展了HLS协议,为实时直播场景提供了更丰富的功能,如延迟控制、播放列表增量更新、阻止播放列表重新加载等。同时客户端可以更灵活地控制播放列表的加载和播放,以适应各种场景和需求。LL-HLS在直播中的延时可以控制在3s内, 但是即使这样, 还是不如RTMP, RTSP等协议的实时性。

技术控的笔记 3364

【SpringMVC】| 异常处理器、基于全注解配置SpringMVC

【SpringMVC】| 异常处理器、基于全注解配置SpringMVC

m0_61933976的博客 4340

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

全注解配置springmvc

使用配置类和注解代替web.xml和SpringMVC配置文件的功能 创建初始化类,代替web.xml 在Servlet3.0环境中,容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果找到的话就用它来配置Servlet容器(也就是tomcat)。 Spring提供了这个接口的实现,名为SpringServletContainerInitializer,这个类反过来又会查找实现WebApplicationInitializer的类并将配

moxiong12138的博客 215

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

12-SpringMVC 完全注解方式配置SpringMVC

1.相关概念 使用配置类和注解代替web.xml和SpringMVC配置文件的功能 在Servlet3.0环境中,容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果找到的话就用它来配置Servlet容器。 Spring提供了这个接口的实现,名为SpringServletContainerInitializer,这个类反过来又会查找实现WebApplicationInitializer的类并将配置的任务交给它们来完成。Spring3.2引入

鸣鼓ming的博客 4081

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

全注解方式配置SpringMVC

1.在J2EE三层的注解: 表现层:@Controller 业务层: @Service 持久层: @Repository 其他: @Component 注解起效需要几方: 1.需要一个注解 2.直接贴在什么地方 3.第三的扫描程序. 步骤: 1.开启注解扫描 <context:component-scan base-package="com._520it.springmv...

weixin_34234721的博客 113

SpringMVC 全注解配置

pom.xml的配置 <properties> <jdk.version>1.8</jdk.version> <spring.version>4.2.2.RELEASE</spring.version> <jackson.version>2.6.3</jackson.version> <logback.version>1.1.3</lo

qq_19349607的博客 5695

Spring SpringMVC Mybatis 全注解配置

Spring SpringMVC Mybatis 全注解方式

tanjun517132的博客 801

SpringMVC全注解配置学习笔记

编写根容器配置类@Configuration @ComponentScan("com.yicj.study.mvc.hello.service") public class RootConfig { } 编写web容器配置类@EnableWebMvc @Configuration @ComponentScan("com.yicj.study.mvc.hello.controller") public class WebConfig { @Bean public InternalReso.

yichengjie_c的博客 177

log4j2 xml mysql_Springmvc+Spring+Mybatis+Freemarker+druid+log4j2 全注解配置

前言:对于使用配置文件已经有了一定经验的初学者来说,应该体验一下使用注解作为配置文件的感受,一下我用自己的经验来配置一份最简单但同时也全面的配置。安利一篇自己的 Maven自定义SpringBoot 更方便快捷的启动项目, 特别适合毕业设计和小型项目。1、目录结构目录结构应该是搭建项目的说明中首先说明的东西,这是涉及到学习者对整体结构了解的一个前提。2、pom文件配置xsi:schemaLocat...

weixin_42128315的博客 346

一文搞懂:SpringMVC全注解方式及原理,2024年最新从零开始学数据结构和算法

上面的MvcConfig配置类中,我们定义了一个拦截器,这个类的代码如下@Component@OverrideSystem.out.println(“这是MyInterceptor拦截器”);

weixin_45298122的博客 669

基于maven的SpringMVC,Spring,MyBatis的全注解配置

首先创建maven项目 1.maven添加各种依赖包 <!--数据库连接池--> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artif...

chongdou0938的博客 123

SpringMVC全注解开发

现在多流行SpringMVC的全注解开发很少见,一般企业了都是使用半xml半注解的开发方式,但是SpringMVC是支持全注解开发的,很多老程序员不愿尝试新技术方案,只愿意复制粘贴老项目代码,所以导致新技术方案推广异常缓慢,SpringMVC很早就可以使用全注解方式开发了。 在SpringMVC中,肯定是没有内置容器的,所以一定还是要有一个WEB-INF目录的,里面会有至少web.xml配置文件。 ...

诗人不写诗 416
上一篇: java File实用工具
下一篇: 关于flex布局
varCode
博客等级 码龄9年 11粉丝 15原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值