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

Spring Boot无法渲染HTTP视图,浏览器报‘无法访问网站’求助

问题描述

我使用ModelAndView结合Thymeleaf展示列表,尝试通过Controller渲染页面。Postman能成功获取JSON格式结果,但浏览器访问时显示“无法访问网站”。已完成以下操作:添加Thymeleaf依赖、Web Starter,配置Thymeleaf属性,Postman可正常获取JSON结果。

Thymeleaf页面代码

<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>会议申请管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
          crossorigin="anonymous">
</head>
<body>
<div class="container-5">
    <h2>会议场次列表 </h2>
    <hr/>
    <a th:href="@{/session-form}" class="btn btn-primary mb-2">添加场次</a>

    <table class="table table-header table-striped">
        <thead>
            <tr>
                <th> 场次ID </th>
                <th> 场次名称 </th>
                <th> 场次描述</th>
                <th> 时长</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="se: ${sessions}">
                <td th:text="${se.session_id}"></td>
                <td th:text="${se.session_name}"></td>
                <td th:text="${se.session_description}"></td>
                <td th:text="${se.session_length}"></td>
            </tr>
        </tbody>
    </table>

    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"
            integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3"
            crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js"
            integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V"
            crossorigin="anonymous"></script>
</div>
</body>
</html>

注:原页面存在3处问题:container=5应为container-5;script标签错误放置在thead的tr中,已调整到页面底部;多余空tr已删除;Thymeleaf表达式改用直接属性名替代getter方法,符合框架规范。

Controller代码

package com.example.springboot.controller;

import com.example.springboot.model.Session;
import com.example.springboot.repositery.SessionRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class SessionController {
    @Autowired
    private SessionRepository sessionRepository;

    @GetMapping("/show-session")
    public ModelAndView showSession(){
        ModelAndView muv = new ModelAndView("show-session");
        List<Session> list = sessionRepository.findAll();
        muv.addObject("sessions", list);
        return muv;
    }

    @GetMapping("/session-form")
    public ModelAndView sessionsForm() {
        ModelAndView muv = new ModelAndView("session-form");
        muv.addObject("session", new Session());
        return muv;
    }

    @PostMapping("/save-session")
    public String saveSession(@ModelAttribute final Session session) {
        sessionRepository.saveAndFlush(session);
        return "redirect:/show-session";
    }

    @GetMapping("/sessions/{id}")
    @ResponseBody
    public Session get(@PathVariable Long id) {
        return sessionRepository.getReferenceById(id);
    }

    @DeleteMapping("/sessions/{id}")
    public void delete(@PathVariable Long id){
        sessionRepository.deleteById(id);
    }

    @PutMapping("/sessions/{id}")
    @ResponseBody
    public Session update(@PathVariable Long id, @RequestBody Session session){
        Session existSession = sessionRepository.getReferenceById(id);
        BeanUtils.copyProperties(session, existSession, "session_id");
        return sessionRepository.saveAndFlush(existSession);
    }
}

注:原Controller存在优化点:REST接口需添加@ResponseBody注解才能返回JSON;表单提交后改用redirect重定向,避免重复提交;冗余代码已简化。

POM依赖代码

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.5</version>
        <relativePath/> <!-- 从仓库查找父依赖 -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springBoot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springBoot</name>
    <description>Spring Boot 演示项目</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <!-- 补充JPA依赖用于数据库操作 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- 补充H2内存数据库便于测试 -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>
</project>

注:原POM缺少JPA及数据库依赖,这会导致sessionRepository.findAll()执行失败,进而引发页面无法访问。

排查与解决要点

  • 页面路径检查:确保Thymeleaf页面文件放置在src/main/resources/templates目录下,文件名与Controller中指定的视图名称完全一致(如show-session.html)
  • 访问地址验证:确认Spring Boot应用启动端口(默认8080),浏览器访问地址应为http://localhost:8080/show-session
  • 日志排查:查看应用启动日志,检查是否存在Bean初始化失败、数据库连接异常等错误
  • REST接口规范:返回JSON的接口必须添加@ResponseBody注解,或改用@RestController标记类
  • 依赖完整性:必须添加JPA及数据库驱动依赖,否则数据查询会抛出异常导致页面无法加载

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:27:00