Spring Boot - Sitemap xml 생성하기
SpringBoot 에서 RestController 호출로 사이트맵을 생성해 리턴하려고 합니다.
사용방법은 간단합니다.
사이트맵 규칙에 맞춰 xml을 생성하고, String으로 Response 해주면 끝이지요!
아래 예제를 보시고 한번 따라해보세요!
1. SiteMapController.java 생성
@RestController
public class SiteMapController {
@Autowired
private SiteMapService siteMapService;
@RequestMapping(value="/sitemap.xml", produces= {"application/xml"})
@ResponseBody
public ResponseEntity<String> sitemap (HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
return ResponseEntity.ok(siteMapService.getSystemicSiteMap());
}
}
2. SiteMapService.java 생성
- @Service
public class SiteMapService {
public static final String BASE_URL = "http://www.site.com";
public static final String BEGIN_DOC = "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";
public static final String END_DOC = "</urlset>";
public static final String CHANGEFREQ_ALWAYS = "always";
public static final String CHANGEFREQ_HOURLY = "hourly";
public static final String CHANGEFREQ_DAILY = "daily";
public static final String CHANGEFREQ_WEEKLY = "weekly";
public static final String CHANGEFREQ_MONTHLY = "monthly";
public static final String CHANGEFREQ_YEARLY = "yearly";
public static final String CHANGEFREQ_NEVER = "never";
public String getSystemicSiteMap() throws UnsupportedEncodingException {
Date now = new Date();
StringBuffer sb = new StringBuffer();
sb.append(BEGIN_DOC);
sb.append(new SiteMap(BASE_URL, now, CHANGEFREQ_NEVER, "1.0"));
return sb.toString();
}
}
3. Sitemap.java 생성
public class SiteMap {
private static final SimpleDateFormat SITE_MAP_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
public SiteMap(String loc) {
this.loc = loc;
this.lastmod = new Date();
this.changefreq = SiteMapService.CHANGEFREQ_NEVER;
this.priority = "1.0";
}
public SiteMap(String loc, Date lastmod, String changefreq, String priority) {
this.loc = loc;
this.lastmod = lastmod;
this.changefreq = changefreq;
this.priority = priority;
}
/**
* url
*/
private String loc;
/**
* yyyy-MM-dd
*/
private Date lastmod;
/**
* always hourly daily weekly monthly yearly never
*/
private String changefreq;
/**
* 1.0 0.9 0.8
*/
private String priority;
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public Date getLastmod() {
return lastmod;
}
public void setLastmod(Date lastmod) {
this.lastmod = lastmod;
}
public String getChangefreq() {
return changefreq;
}
public void setChangefreq(String changefreq) {
this.changefreq = changefreq;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("<url>");
sb.append("<loc>" + loc + "</loc>");
sb.append("<lastmod>" + SITE_MAP_DATE_FORMAT.format(lastmod) + "</lastmod>");
sb.append("<changefreq>" + changefreq + "</changefreq>");
sb.append("<priority>" + priority + "</priority>");
sb.append("</url>");
return sb.toString();
}
}