springboot同时支持jsp和html

半兽人 发表于: 2018-08-27   最后更新时间: 2020-07-09 20:09:40  
{{totalSubscript}} 订阅, 14,175 游览

默认情况下,springboot是不支持jsp的访问的。那么本项目提供以下支持:

  • SpringBoot同时访问html和jsp
  • SpringBoot以jar包运行
  • SpringBoot支持thymeleaf

项目结构:

.
├── pom.xml
├── springboot-jsp-html.iml
└── src
    └── main
        ├── java
        │   └── org
        │       └── dreams
        │           └── forepart
        │               ├── Application.java
        │               ├── ViewResolverConfiguration.java
        │               └── controller
        │                   └── IndexController.java
        ├── resources
        │   └── application.properties
        └── webapp
            ├── css
            │   └── global.css
            ├── html
            │   └── index.html
            ├── img
            │   └── orcHome.png
            └── jsp
                └── index.jsp

pom参数:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.dreams</groupId>
    <artifactId>springboot-jsp-html</artifactId>
    <version>1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
    </parent>

    <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-thymeleaf</artifactId>
        </dependency>

        <!-- 热部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </dependency>

        <!--jsp页面使用jstl标签-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <!--Provided  start-->
        <!--War包部署到外部的Tomcat中已经包含了这些,所以需要添加以下依赖 否则会和内嵌的Tomcat 容器发生冲突 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>

        <!--用于编译jsp-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.4.2.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <!-- 打包时将jsp文件拷贝到META-INF目录下-->
            <resource>
                <!-- 指定resources插件处理哪个目录下的资源文件 -->
                <directory>src/main/webapp</directory>
                <!--注意此次必须要放在此目录下才能被访问到-->
                <targetPath>META-INF/resources</targetPath>
                <includes>
                    <include>**/**</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/**</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

</project>

多视图实现的视图解析器

package org.dreams.forepart;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ITemplateResolver;

@Configuration
public class ViewResolverConfiguration {
    @Configuration//用来定义 DispatcherServlet 应用上下文中的 bean
    @EnableWebMvc
    @ComponentScan("org.dreams.forepart")
    public class WebConfig implements WebMvcConfigurer {
        @Bean
        public ViewResolver viewResolver() {
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix("/jsp/");
            resolver.setSuffix(".jsp");
            resolver.setViewNames("*");
            resolver.setOrder(2);
            return resolver;
        }

        @Bean
        public ITemplateResolver templateResolver() {
            SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
            templateResolver.setTemplateMode("HTML5");
            templateResolver.setPrefix("/");
            templateResolver.setSuffix(".html");
            templateResolver.setCharacterEncoding("utf-8");
            templateResolver.setCacheable(false);
            return templateResolver;
        }

        @Bean
        public SpringTemplateEngine templateEngine() {
            SpringTemplateEngine templateEngine = new SpringTemplateEngine();
            templateEngine.setTemplateResolver(templateResolver());
            // templateEngine
            return templateEngine;
        }

        @Bean
        public ThymeleafViewResolver viewResolverThymeLeaf() {
            ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
            viewResolver.setTemplateEngine(templateEngine());
            viewResolver.setCharacterEncoding("utf-8");
            viewResolver.setOrder(1);
            viewResolver.setViewNames(new String[]{"html/*", "vue/*"});
            return viewResolver;
        }

        @Override
        public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
            configurer.enable();
        }

        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/img/**").addResourceLocations("/img/");
            registry.addResourceHandler("/static/**").addResourceLocations("/WEB-INF/" + "/static/");
        }
    }
}

页面跳转逻辑层

package org.dreams.forepart.controller;

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

@Controller
public class IndexController {

    @RequestMapping("/jsp")
    public String jsp(Model model) {
        model.addAttribute("message", "this is index jsp page!");
        return "index";
    }

    @GetMapping("/html")
    public String testThemleaf(Model model) {
        model.addAttribute("message", "this is index html page!");
        return "html/index";
    }
}

jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="/css/global.css" />
</head>
<body>
<img src="/img/orcHome.png"/>
${message}
</body>
</html>

html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/css/global.css" />
</head>
<body>
<img src="/img/orcHome.png"/>
<span th:text="${message}"></span>
</body>
</html>

运行入口

package org.dreams.forepart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

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

测试访问

https://localhost:8080/jsp
https://localhost:8080/html

git完整源码地址

更新于 2020-07-09

戏子 3年前

为什么要写在ViewResolverConfiguration中
为啥我完全按照您的步骤写,还是不能跳转到jsp,一直提示找不到,求指导

半兽人 -> 戏子 3年前

这真的指导不了的,要调试的。

这两句代码不要

@Configuration
public class ViewResolverConfiguration {
憨豆先生 3年前

感谢楼主

没有git地址啊

隐藏内容里。

  4年前

大佬,git地址怎么没有了

半兽人 ->   4年前

隐藏内容吧。

我也碰到了 无法加载css的问题 并且任何访问进来都会被识别成error

我重新拉代码下来看看

我更新了代码,加了css的测试,是可以的呀?

重新拉取下代码看看

要配置资源路劲吧,这里面加

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
  registry.addResourceHandler("/img/**").addResourceLocations("/img/");
  registry.addResourceHandler("/static/**").addResourceLocations("/WEB-INF/" + "/static/");
}
ash 5年前

请问这么操作之后html无法加载.css和图片怎么办呀?

半兽人 -> ash 5年前

提示的错误是啥?

ash -> 半兽人 5年前

没提示,就是不显示图片,也没有css样式,我试过把图片和css文件放在resources/static、resources、webapp、webapp\html下,都不好使

半兽人 -> ash 4年前

怎么会,我新增加了css做测试,也是ok的。

呉“某某”亽 -> ash 8月前

要配置资源路劲吧,这里面加

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/img/**").addResourceLocations("/img/");
    registry.addResourceHandler("/static/**").addResourceLocations("/WEB-INF/" + "/static/");
}

感谢,祝大佬工作顺利!!!

谢谢哈,中秋节快乐。

application.properties 文件怎么配置的

server.port=8080
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8

有例子没

这个就是呀

查看SpringBoot更多相关的文章或提一个关于SpringBoot的问题,也可以与我们一起分享文章