使用java代碼代替xml實現(xiàn)SSM教程
SpringBoot推薦開發(fā)者使用Java配置來搭建框架,SpringBoot中大量的自動化配置都是通過Java代碼配置實現(xiàn)的,而不是XML配置,同理,我們自己也可以使用純Java來搭建一個SSM環(huán)境,即在項目中不存在任何XML配置,包括web.xml
環(huán)境要求:
Tomact版本必須在7以上
1.在IDEA中創(chuàng)建一個普通的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 會傳遞到依賴的項目中。適用于所有階段,會隨著項目一起發(fā)布 2.provided,跟compile相似,但是表明了dependency 由JDK或者容器提供,例如Servlet AP和一些Java EE APIs。這個scope 只能作用在編譯和測試時,同時沒有傳遞性 3.runtime,表示dependency不作用在編譯時,但會作用在運行和測試時,如JDBC驅(qū)動,適用運行和測試階段 4.test,表示dependency作用在測試時,不作用在運行時。 只在測試時使用,用于編譯和運行測試代碼。不會隨項目發(fā)布 5.system,跟provided 相似,但是在系統(tǒng)中要以外部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配置
創(chuàng)建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; /** * @author xiaoss * @Configuration注解標識該類是一個配置類,作用類似于:applicationContext.xml文件 * @ComponentScan注解標識配置包掃描,useDefaultFilters表示使用默認的過濾器,excludeFilters里面的配置表示除去Controller里面的注解, * 即項目啟動時候,spring容器只掃描除了Controller類之外的所有bean * @date 2021年10月29日 16:43 */ @Configuration @ComponentScan(basePackages = "com.xiao",useDefaultFilters = true, excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = Controller.class)}) public class SpringConfig { }
3.添加SpringMVC配置
創(chuàng)建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; /** * @author xiaoss * @date 2021年10月29日 16:56 */ @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 { /** * 配置靜態(tài)資源過濾,相當于 <mvc:resources mapping="/**" location="/"></> * @param registry */ @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/js/**").addResourceLocations("classpath:/"); } /** * 配置視圖解析器 * @param registry */ @Override protected void configureViewResolvers(ViewResolverRegistry registry) { registry.jsp("/jsp/",".jsp"); } /** * 路徑映射 * @param registry */ @Override protected void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/hello3").setViewName("hello"); } /** * json轉(zhuǎn)換配置 * @param converters */ @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); } }
4.配置web.xml
創(chuàng)建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; /** * @author xiaoss * @date 2021年10月29日 17:13 */ 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,這個類需要實現(xiàn)WebApplicationInitializer接口,并實現(xiàn)其方法,當項目啟動時,onStartup方法會被自動執(zhí)行,我們可以在這里進行項目初始化操作,如:加載SpringMVC容器,添加過濾器,添加Listener,添加Servlet等
注:
由于在onStartup里面只加載了springmvc配置,沒有加載spring容器,如果要加載Spring容器
方案一:
修改springmvc配置,在配置的包掃描中也去掃描@Configuration注解
推薦 方案二:
去掉springConfig文件,講所有的配置都放到springmvc里面
5.測試
5.1創(chuàng)建HelloController類
package com.xiao.control; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @author xiaoss * @date 2021年10月29日 17:00 */ @RestController public class HelloController { @GetMapping("/hello") public String hello(){ return "hello"; } }
運行結(jié)果:
5.2創(chuàng)建HelloController2類
package com.xiao.control; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; /** * @author xiaoss * @date 2021年10月29日 22:17 */ @Controller public class HelloController2 { @GetMapping("hello2") public String hello2(){ return "hello"; } }
運行結(jié)果:
5.3路徑映射
6.JSON配置
SpringMVC可以接收json參數(shù),也可以返回json參數(shù),這一切依賴于HttpMessageConverter
HttpMessageConverter可以將一個json字符串轉(zhuǎn)為對象,也可以將一個對象轉(zhuǎn)為json字符串,實際上它的底層還是依賴具體的json庫
SpringMVC中默認提供了Jackson和gson的HttpMessageConverter,分別是:
MappingJackson2HttpMessageConverter
GsonHttpMessageConverter
7.總結(jié)
1.本項目需要在idea中配置外部的tomact才可運行
2.自己也嘗試在pom.xml中配置tomact插件,最后發(fā)現(xiàn)不行
3.使用mave插件打包不行,因為他會找web.xml,所以找不到就會打包失敗
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SVN報錯:Error Updating changes:svn:E155037的解決方案
今天小編就為大家分享一篇關(guān)于SVN報錯:Error Updating changes:svn:E155037的解決方案,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01Java數(shù)據(jù)結(jié)構(gòu)之圖(動力節(jié)點Java學院整理)
本文章主要講解學習如何使用JAVA語言以鄰接表的方式實現(xiàn)了數(shù)據(jù)結(jié)構(gòu)---圖(Graph)。對java數(shù)據(jù)結(jié)構(gòu)之圖相關(guān)知識感興趣的朋友一起學習吧2017-04-04java基于Apache FTP點斷續(xù)傳的文件上傳和下載
本篇文章主要介紹了java基于Apache FTP點斷續(xù)傳的文件上傳和下載,利用FTP實現(xiàn)文件的上傳和下載,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2016-11-11java中CompletableFuture異步執(zhí)行方法
本文主要介紹了java中CompletableFuture異步執(zhí)行方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-06-06Java BeanMap實現(xiàn)Bean與Map的相互轉(zhuǎn)換
這篇文章主要介紹了利用BeanMap進行對象與Map的相互轉(zhuǎn)換,通過net.sf.cglib.beans.BeanMap類中的方法來轉(zhuǎn)換,效率極高,本文給大家分享實現(xiàn)代碼,感興趣的朋友一起看看吧2022-11-11Mybatis實現(xiàn)關(guān)聯(lián)關(guān)系映射的方法示例
本文主要介紹了Mybatis實現(xiàn)關(guān)聯(lián)關(guān)系映射的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07