背景:Spring Boot 集成servlet,發布為可直接運行的war包,方便后續打包為docker鏡像。
1、build.gradle 配置
注意,加入了war插件,在依賴中加入了jstl、tomcat-embed-jasper,這樣才能運行jsp頁面。
buildscript {
ext {
springBootVersion = '1.5.3.RELEASE'
}
repositories {
maven { url "http://maven.aliyun.com/nexus/content/groups/public/" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
maven { url "http://maven.aliyun.com/nexus/content/groups/public/" }
}
dependencies {
compile 'jstl:jstl:1.2'
compile 'org.apache.tomcat.embed:tomcat-embed-jasper'
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
2、spring boot 入口文件配置
注意:繼承SpringBootServletInitializer
,開啟@ServletComponentScan
@SpringBootApplication
@ServletComponentScan
public class DemoApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(DemoApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3、servlet/jsp 的正確姿勢
文件布放圖
3.1、servlet
注意:使用了@WebServlet
配置頁面訪問地址,訪問jsp頁面需要使用完整的相對路徑/WEB-INF/jsp/index.jsp
@WebServlet( urlPatterns = {"/index"})
public class Index extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);
}
}
3.2、controller方式使用jsp
注意:配合application.properties配置,可以使用簡化的jsp路徑
①application.properties配置
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
②controller編寫
@Controller
public class HelloController {
@RequestMapping("/index1")
public ModelAndView index(ModelAndView view) {
view.setViewName("index");
return view;
}
}
4、運行方法
右鍵入口文件直接運行
bootRun
執行gradle build,java -jar xxx.war
5、完整實例代碼
https://github.com/weibaohui/springboot-servlet-jsp-war-demo