首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java 後端返回 HTML 標籤給瀏覽器:設定 Content-Type 為 text/html

     編輯:程式設計疑難解答

問題:Controller 返回字串包含 `

...
`,瀏覽器顯示原始標籤而非渲染。

原因:預設 `Content-Type: application/json` 或 `text/plain`,瀏覽器不解析 HTML

解決:明確設定回應標頭


// Spring MVC
@GetMapping("/html")
public void html(HttpServletResponse response) throws IOException {
    response.setContentType("text/html; charset=UTF-8");
    response.getWriter().write("
Hello HTML
"); } // 或返回 String 配合 @ResponseBody + produces @GetMapping(value="/html2", produces = "text/html;charset=UTF-8") @ResponseBody public String html2() { return "
Hello HTML 2
"; } // Spring WebFlux @GetMapping(value="/html3", produces = "text/html;charset=UTF-8") public Mono html3() { return Mono.just("
Reactive HTML
"); }

關鍵點

  • `text/html` 告訴瀏覽器「這是 HTML 文件,請解析渲染」。
  • `charset=UTF-8` 避免中文亂碼。
  • 若用模板引擎 (Thymeleaf/FreeMarker/JSP),**不要加 `@ResponseBody`**,直接返回視圖名,容器自動設 `text/html`。

常見誤區

  • 以為 `@ResponseBody` 返回字串自動變 HTML → 錯,預設 `application/json`。
  • 前端 `$.get(url, fn)` 預期 JSON,實際收 HTML → JS 解析報錯,**前端需 `dataType: 'html'` 或直接 `location.href` 跳轉**。

只要加上 `response.setContentType("text/html; charset=UTF-8")` 或 `produces = "text/html;charset=UTF-8"`,瀏覽器即可正確渲染後端返回的 HTML 片段。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved