龙哥网

龙哥网

使用java代码代替xml实现SSM教程_java(java的ssm)
2022-03-01

目录
  • 1.在IDEA中创建一个普通的maven项目
  • 2.添加Spring配置
  • 3.添加SpringMVC配置
  • 5.测试
    • 5.1创建HelloController类
    • 5.2创建HelloController2类
    • 5.3路径映射
  • 6.JSON配置
    • 7.总结

      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;
      /**
       * @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配置

      创建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 {
          /**
           * 配置静态资源过滤,相当于   <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转换配置
           * @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

      创建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,这个类需要实现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;
      /**
       * @author xiaoss
       * @date 2021年10月29日 17:00
       */
      @RestController
      public 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;
      /**
       * @author xiaoss
       * @date 2021年10月29日 22:17
       */
      @Controller
      public 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

      7.总结

      1.本项目需要在idea中配置外部的tomact才可运行

      2.自己也尝试在pom.xml中配置tomact插件,最后发现不行

      3.使用mave插件打包不行,因为他会找web.xml,所以找不到就会打包失败

      免责声明
      本站部分资源来源于互联网 如有侵权 请联系站长删除
      龙哥网是优质的互联网科技创业资源_行业项目分享_网络知识引流变现方法的平台为广大网友提供学习互联网相关知识_内容变现的方法。