当前位置: java基础教程 > 29-springboot > 阅读正文

web项目转spring web

2021.6.19.   659 次   1789字

这里的普通项目, 主要讨论的是servlet, jsp项目

由于springboot是建立在maven项目之上的, 普通项目转maven是很容易的, 不是我们讨论的主要点, 我们假设这是一个 maven 的普通web项目

坐标改造

1.导入springboot核心坐标

在maven的pom.xml中, 导入springboot的parent坐标

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

2.导入web依赖坐标

此坐标, 包含了servlet, tomcat, jackson, springmvc(包含了jsp)等

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

3.导入打包坐标

springboot打包时, 需要此专门的打包插件

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

若上述插件报错, 可以手动指定version, 或者把properties改为仅有java版本号

  <properties>
    <java.version>1.8</java.version>
  </properties>

默认指定为jar包, 也可以手动指定

<packaging>jar</packaging>

3.删除不必要的依赖

servlet, jsp, jackson, tomcat坐标已经不再需要了, 不必要的坐标都可以删掉

页面改造

仅针对servlet, 和 jsp页面, 而jsp不需要修改

servlet页面改造

对于传统的servlet进行改造, 仅需要添加2个额外的注解, 其他的不变

@SpringBootApplication  //标明这是一个启动类
@ServletComponentScan  //让springboot扫描此类
@WebServlet("/myServlet")
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //输出一个helloworld
        resp.getWriter().println("Hello My Servlet!");
    }
}

目录改造

springboot和普通的maven web项目的目录并不一样, 所以需要修改目录

主要修改的地方在于web资源的位置, springboot不再有webapp

  • webapp —> resources/static
  • jsp页面 –> resources/templates

启动与配置改造

由于内置了tomcat, 无法直接启动tomcat, 而是通过启动类

在java目录下, 新建一个com.xxx.项目名的包, 然后新建一个xxxApplication类

通过main方法启动springboot项目, 其他java文件均应该与此类同级或子级包

public static void main(String[] args) {
        SpringApplication.run(xxxApplication.class, args);
    }

配置的修改

maven项目依然是在tomcat坐标中修改端口等信息, 现在已经无法实现了

在resources新建application.properties或者yml文件( 不懂语法先使用前者)

那么, 对于配置的修改, 比如修改端口

server.port=8081
server.servlet.context-path=/test

本篇完,还有疑问?

加入QQ交流群:11500065636 IT 技术交流群