场景
新建SpringBoot
项目,继承父项目,导入依赖。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qianyu</groupId>
<artifactId>demo</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
在/resources/templates/
文件夹下,新建index.html
文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<h1>index界面</h1>
<script type="application/javascript" src="/js/sayhello.js"></script>
<script>
hello();
</script>
</body>
</html>
index.html
文件里面引入的js
文件是/resources/static/js/
文件夹下的sayhello.js
function hello() {
alert('hello')
}
新建Controler
@Controller
public class IndexController {
@GetMapping("/")
public String index(){
return "index";
}
}
新建启动类,启动SpringBoot
程序:
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
可见js
文件顺利引入:
加入拦截器
新建拦截器,作用:打印访问网站的用户的ip地址
@Component
public class LogInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
System.out.println("ip :" + req.getRemoteAddr() + " 访问了网站");
return true;
}
}
配置拦截器:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Autowired
private LogInterceptor logInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(logInterceptor)
.addPathPatterns("/**");
}
}
再次访问网站:
解决方法
经查阅资料,参考文章:Spring注解@EnableWebMvc使用坑点解析,发现Spring Boot
默认提供Spring MVC
自动配置,不需要使用@EnableWebMvc
注解,于是将@EnableWebMvc
注释掉就可以访问静态资源了。