You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中实现点击列表链接跳转到用户指定外部网站的方法

功能实现步骤

1. 修正现有前端代码问题

index.html 链接语法修正

你当前的th:href写法有误,变量引用错误且没有适配外部链接规则,修正后代码如下:

<td><a th:href="@{${website.link}}" target="_blank">Link</a></td>

说明:target="_blank"为可选配置,添加后点击链接会在新标签页打开,不会跳离你的站点。

new.html 表单修正

你当前div的对齐属性拼写错误,同时建议补充输入提示避免用户漏填协议:

<div align="left">
  <tr>
       <label class="form-label">Link</label>
       <td><input type="text" th:field="*{link}" class="form-control" 
       placeholder="请输入带协议的链接,例如https://www.example.com" /></td>
  </tr>
</div>

提示:你也可以给输入框加前端校验,判断如果用户输入的链接没有带http/https前缀,自动补全避免跳转失败。

2. 编写数据实体类(如果还未创建)

假设存储网站信息的实体类命名为Website,示例代码如下:

// 省略包导入和lombok配置(如果用lombok可直接用@Data注解省略getter/setter)
@Entity
public class Website {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String link; // 对应表单提交的链接字段
    // 可按需扩展网站名称、备注等其他字段
    // 补充getter、setter、无参构造方法
}

3. 编写Controller层代码

你需要三个核心接口,分别对应新增页面访问、网站信息保存、首页列表查询,示例代码如下:

// 省略包导入
@Controller
public class WebsiteController {

    // 注入你的数据访问层,这里以JPA的Repository为例,你也可以替换为自己的Service层
    @Autowired
    private WebsiteRepository websiteRepository;

    // 访问新增网站页面
    @GetMapping("/new")
    public String toAddPage(Model model) {
        model.addAttribute("website", new Website());
        return "new";
    }

    // 处理新增网站提交请求
    @PostMapping("/saveWebsite")
    public String save(@ModelAttribute Website website) {
        // 后端兜底补全协议,避免用户漏填导致跳转失败
        String link = website.getLink();
        if (!link.startsWith("http")) {
            website.setLink("https://" + link);
        }
        websiteRepository.save(website);
        // 保存成功后跳转到首页
        return "redirect:/index";
    }

    // 首页加载网站列表
    @GetMapping("/index")
    public String toIndex(Model model) {
        List<Website> websiteList = websiteRepository.findAll();
        model.addAttribute("websites", websiteList);
        return "index";
    }
}

4. 补充index.html列表遍历逻辑

你需要在index.html中遍历返回的网站列表,才能渲染所有用户添加的链接,完整示例如下:

<table>
  <!-- 遍历model里的websites集合 -->
  <tr th:each="website : ${websites}">
    <!-- 可按需展示其他字段,比如网站名称 -->
    <td><a th:href="@{${website.link}}" target="_blank">Link</a></td>
  </tr>
</table>

内容的提问来源于stack exchange,提问作者CandyCode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:45:02