Spring MVC on VSCode - Maven Project

342 阅读2分钟

准备:

步骤:

1 Open vscode command palette from View -> Command palette on the menu bar ( or use Cntrl + Shift + P ). Search for Java: Create Java Project on the search field and choose the option from the list. Another view will be displayed to choose your project type, one of which is Maven. Select the Maven option. We're interested in web project, so select the maven-archtype-webapp from the archtype view.

Maven will run on vscode terminal and install all necessary dependencies for a basic webapp project. During the process you'll be prompted to interactively enter project's groupId, artifactId, Version, package name.

1) Adding Spring Dependency

To add spring mvc dependencies, open vscode command palette from View -> Command pallet on the menu bar ( or use Cntrl + Shift + P ). Search for Maven: Add a dependency select it from the list of command. Another search field will be opened to search for dependencies. Search for:

  • spring-webmvc
  • javax.servlet-api

补充:

  • 修改 maven 使用的 java 版本为 1.8
  • 删除 maven-archtype-webapp 这个模版里面创建的 pom.xml 用到的 build 里面的所有插件以及配置,添加 tomcat7-maven-plugin这个插件。
<!--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.example</groupId>
      <artifactId>demo_ssm</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>war</packaging>

      <name>demo_ssm Maven Webapp</name>

      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
      </properties>

      <dependencies>

        <!-- 1 导入依赖 -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>5.2.25.RELEASE</version>
        </dependency>

        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.1.0</version>
          <scope>provided</scope>
        </dependency>

        <!-- 1 导入依赖 -->

      </dependencies>

      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>
              <port>80</port>
              <path>/</path>
            </configuration>
          </plugin>
        </plugins>
      </build>
</project>

2)创建 cotroller 类

package com.ftf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

// 2 写控制器类
@Controller
public class UserController {

    @RequestMapping("/save")
    @ResponseBody
    public String save() {
        System.out.println("usre save ...");
        return "{'info': 'Spring MVC'}";
    }
}

3)创建 SpringMVC 配置类

package com.itcast.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

// 3 写 spring mvc 配置类
@Configuration
@ComponentScan("com.ftf.controller")
public class SpringMvcConfig {
    //
}

4)创建 配置 tomcat 的 servlet 容器配置类,设置启动时加载 spring 环境

package com.ftf.config;

import org.springframework.lang.Nullable;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

// 4 配置 tomcat 的 servlet 容器配置类,设置启动时加载 spring 环境
public class ServletContainerInitConfig extends AbstractDispatcherServletInitializer {

    @Override
    // 加载springmvc 配置
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringMvcConfig.class);
        return ctx;
    }

    // 设置所有的请求由 springmvc 处理
    @Override
    // 设置 tomcat 接受的请求那些归 springmvc 处理
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

    @Override
    @Nullable
    // 设置spring 相关的配置
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }
}

或者 使用如下简化的配置方式

package com.ftf.config;

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

public class ServletContainerInitConfig2 extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    @Nullable
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class}
    }

    @Override
    @Nullable
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { SpringMvcConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

5)删除 maven 模版 maven-archtype-webapp 这个模版里面创建的 /Users/mac/program-demo-sets/java-demo-itcast/demo_ssm/src/main/webapp/WEB-INF/web.xml

6) 启动项目

image.png

7) 访问项目

用浏览器打开:

http://localhost/

http://localhost/save

image.png

ref:dev.to/spaceofmiah…