Right now your shortener shortens anything it gets, and a body with no "url" even crashes it with a 500. Short links are clicked by strangers, so the app should check what it gets first. Bad input is turned away with 400 Bad Request, before anything is counted or stored.
Two tools do the checking. A map's getOrDefault(key, default) reads a key without giving you null: when the key is missing, you get the default instead. A string's startsWith method tells you whether it begins with a given text. Here is the same idea on another route, a list of tags that only accepts names starting with #:
@PostMapping("/tags")
Object createTag(@RequestBody Map<String, Object> data) {
String name = (String) data.getOrDefault("name", "");
if (!name.startsWith("#")) {
return ResponseEntity.status(400).body(Map.of("error", "A tag starts with #"));
}
tags.add(name);
return ResponseEntity.status(201).body(Map.of("name", name));
}
Only addresses that start with http:// or https:// are web pages to send people to. Without that start, a browser reads www.python.org as a page of your own app, and ftp: or javascript: addresses don't belong behind a link strangers click. One more rule: the same URL sent twice gets the code it already has, with 200 OK, because nothing new was created. These are the test requests, in order:
POST /links {"url": "https://www.python.org/downloads/"} → 201 {"code": "1", "url": "https://www.python.org/downloads/"}
POST /links {"url": "ftp://files.example.com/report.pdf"} → 400 {"error": "The URL must start with http:// or https://"}
POST /links {"url": "javascript:alert(1)"} → 400 {"error": "The URL must start with http:// or https://"}
POST /links {"url": "www.python.org"} → 400 {"error": "The URL must start with http:// or https://"}
POST /links {} → 400 {"error": "The URL must start with http:// or https://"}
POST /links {"url": "http://example.com/old-page"} → 201 {"code": "2", "url": "http://example.com/old-page"}
POST /links {"url": "https://www.python.org/downloads/"} → 200 {"code": "1", "url": "https://www.python.org/downloads/"}
GET /links/3/stats → 404 {"error": "Link not found"}
GET /2 → 302 Location: http://example.com/old-page
Your task: in createLink, read the URL with getOrDefault and the default "", and answer 400 with the error above when it starts with neither http:// nor https://. Then, before making a new code, loop over links.keySet(): if a stored link has the same URL, answer its code and URL with 200.
Assignment
Follow the Coding Tutorial to make createLink accept only real web addresses and give a URL it already knows its old code.
Hint
Both checks go above counter += 1, so a refused or repeated URL uses up no number: that is why GET /links/3/stats answers 404. A for-each loop over links.keySet() gives the map's keys, here the codes. Compare strings with .equals(...), not ==.
Free plan: 30 tutor messages. PRO is unlimited.
