SpringBoot创建web项目静态资源路径配置

本文详细介绍如何在SpringBoot项目中正确配置并使用JSP页面,包括配置视图解析器、资源处理器及添加tomcat-embed-jasper依赖,解决访问JSP页面时遇到的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用springboot创建web项目,根据网上的教程都是在application配置文件中配置的

#spring boot视图配置
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

#静态文件访问配置
spring.mvc.static-path-pattern=/static/*

但是,配置完不起作用,每次访问能进后台controller,但是就是访问不到前台的jsp页面(springboot对jsp支持的支持非常不友好)

配置文件不起作用具体原因不太清楚,在网上搜索一番之后,需要在项目的启动类中添加对应的方法,或者创建一个config类(类似于配置文件),我采用了后者,创建了一个config类

package com.njws.rwgl;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
@ComponentScan
public class MvcConfiguration extends WebMvcConfigurationSupport {
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        registry.viewResolver(resolver);
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

因为Springboot对jsp不太友好所以需要添加  tomcat-embed-jasper  用来整合jsp

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>

注:WebMvcConfigurationSupport 可参考 

https://blog.youkuaiyun.com/weixin_41788754/article/details/82890515

https://blog.youkuaiyun.com/pinebud55/article/details/53420481

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值