SpringBoot教程

SpringBoot打Jar包并运行

项目名称:037-springboot-web-jar

因为SpringBoot默认的打包方式就是jar包,所以我们直接执行Maven的package命令就行了。

1.在pom.xml文件中添加Tomcat解析jsp依赖

<!--SpringBoot项目内嵌tomcat对jsp的解析包-->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>

2.在pom.xml文件中添加resources配置,以后为了保险起见,大家在打包的时候,建议把下面的配置都加上

<resources>
    <!--mybatis的mapper.xml-->
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
    <!--src/main/resources下的所有配置文件编译到classes下面去-->
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/*.*</include>
        </includes>
    </resource>
    <resource>
        <!--源文件位置-->
        <directory>src/main/webapp</directory>
        <!--编译到META-INF/resources,该目录不能随便写-->
        <targetPath>META-INF/resources</targetPath>
        <includes>
            <!--要把哪些文件编译过去,**表示webapp目录及子目录,*.*表示所有-->
            <include>**/*.*</include>
        </includes>
    </resource>
</resources>

3.修改pom.xml文件中打包插件的版本

默认SpingBoot提供的打包插件版本为2.1.2.RELEASE,这个版本打的jar包jsp不能访问,我们这里修改为1.4.2.RELEASE(其它版本测试都有问题)

<!--SpringBoot提供的打包编译等插件-->
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>1.4.2.RELEASE</version>
</plugin>

4.修改application.properties配置文件

#设置内嵌Tomcat端口号
server.port=9090
#设置项目上下文根
server.servlet.context-path=/

#配置jsp的前/后缀
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

5.在com.abc.springboot.web包下创建IndexController

package com.abc.springboot.web;

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

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:IndexController
 * Package:com.abc.springboot.web
 * Description:

 */
@Controller
public class IndexController {

    @GetMapping(value = "/springboot/index")
    public String index(HttpServletRequest request, Model model) {
        model.addAttribute("data","Hello SpringBoot JSP");
        return "index";
    }

    @RequestMapping(value = "/springboot/json")
    public @ResponseBody Object json() {
        Map retMap = new HashMap();

        retMap.put("message","SpringBoot-JSON");

        return retMap;
    }

}

6.创建webapp并指定为web资源目录

7.通过java命令执行jar包,相当于启动内嵌tomcat

将target下的jar包拷贝到某一个目录,在该目录下执行java -jar jar包名称

8.浏览器访问测试

技术文档推荐

更多>>

视频教程推荐

更多>>