1、如何设置web静态页面的路径addResourceHandlers
springboot默认的静态页面是resources/static文件夹
如果集成WebMvcConfigurationSupport这个方法,就必须自己设定静态页面路径。否则无法访问静态页面路径。
如果想改其他的路径才会用到如下的方法
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("开始进行静态资源映射");
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/");
}
classpath变量是什么意思
参考:https://segmentfault.com/a/1190000015802324
java和和resources在编译后会编程classes文件夹下的com和static对应的文件,所以classpath可以理解为java或resources文件夹
2、设置默认的访问主页index.html
参考:Spring Boot 默认跳转到index.html的二种方式
springboot 2.3.2如何从后台以请求至vue前端页面
HttpServletResponse.sendRedirect这个方法,实现跳转页面
package com.tj.demo.system.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
@RequestMapping("/")
public class IndexController {
/**
* Get访问根路径是跳转到index.html页面
*
* @param response
* @throws IOException
*/
@GetMapping
public void toIndex(HttpServletResponse response) throws IOException {
response.sendRedirect("/index.html");
}
}
附录:完整配置文件WebMvcConfig
package com.tj.demo.config;
import com.tj.demo.utils.JacksonObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.List;
@Slf4j
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
/**
* springboot默认的静态页面是static,
* 但是如果集成WebMvcConfigurationSupport后,就必须指定设置web静态资源映射
* 否则无法访问html的页面
* "/**"表示根路径,访问路径例如:http://localhost:8084/index.html
* 如果设置"/web/**",那么访问连接就要加上/web,例如:http://localhost:8084/web/index.html
*
* @param registry
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("开始进行静态资源映射");
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/");
// registry.addResourceHandler("/templates/**")
// .addResourceLocations("classpath:/template/");
}
/**
* 扩展MVC框架的消息转换器
*
* @param converters
*/
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
//创建消息转换器对象
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
//设置对象转换器,底层使用Jackson将Java对象转为json
messageConverter.setObjectMapper(new JacksonObjectMapper());
//将上面的消息转换对象追加到mvc框架的转换器集合中
converters.add(0, messageConverter);
}
}