java實(shí)現(xiàn)短地址服務(wù)的方法(附代碼)
假設(shè)下面是你的視頻網(wǎng)站鏈接列表,如果別人想爬取你的數(shù)據(jù)十分輕松,看規(guī)則就知道數(shù)據(jù)庫(kù)是序列自增的
http://www.xxxx.com/video/1
http://www.xxxx.com/video/2
http://www.xxxx.com/video/3
那么解決這一問(wèn)題,我們可以使用短地址,不對(duì)外暴露真實(shí)鏈接,使用對(duì)稱加密是一個(gè)很好的方案。
Hashids是一個(gè)很好的選擇,它提供了JS/PHP/JAVA/PYTHON等編程語(yǔ)言的實(shí)現(xiàn),這里我使用的就是它。
下面是我基于blade框架搭建的java短地址服務(wù)。
CREATE TABLE `t_url` ( `id` int(10) NOT NULL AUTO_INCREMENT, `url` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
路由
@Path public class IndexRoute { // 鹽值 private static final Hashids HASHIDS = new Hashids("blade-shorturl"); private UrlModel urlModel = new UrlModel(); @Route("/:key") public void get(Request req, Response response) { String key = req.pathParam(":key").replaceAll("[^A-Za-z0-9]", ""); long[] numbers = HASHIDS.decode(key); if (null == numbers || numbers.length < 1) { response.text("沒有找到"); return; } int id = (int) numbers[0]; String result = get(id).getUrl(); if (result == null) { response.text("沒有找到"); return; } response.redirect(result); } @Route(value = "/", method = HttpMethod.GET) public String index() { return "index"; } @Route(value = "/", method = HttpMethod.POST) public String save(Request request, Response response) { String resJsp = "index"; String longUrl = request.query("url"); if (!isURL(longUrl)) { request.attribute("error", "無(wú)效的URL"); return resJsp; } Integer id = this.save(longUrl); if (id == 0) { request.attribute("error", "保存失敗"); return resJsp; } String hash = HASHIDS.encode(id); request.attribute("url_hash", hash); System.out.println("id = " + id + ",url_hash=" + hash); return resJsp; } private Integer save(String url) { return urlModel.insert().param("url", url).executeAndCommit(); } private UrlModel get(int id) { return urlModel.fetchByPk(id); } private final String REGEX = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; private boolean isURL(String url) { if(StringKit.isNotBlank(url)){ Pattern pattern = Pattern.compile(REGEX); Matcher matcher = pattern.matcher(url); if (matcher.find()) { return true; } } return false; } }
實(shí)現(xiàn)效果:
代碼位置:https://github.com/bladejava/blade-shorturl
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
相關(guān)文章
String轉(zhuǎn)BigDecimal,BigDecimal常用操作,以及避免踩坑記錄
這篇文章主要介紹了String轉(zhuǎn)BigDecimal,BigDecimal常用操作,以及避免踩坑記錄,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07Java使用MulticastSocket實(shí)現(xiàn)群聊應(yīng)用程序
這篇文章主要為大家詳細(xì)介紹了Java使用MulticastSocket實(shí)現(xiàn)群聊應(yīng)用程序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05java實(shí)現(xiàn)合并單元格的同時(shí)并導(dǎo)出excel示例
這篇文章主要給大家介紹了關(guān)于java實(shí)現(xiàn)合并單元格的同時(shí)并導(dǎo)出excel的相關(guān)資料,文中先進(jìn)行了簡(jiǎn)單的介紹,之后給出了詳細(xì)的示例代碼,相信對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-03-03