SpringBoot 2.x 整合thymeleaf 和 jsp

3 篇文章 0 订阅
1 篇文章 0 订阅

个人github:https://github.com/tolzlz

个人github:https://github.com/tolzlz

个人github:https://github.com/tolzlz

因公司需要,须同时集成Thymeleaf框架和jsp框架,网络上方法不可用,都一个抄一个

( 一 ) 集成JSP和Thymeleaf配置,配置运行环境

( 二 ) 配置JSP和Thymeleaf运行环境下静态资源访问

测试环境:SpringBoot 2.1.1

一、引入代码包,在SpringBoot内置tomcat中启动,不排除包,直接引入

    pom文件中插入以下代码
     <!--jsp-->
     <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>

     <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>jstl</artifactId>
     </dependency>
     <!--jsp-->

二、application.yml中,可以加入以下代码(application.properties 同理),也可以不写,看个人习惯

spring:
  # 模板引擎
  thymeleaf:
    mode: HTML
    encoding: utf-8
    # 禁用缓存
    cache: false
    servlet:
      content-type: text/html
    suffix: .html

     注意:这些都不做任何配置


#spring.mvc.view.prefix=/WEB-INF/jsp/
#spring.mvc.view.suffix=.jsp
#spring.thymeleaf.view-names=thymeleaf/*

三、新建一个类,注入,来最简单的吧,直接在启动类MainApplication中注入,这里注意 @EnableWebMvc,后面要用到

@SpringBootApplication(exclude = ...)
//@EnableWebMvc
@Controller
public class MainApplication
{

    public static void main(String[] args)
    {
    	new SpringApplicationBuilder(AppApplication.class)
        .web(WebApplicationType.SERVLET)
        .run(args);
        // System.setProperty("spring.devtools.restart.enabled", "false");
       // SpringApplication.run(MainApplication.class, args);
        System.out.println("(♥◠‿◠)ノ゙     启动成功   ლ(´ڡ`ლ)゙  \n" );
    }


    @Bean
    public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
        ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
        resolver.setContentNegotiationManager(manager);

        List<ViewResolver> resolvers = new ArrayList<ViewResolver>();

        resolvers.add(jsonViewResolver());
        resolvers.add(jspViewResolver());
        resolvers.add(thymeleafViewResolver());
        resolver.setViewResolvers(resolvers);
        return resolver;
    }

    @Bean
    public ViewResolver jsonViewResolver() {
        return new ViewResolver() {

            @Override
            public View resolveViewName(String viewName, Locale locale) throws Exception {
                MappingJackson2JsonView view = new MappingJackson2JsonView();
                view.setPrettyPrint(true);
                return view;
            }
        };
    }


    @Bean
    public ViewResolver jspViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setContentType("text/html");
        viewResolver.setOrder(2);
        return viewResolver;
    }

    @Bean
    public ViewResolver thymeleafViewResolver() {

        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();

        viewResolver.setTemplateEngine(thymeleafTemplateEngine());
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setOrder(0);

        // Important!!
        // th_page1.html, th_page2.html, ...
        // 可以删除
        viewResolver.setViewNames(new String[] { "th_*" });

        return viewResolver;
    }

    // Thymeleaf template engine with Spring integration
    @Bean
    public SpringTemplateEngine thymeleafTemplateEngine() {

        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(thymeleafTemplateResolver());
        templateEngine.setEnableSpringELCompiler(true);

        return templateEngine;
    }

    @Bean
    public SpringResourceTemplateResolver springResourceTemplateResolver() {
        return new SpringResourceTemplateResolver();
    }

    // Thymeleaf template resolver serving HTML 5
    @Bean
    public ITemplateResolver thymeleafTemplateResolver() {

        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();

        templateResolver.setPrefix("templates/");
        templateResolver.setCacheable(false);
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCharacterEncoding("UTF-8");

        return templateResolver;
    }


    //thymeleaf 访问方式
    @RequestMapping("/api/index_ht")
    public String index(Model model) {
        model.addAttribute("name", "world");
        return "th_index";
    }

    //jsp访问方式
    @RequestMapping("/api/index")
    public String welcome(Model model) {
        model.addAttribute("name", "jsp world");
        return "index";
    }

}

可能会报空指针异常

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null

可能1:配置文件未导入

可能2:导入包重复

可能3:RequestContextListener为空,需要重新new

在MainApplication中,注入bean

    @Bean
    public RequestContextListener requestContextListenerBean() {
        return new RequestContextListener();
    }

四、新建类,重新web容器中进行部署,也可以直接继承MainApplication,我这里新建了个类

public class MainServletInitializer extends SpringBootServletInitializer
{
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
    {
        return application.sources(MainApplication.class);
    }
    
    
}

五,文件结构

    注意: templates和META-INF在同一级目录下

六、properties和yml 各类配置文件读取路径

配置文件统一在resources文件夹下,在webapp目录下,不放入任何文件

七、静态资源访问配置

这里是重点!!!!!!!!!!!!!!!!!!!

这里是重点!!!!!!!!!!!!!!!!!!!

这里是重点!!!!!!!!!!!!!!!!!!!

这里分为两种方式(源地址): 论坛链接

①  一种有@EnableWebMvc 修饰

  1. SpringBoot 的 @EnableAutoConfiguration 会启用自动配置类 WebMvcAutoConfiguration,该类配置了一些默认的静态资源映射
    • 自动映射 localhost:8080/** 为以下路径
      • classpath:/resources/
      • classpath:/static/
      • classpath:/public/
      • classpath:/META-INF/resources/
    • 自动映射 localhost:8080/webjars/** 为以下路径
      • classpath:/META-INF/resources/webjars/
  2. 此时,我们不需要多做什么,只要将静态资源放入 src/main/resources 目录下的 resources、static 或 public 文件夹下,即可通过 url 定位相关资源,例如 localhost:8080/index.html 可定位至 src/main/resources/static/index.html
  3. 注意:如果编写了以下的自定义配置,则以上默认配置将被取消。更确切的说,一旦自定义的配置不为空,则默认配置将不被采用。

 

@EnableWebMvc
@Configuration
@Component
public class WebResourceConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //配置静态资源处理
        registry.addResourceHandler("/**")
                .addResourceLocations("resources/", "static/", "public/",
                        "META-INF/resources/")
                .addResourceLocations("classpath:resources/", "classpath:static/",
                        "classpath:public/", "classpath:META-INF/resources/")
                .addResourceLocations("file:///tmp/webapps/");
    }
}

也可以采用

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\
  classpath:/static/,classpath:/public/,file:D://hehe

② 一种无@EnableWebMvc 修饰

 

  1. 如果使用了 @EnableWebMvc,则自动配置类 WebMvcAutoConfiguration 会失效,因此默认映射路径 /static, /public, META-INF/resources, /resources 都将失效
  2. 这种情况下,只能设置自定义配置
    • 无任何前缀 -> “文档根目录”(一般指代 src/main/webapp 目录), 例如 localhost:8080/index.html 定位至 src/main/webapp/static/index.html
    • 存在前缀 classpath -> 类路径(一般指代 src/main/resources 目录)
    • 存在前缀 file:// -> 文件系统路径(“绝对路径”)
@Configuration
public class GoWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //配置静态资源处理
        registry.addResourceHandler("/**")
                .addResourceLocations("resources/", "static/", "public/", 
                "META-INF/resources/")
                .addResourceLocations("classpath:resources/", "classpath:static/", 
                "classpath:public/", "classpath:META-INF/resources/")
                .addResourceLocations("file:///tmp/webapps/");
    }
}

八、项目案例

项目连接

(项目是别人的,里面无静态资源访问路径,如需要请自己配置一下)

如果解决问题,请点赞关注以下喽!!!!

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值