一般的项目的classpath是指 WEB-INF文件夹下的classes目录:
src路径下的文件在编译后会放到WEB-INF/classes路径下。默认的classpath是在这里。直接放到WEB-INF下的话,是不在classpath下的。用ClassPathXmlApplicationContext当然获取不到的。
classPath即为java文件编译之后的class文件的编译目录一般为web-inf/classes,src下的xml在编译时也会复制到classPath下
(1)ApplicationContext ctx = new ClassPathXmlApplicationContext("xxxx.xml"); //读取classPath下的spring.xml配置文件
(2)ApplicationContext ctx = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/xxxx.xml"); //读取WEB-INF 下的spring.xml文件
classpath 和 classpath* 区别:
classpath:只会到你的class路径中查找找文件;
classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找.
maven项目的classpath就是指src/main/java,src/main/resources,src/main/webapp,假如在main文件夹下新建一个文件properties,那么classpath在原有三个文件的基础上又多了一个src/main/properties,properties文件的路径默认采用的都是classpath,不需要加前缀,直接写包名即可
在Springboot中默认的静态资源路径有:classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,从这里可以看出这里的静态资源路径都是在classpath中(也就是在项目路径下指定的这几个文件夹)
springboot项目访问resources/templates目录下的html文件
pom文件中引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
在application.yml中添加访问请求配置
spring:
mvc:
static-path-pattern: /**
resources:
static-locations: classpath:/static/
thymeleaf:
prefix: classpath:/templates/
suffix: .html
cache: false #关闭缓存
然后通过control层接口映射到html页面,类必需要用@Controller
@RestController注解相当于@ResponseBody + @Controller合在一起的作用。
@Controller
public class HelloWorld{
@RequestMapping(value = "/hello")
public String hello(Model model) throws Exception {
return "/hello";
}
}
1) 如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,或者html,配置的视图解析器 InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
2) 如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。