SpringBoot使用JSP(官網Demo)


最開始接觸java的時候,前端頁面基本都是用jsp來寫,最近公司項目要使用SpringBoot重構,查看SpringBoot文檔,發現SpringBoot不建議使用JSP,因為jsp在使用內嵌servlet容器時會有一些限制

雖然以后項目中也會將jsp替換成Template Engines,而且這都是前端的事情,其實與后端並無比較大的聯系,但比較好奇Springboot中對jsp的使用,故根據官方文檔進行了簡單測試驗證

如果使用JSP,則需要將項目打包成war包,jar包不支持JSP。

打開JSP sample,這是一個github上的項目,點擊Code標簽頁,clone or download下載源碼,這里下載的代碼中包含有很多個springboot項目,其中spring-boot-samples中包含有我們需要的spring-boot-sample-web-jsp

解壓下載的文件,spring-boot-samples下項目很多,我們根據需要在eclipse中只導入spring-boot-sample-web-jsp項目,導入時可能出現以下異常

點擊finish -- ok,pom.xml文件中出現異常

 選擇Mark goal validate as ignored in pom.xml忽略掉該信息

點擊OK

此時若項目上還有紅色的叉號,則在項目名稱上右鍵 -- Maven -- Update Project -- OK。

項目結構

包sample.jsp下有兩個類

控制器WelcomeController

package sample.jsp;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class WelcomeController {

    @Value("${application.message:Hello World}")
    private String message = "Hello World";

    @GetMapping("/")
    public String welcome(Map<String, Object> model) {
        model.put("time", new Date());
        model.put("message", this.message);
        return "welcome";
    }

    @RequestMapping("/foo")
    public String foo(Map<String, Object> model) {
        throw new RuntimeException("Foo");
    }
}

啟動類SampleWebJspApplication.java

package sample.jsp;

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

@SpringBootApplication
public class SampleWebJspApplication extends SpringBootServletInitializer {

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

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

 兩個jsp頁面

welcome.jsp

<!DOCTYPE html>

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html lang="en">

<body>
    <c:url value="/resources/text.txt" var="url"/>
    <spring:url value="/resources/text.txt" htmlEscape="true" var="springUrl" />
    Spring URL: ${springUrl} at ${time}
    <br>
    JSTL URL: ${url}
    <br>
    Message: ${message}
</body>

</html>

error.jsp

<!DOCTYPE html>
<html lang="en">
<body>
Something went wrong: ${status} ${error}
</body>
</html>

pom.xml

<?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>
        <!-- Your own application should inherit from spring-boot-starter-parent -->
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-samples</artifactId>
        <version>${revision}</version>
    </parent>
    <artifactId>spring-boot-sample-web-jsp</artifactId>
    <packaging>war</packaging>
    <name>Spring Boot Web JSP Sample</name>
    <description>Spring Boot Web JSP Sample</description>
    <properties>
        <main.basedir>${basedir}/../..</main.basedir>
        <m2eclipse.wtp.contextRoot>/</m2eclipse.wtp.contextRoot>
    </properties>
    <dependencies>
        <!-- Compile -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!-- Provided -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- Test -->
        <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>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <useSystemClassLoader>false</useSystemClassLoader>
                </configuration>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>
                                            io.spring.javaformat
                                        </groupId>
                                        <artifactId>
                                            spring-javaformat-maven-plugin
                                        </artifactId>
                                        <versionRange>
                                            [0.0.6,)
                                        </versionRange>
                                        <goals>
                                            <goal>validate</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore></ignore>
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>
View Code

以上為該Demo官網pom文件,但其中內容個人覺得有多余,spring-boot-starter-tomcat和tomcat-embed-jasper在spring-boot-starter-web中已經有引用,所以可以去掉

啟動主函數

頁面訪問:http://localhost:8080/

頁面訪問:http://localhost:8080/foo

一、本例中啟動類繼承了SpringBootServletInitializer,重寫了configure方法,如果去掉該類的集成,能不能正常運行程序,其實是可以的(添加server.port=8081端口,與8080區分,測試)

二、SpringBootServletInitializer是做什么用處的?

springboot官方文檔中 “91.1 Create a Deployable War File”有對該類的具體描述

三、按照當前pom.xml中配置,打包(eclipse中執行package),出現以下異常

[ERROR] Failed to execute goal io.spring.javaformat:spring-javaformat-maven-plugin:0.0.6:validate (default) on project spring-boot-sample-web-jsp: Formatting violations found in the following files:

日志中也給出了建議,使用:spring-javaformat:apply修復該問題

spring-javaformat:apply執行結束后,再次執行package,打包成功,打包過程中,會有很多的jar包下載。

進入到target目錄,執行:java -jar .\spring-boot-sample-web-jsp-2.1.2.RELEASE.war,程序啟動后,頁面訪問正常。

四、上面官方文檔已經講,打成可執行jar包,不支持JSP,下面嘗試一下,是否如此,首先去掉主函數中集成SpringBootServletInitializer類,去掉重寫的方法,pom.xml中war改為jar

  1、運行主函數,jsp可正常訪問

  2、執行clean package打包,打包時出現異常,也許此異常與JSP無關,但此處就不在進行處理重新打包,畢竟官網也已經聲明可執行jar不支持JSP

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-checkstyle-plugin:3.0.0:check (checkstyle-validation) on project spring-boot-sample-web-jsp: You have 2 Checkstyle violations. -> [Help 1]

五、以上demo跑通后,也需要自己新建一個使用jsp的web項目,來運行測試下。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM