首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >免xml配置springmvc应用--搭建

免xml配置springmvc应用--搭建

作者头像
叔牙
发布2020-11-19 14:54:45
发布2020-11-19 14:54:45
5770
举报

springmvc是常用的框架,有两种使用方式:

1)基于xml配置;大部分环境配置放在xml文件中,实现统一管理,以及配置和代码分离 。

2)免xml配置;免xml配置不等于免配置,只不过使用javabean代替xml,

这样可以免去复杂的配置文件,发挥bean的优势。

大家最常用的也是基于xml配置的,xml是有时候显得比较复杂和笨重,并且在应用启动过程中也会把xml中各种配置解析成相应的bean,所以可以这样说,xml配置本身就是bean,只不过和java bean存在的形式不一样。下边我们介绍一下免xml配置实现springmvc应用的方式和步骤。

  1. 新建webapp应用

项目目录结构如下

在pom文件中添加响应依赖,具体可以参见源码:https://gitee.com/ScorpioAeolus/extendDemo.git

  1. 编写代码 public class AppIntializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { System.out.println("Initializing Application for " + servletContext.getServerInfo()); // Create ApplicationContext AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); applicationContext.register(AppConfig.class); applicationContext.setServletContext(servletContext); // Add the servlet mapping manually and make it initialize automatically DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext); ServletRegistration.Dynamic servlet = servletContext.addServlet("mvc-dispatcher", dispatcherServlet); servlet.addMapping("*.do"); servlet.setAsyncSupported(true); servlet.setLoadOnStartup(1); } } 继承WebApplicationInitializer类重写onStartup方法,其实就是类似于web.xml中的请求路由配置,其中用到了AppConfig.class,查看其实现 @Configuration @EnableWebMvc @ComponentScan("com.typhoon.spring") public class AppConfig extends WebMvcConfigurerAdapter{ } 该类可以不继承WebMvcConfigurerAdapter,就能实现springmvc功能,继承后可以重写一些方法来实现过滤和拦截等功能,@EnableWebMvc启用springmvc功能,@Configuration定义成一个配置,@ComponentScan扫描指定包下边的类
  2. 编译运行 <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>8080</port> <path>/spring</path> </configuration> </plugin> 项目pom文件中有这么一段,意思是将tomcat7当做maven的一个插件引入到maven功能中来,这样我们可以直接通过maven命令来启动项目,而不用再配置tomcat server来启动项目。执行maven命令mvn tomcat7:run启动项目

看到没有启动异常,在浏览器中输入localhost:8080/spring,看到如下结果

说明项目配置启动成功,随便编写一个controller如下

再次运行mvn tomcat7:run,在浏览器输入localhost:8080/spring/user/index.do,看到如下结果

说明我们的环境搭建成功。

此篇简单介绍了使用免xml配置搭建springmvc项目,后续将在此基础上介绍其他内容

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-03-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 PersistentCoder 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档