SpringBoot使用JSP(官网Demo)

Stella981
• 阅读 513

最开始接触java的时候,前端页面基本都是用jsp来写,最近公司项目要使用SpringBoot重构,查看SpringBoot文档,发现SpringBoot不建议使用JSP,因为jsp在使用内嵌servlet容器时会有一些限制

SpringBoot使用JSP(官网Demo)

虽然以后项目中也会将jsp替换成Template Engines,而且这都是前端的事情,其实与后端并无比较大的联系,但比较好奇Springboot中对jsp的使用,故根据官方文档进行了简单测试验证

SpringBoot使用JSP(官网Demo)

如果使用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项目,导入时可能出现以下异常

SpringBoot使用JSP(官网Demo)

点击finish -- ok,pom.xml文件中出现异常

SpringBoot使用JSP(官网Demo)

 选择Mark goal validate as ignored in pom.xml忽略掉该信息

SpringBoot使用JSP(官网Demo)

点击OK

此时若项目上还有红色的叉号,则在项目名称上右键 -- Maven -- Update Project -- OK。

项目结构

SpringBoot使用JSP(官网Demo)

包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

SpringBoot使用JSP(官网Demo) SpringBoot使用JSP(官网Demo)

<?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/

SpringBoot使用JSP(官网Demo)

页面访问:http://localhost:8080/foo

SpringBoot使用JSP(官网Demo)

一、本例中启动类继承了SpringBootServletInitializer,重写了configure方法,如果去掉该类的集成,能不能正常运行程序,其实是可以的(添加server.port=8081端口,与8080区分,测试)

二、SpringBootServletInitializer是做什么用处的?

springboot官方文档中 “91.1 Create a Deployable War File”有对该类的具体描述

SpringBoot使用JSP(官网Demo)

三、按照当前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项目,来运行测试下。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Easter79 Easter79
2年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Easter79 Easter79
2年前
SpringBoot使用JSP(官网Demo)
最开始接触java的时候,前端页面基本都是用jsp来写,最近公司项目要使用SpringBoot重构,查看SpringBoot文档,发现SpringBoot不建议使用JSP,因为jsp在使用内嵌servlet容器时会有一些限制!(https://img2018.cnblogs.com/blog/562030/201901/56203020190120
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这