本篇内容介绍了“如何使用java代码代替xml实现SSM”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
SpringBoot推荐开发者使用Java配置来搭建框架,SpringBoot中大量的自动化配置都是通过Java代码配置实现的,而不是XML配置,同理,我们自己也可以使用纯Java来搭建一个SSM环境,即在项目中不存在任何XML配置,包括web.xml
环境要求:
Tomact版本必须在7以上
1.在IDEA中创建一个普通的maven项目
在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"> <modelVersion>4.0.0</modelVersion> <groupId>com.xiao.ssm</groupId> <artifactId>SSM-demo</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> <tomcat.version>2.2</tomcat.version> <webserver.port>8888</webserver.port> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!--引入springMVC依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.12.RELEASE</version> </dependency> <!--引入servlet依赖--> <!--scope作用域: 1.compile,默认的scope(作用域),表示 dependency 都可以在生命周期中使用。而且,这些dependencies 会传递到依赖的项目中。适用于所有阶段,会随着项目一起发布 2.provided,跟compile相似,但是表明了dependency 由JDK或者容器提供,例如Servlet AP和一些Java EE APIs。这个scope 只能作用在编译和测试时,同时没有传递性 3.runtime,表示dependency不作用在编译时,但会作用在运行和测试时,如JDBC驱动,适用运行和测试阶段 4.test,表示dependency作用在测试时,不作用在运行时。 只在测试时使用,用于编译和运行测试代码。不会随项目发布 5.system,跟provided 相似,但是在系统中要以外部JAR包的形式提供,maven不会在repository查找它 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> </dependencies> <build> <plugins> <!-- tomcat7插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>${tomcat.version}</version> <configuration> <port>${webserver.port}</port> <path>/${project.artifactId}</path> <uriEncoding>${project.build.sourceEncoding}</uriEncoding> </configuration> </plugin> </plugins> </build> <repositories> <repository> <id>central</id> <url>https://maven.aliyun.com/nexus/content/repositories/central</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>central</id> <url>https://maven.aliyun.com/nexus/content/repositories/central</url> </pluginRepository> </pluginRepositories></project>
2.添加Spring配置
创建SpringConfig.java文件
package com.xiao.config;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.FilterType;import org.springframework.stereotype.Controller;@Configuration@ComponentScan(basePackages = "com.xiao",useDefaultFilters = true, excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = Controller.class)})public class SpringConfig {}
3.添加SpringMVC配置
创建SpringMVCConfig.java文件
package com.xiao.config;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.FilterType;import org.springframework.stereotype.Controller;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;@Configuration//@ComponentScan(basePackages = "com.xiao",useDefaultFilters = true,// excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = Controller.class)})@ComponentScan(basePackages = "com.xiao")public class SpringMVCConfig extends WebMvcConfigurationSupport { @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/js @Override protected void configureViewResolvers(ViewResolverRegistry registry) { registry.jsp("/jsp/",".jsp"); } @Override protected void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/hello3").setViewName("hello"); } @Override protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter converter=new FastJsonHttpMessageConverter(); converter.setDefaultCharset(Charset.forName("UTF-8")); FastJsonConfig fastJsonConfig=new FastJsonConfig(); fastJsonConfig.setCharset(Charset.forName("UTF-8")); converter.setFastJsonConfig(fastJsonConfig); converters.add(converter); }}
配置web.xml
创建WebInit.java文件
package com.xiao.config;import org.springframework.web.WebApplicationInitializer;import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;import org.springframework.web.servlet.DispatcherServlet;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.ServletRegistration;public class WebInit implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { //首先来加载SpringMVC的配置文件 AnnotationConfigWebApplicationContext ctx=new AnnotationConfigWebApplicationContext(); ctx.register(SpringMVCConfig.class); //添加DispatcherServlet ServletRegistration.Dynamic springmvc=servletContext.addServlet("springmvc",new DispatcherServlet(ctx)); //给DispatcherServlet添加路径映射 springmvc.addMapping("/"); //给DispatcherServlet添加启动时机 springmvc.setLoadOnStartup(1); }}
WebInit的作用类似于web.xml,这个类需要实现WebApplicationInitializer接口,并实现其方法,当项目启动时,onStartup方法会被自动执行,我们可以在这里进行项目初始化操作,如:加载SpringMVC容器,添加过滤器,添加Listener,添加Servlet等
注:
由于在onStartup里面只加载了springmvc配置,没有加载spring容器,如果要加载Spring容器
方案一:
修改springmvc配置,在配置的包扫描中也去扫描@Configuration注解
推荐 方案二:
去掉springConfig文件,讲所有的配置都放到springmvc里面
5.测试
5.1创建HelloController类
package com.xiao.control;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class HelloController { @GetMapping("/hello") public String hello(){ return "hello"; }}
运行结果:
5.2创建HelloController2类
package com.xiao.control;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;@Controllerpublic class HelloController2 { @GetMapping("hello2") public String hello2(){ return "hello"; }}
运行结果:
5.3路径映射
6.JSON配置
SpringMVC可以接收json参数,也可以返回json参数,这一切依赖于HttpMessageConverter
HttpMessageConverter可以将一个json字符串转为对象,也可以将一个对象转为json字符串,实际上它的底层还是依赖具体的json库
SpringMVC中默认提供了Jackson和gson的HttpMessageConverter,分别是:
MappingJackson2HttpMessageConverter
GsonHttpMessageConverter
“如何使用java代码代替xml实现SSM”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注编程网网站,小编将为大家输出更多高质量的实用文章!