1. 程式人生 > >26 外接Servlet容器(以Tomcat為例)使用

26 外接Servlet容器(以Tomcat為例)使用

1 步驟

1.1 建立war專案

1.2 將內建Tomcat指定為provided

<?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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository -->
</parent> <groupId>com.springboot</groupId> <artifactId>springboot-22</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>springboot-22</name> <description>Demo project for Spring Boot</
description
>
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

1.3 SpringBootServletInitializer的子類必須存在,並呼叫configure方法

package com.gp6.springboot22;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Springboot22Application.class);
    }

}

1.4 配置外部tomcat

配置外部tomcat

1.5 新建測試頁面

  • test.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <h1>測試 JSP</h1>
    <a href="test">點選看看</a>
</body>
</html>

1.6 Controller

package com.gp6.springboot22.controller;

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

@Controller
public class HelloController {

    @GetMapping("/test")
    public String hello(Model model){
        model.addAttribute("msg","看什麼?6,你和我,走一波!");
        return "success";
    }
}

1.7 application.properties

spring.mvc.view.prefix=/WEB_INF/
spring.mvc.view.suffix=.jsp

1.8 測試

http://localhost:8082/test.jsp