1. 程式人生 > >Spring Boot 使用外接的 Servlet 容器 -- 專案打War包和外部Tomcat配置與專案啟動

Spring Boot 使用外接的 Servlet 容器 -- 專案打War包和外部Tomcat配置與專案啟動

嵌入式 & 外接 Servlet 容器的優缺點;

嵌入式 Servlet 容器:
優點:簡單,便攜;
缺點:預設不支援 JSP、優化定製複雜(使用定製器【ServerProperties,自定義定製器EmbeddedServletContainerCustomizer】,自己編寫嵌入式容器建立工廠【EmbeddedServletContainerFactory】)

外接 Servlet 容器:在外面安裝 Tomcat 程式 – 應用war

【1】建立專案並打War包

使用Spring Initializer方式建立專案, **Packaging 選擇 War**

在這裡插入圖片描述

在這裡插入圖片描述

有三個地方需要注意:
  
  pom中打包方式已經為war;
  對比預設為jar的專案多了ServletInitializer類(必須要有此類並且呼叫configure方法

);
  專案結構沒有src/main/webapp,且沒有WEB/INF web.xml。

ServletInitializer類:

public class ServletInitializer extends SpringBootServletInitializer {

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

}

補全專案結構
在這裡插入圖片描述

生成 web.xml 檔案
在這裡插入圖片描述

在這裡插入圖片描述

在這裡插入圖片描述

【2】IDEA 整合 外部配置的Tomcat啟動專案
在這裡插入圖片描述

在這裡插入圖片描述

在這裡插入圖片描述

在這裡插入圖片描述

在這裡插入圖片描述

在這裡插入圖片描述

啟動服務
在這裡插入圖片描述

建立 JSP

<h1>Hello Spring Boot JSP</h1>

hello.jsp 傳送請求來到 /WEB-INF/success.jsp

hello.jsp

<h1>Hello Spring Boot JSP</h1>

 <a href="hello">abc</a>

HelloController

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello(Model model){
        model.addAttribute("msg","你好 Spring Boot");
        return "success";
    }

}

success.jsp

<h1>SUCCESS</h1>
<h1>${msg}</h1>

在這裡插入圖片描述