728x90
현재 개발은
vue 서버 + spring boot 서버
각각 켜서 작업하고 있다.
router는
그냥 화면전환용 url이기 때문에
이벤트를 이용해
this.$router.push 형식으로
화면변환을 시키면 router가 작동은 한다.
문제는
새로고침 혹은 url을 직접 치고 들어갔을 때다.
url은 서버에서 제일 먼저 받아서 처리한다.
해당 api url이 없는 경우 404를 뱉는다.
그래서 처리할 수 있는 방법이 2가지가 있다.
1. ErrorController
2. WebMvcConfigurer
두 가지를 살펴보자
1. ErrorController
spring에서 에러가 나면
/error라는 내장된 경로를 통해 404 페이지를 보여준다.
이것을 이용해서
api에 해당하는 url이 없으면
/error 에다가 매핑 시켜
index.html을 반환하게 한다.
spring boot에서의 설정은 다음과 같다.
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class RootController implements ErrorController{
@GetMapping("/error")
public String redirectRoot() {
System.out.println("에러핸들링 redirect 시작.. >>> ");
return "index.html";
}
}
2. WebMvcConfigurer
이것도 에러핸들링과 비슷하지만 조금 더 정확하게 처리하는 방법 같다.
소스를 보면 리졸버를 미리 만들어 놓고 대기시킨다.
요청한리소스가 없으면 /static/index.html 정적리소스를 리턴해준다.
스프링부트에서 자바소스는 다음과 같다.
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;
@Configuration
public class WebConfig implements WebMvcConfigurer{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**/*")
.addResourceLocations("classpath:/static/")
.resourceChain(true)
.addResolver(new PathResourceResolver() {
@Override
protected Resource getResource(String resourcePath, Resource location) throws IOException {
Resource requestedResource = location.createRelative(resourcePath);
return requestedResource.exists() && requestedResource.isReadable() ? requestedResource
: new ClassPathResource("/static/index.html");
}
});
}
}
/** <- 요거 쓰면
에러날 수도 있다.
그럴 땐
application.properties에 다음과 같이 설정해주자
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
'Spring' 카테고리의 다른 글
Spring boot) debug만 안켜지는 이유 (0) | 2024.02.05 |
---|---|
Spring boot) keytool로 ssl 생성하여 ssl 적용하기 (0) | 2024.02.05 |
spring boot) vue + spring boot websocket 웹소켓 proxy error (0) | 2024.01.28 |
SpringBoot) 이미지와 텍스트를 함께 보낼 때 (0) | 2024.01.18 |
mybatis) attempted to return null 에러 (0) | 2024.01.08 |