springBoot thymeleaf 配置template might not exist or might not be acces 及静态资源 static

解决方法:

1、确定模板是否在默认templates文件夹里面,并且路径要和返回的View名字一致。

2、new ModelAndView("/login");这样写是不对,应该把开头的斜杠去掉,改成:new ModelAndView("login");

这种方法适用我配置的,

结构图:

springboot 打成 jar包没有webapp的这个要注意,不能把页面放在webapp下;



From : https://blog.csdn.net/u013185616/article/details/73647955

二 静态资源

1.1:默认方式

在SpringBoot中加载静态资源和在普通的web应用中不太一样。静态资源(js、css、图片等资源)默认目录位置需置于classpath下,并且符合以下目录规则:

  • /static
  • /public
  • /resources
  • /META-INF/resources

我们通过一个例子来看下,先来看一个目录结构: 
这里写图片描述 
我们在resources目录下新建一个目录static,其下面又有个image目录,static符合我们上面所说的springboot默认的静态资源目录,所以我们如果访问这个图片,就可以通过http://localhost:8080/image/timg.jpg。也就是说,上面那几个目录,都是静态资源的映射路径,优先级顺序为:META-INF/resources > resources > static > public 
建议:直接使用Spring Boot的默认配置方式

1.2 修改默认方式
  1. 配置文件方式
# 默认值为 /**
spring.mvc.static-path-pattern=
# 默认值为 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
spring.resources.static-locations=这里设置要指向的路径,多个使用英文逗号隔开
  • 1
  • 2
  • 3
  • 4

比如我把spring.mvc.static-path-pattern=/demo/**,那么上面我们的那个图片就需要通过http://localhost:8080/demo/image/timg.jpg才能访问的到,如果我改了下面的locations,那么我图片依然在static就不能访问的到了。 
2. WebMvcConfigurerAdapter 
通过写一个类继承WebMvcConfigurerAdapter,重写其addResourceHandlers方法,可以增加一些资源路径的配置:

import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by gonghao on 2017/6/3.
 */
//@EnableWebMvc :如果添加了该注解,则是完全控制MVC,谨慎使用
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter{
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/myResource/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/myResource/");
        registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/");
        super.addResourceHandlers(registry);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

这里我们没有使用@EnableWebMvc注解,所以我们这里是增加了一些资源路径的配置,而不是完全修改默认的资源路径配置。也就是说我增加了这个配置后:我通过http://localhost:8080/static/image/timg.jpghttp://localhost:8080/image/timg.jpg都可以访问到图片。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值