250x250
syk531
하루
syk531
전체 방문자
오늘
어제
  • 분류 전체보기 (166)
    • 개발 (166)
      • java (11)
      • kotlin (7)
      • spring, spring boot (35)
      • Javascript (4)
      • Tyhmeleaf (2)
      • Kafka (17)
      • Docker (8)
      • Kubernetes (3)
      • Elastic Stack (4)
      • react native (3)
      • Web (4)
      • GIS (3)
      • 리눅스 (16)
      • Windows (2)
      • 네트워크 (2)
      • 안드로이드앱 (5)
      • git (2)
      • Tool (15)
      • 프로젝트 (7)
      • 백준알고리즘 (14)
      • DB (2)

인기 글

최근 글

블로그 메뉴

    공지사항

    태그

    • 오블완
    • 뉴스앱
    • 티스토리챌린지

    최근 댓글

    티스토리

    hELLO · Designed By 정상우.
    syk531

    하루

    개발/spring, spring boot

    Kotlin을 사용한 sitemap.xml 자동 생성 방법 (Spring Boot)

    2024. 9. 5. 10:08
    728x90
    반응형

    웹사이트의 SEO를 강화하려면 sitemap.xml 파일이 필요합니다. 이 파일은 검색 엔진 크롤러가 사이트 구조를 이해하고 색인화하는 데 도움을 줍니다. 하지만 매번 수동으로 sitemap.xml을 업데이트하는 것은 번거로울 수 있습니다. 여기서 사이트맵 파일을 자동으로 관리하고, 새로운 페이지가 추가될 때마다 사이트맵이 업데이트하는 방법을 사용합니다.

     

    sitemap.xml 자동 생성하는 Kotlin 코드

    아래의 코드는 https://www.bestfeed.site/sitemap.xml 에 접속하면 sitemap.xml 파일이 자동으로 생성되고, 브라우저 또는 크롤러에 제공됩니다.

    @Controller
    class SitemapController(
        private val requestMappingHandlerMapping : RequestMappingHandlerMapping
    ) {
    
        @GetMapping("/sitemap.xml", produces = ["application/xml"])
        fun getSitemap(response: HttpServletResponse) {
            val sitemapXml = genSitemapXml()
            response.contentType = "application/xml"
            response.writer.write(sitemapXml)
        }
    
        fun genSitemapXml() : String {
            val host = "https://www.bestfeed.site"
            val sb = StringBuilder()
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
            sb.append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n")
    
            val now = LocalDateTime.now()
            val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX")
            // UTC 기준으로 변환
            val formattedDateTime = now.atOffset(ZoneOffset.UTC).format(formatter)
    
            val handlerMethods = requestMappingHandlerMapping.getHandlerMethods()
            for (entry in handlerMethods.entries) {
                entry.key.pathPatternsCondition?.patterns?.forEach { url ->
                    sb.append("  <url>\n")
                    sb.append("    <loc>${host}${url}</loc>\n")
                    sb.append("    <lastmod>${formattedDateTime}</lastmod>\n")
                    sb.append("  </url>\n")
                }
            }
    
            sb.append("</urlset>")
    
            return sb.toString()
        }
    }

     

     

    참고자료

    https://stackoverflow.com/questions/50444160/how-can-i-do-google-sitemap-for-spring-boot-application

    https://youseong.me/auth/skillboard/details/11

    728x90
    반응형
    저작자표시 (새창열림)

    '개발 > spring, spring boot' 카테고리의 다른 글

    @Bean 객체 이름 설정  (0) 2024.11.19
    Spring Boot: Configuration Class 오류 해결 방법 - I/O Failure  (2) 2024.09.13
    [Java] [Gradle] Your build is currently configured to use Java 21 and Gradle 7.6.1. 에러 수정  (0) 2024.07.17
    Spring Boot 의존성 확인 방법  (0) 2024.07.02
    [Spring integration] TCP 연결 끊김 처리, connectionId  (0) 2024.06.25
      '개발/spring, spring boot' 카테고리의 다른 글
      • @Bean 객체 이름 설정
      • Spring Boot: Configuration Class 오류 해결 방법 - I/O Failure
      • [Java] [Gradle] Your build is currently configured to use Java 21 and Gradle 7.6.1. 에러 수정
      • Spring Boot 의존성 확인 방법
      syk531
      syk531
      기억을 위해 기록을.

      티스토리툴바