java - 如何重定向到 Java/Spring 控制器中的 URL
问题描述
我正在构建一个 URL 缩短器并正在研究“跟随方法” - 例如 short.li/?stub=dishpods 应该重定向到 https://www.amazon.com/gp/product/B07CTQ8THP/ref=ppx_yo_dt_b_asin_title_o00_s00?ie= UTF8&psc=1
如何在我的控制器中设置此自动重定向?我能想到的最好的方法是打印到控制台,但我希望它自动跟随。
@GetMapping("/")
void follow(@RequestParam String stub) throws IOException, InterruptedException {
ShortUrl longUrl = repository.findByShortUrl(stub);
String longUrlString;
if (longUrl != null) {
longUrlString = longUrl.getShortUrl();
} else {
longUrlString = "https://google.com";
}
try {
URL myurl = new URL(longUrlString);
con = (HttpURLConnection) myurl.openConnection();
con.setRequestMethod("GET");
StringBuilder content;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String line;
content = new StringBuilder();
while ((line = in.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
}
System.out.println(content.toString());
} finally {
con.disconnect();
}
}
解决方案
您可以使用弹簧RedirectView:
@GetMapping("/")
public RedirectView follow() {
return new RedirectView("www.foo.baa");
}
推荐阅读
- javascript - 我如何将这个代码片段从一个类重构为功能组件反应?
- mysql - 显示像'a_'这样的表格,仅以a开头并以数字结尾
- python - 报告编写软件的建议,以生成类似于月度经纪报表的报告
- javascript - 如何检查 Key inv_ 是否具有 Deer Quick.db 的值
- javascript - JavaScript中的分组运算符()和Eager评估策略
- c++ - 获取任意数量对象的可变参数函数
- glsl - 如何在 GLSL 着色器中获取对象 ID
- r - 根据按列值分组连接行
- javascript - 在 three.js 中将对象一起添加会导致它们移动
- sql - 如何使用来自另一个 SQL 服务器的数据创建表/视图?