Servlet 3.1 国际化 - 区域设置 - 语言
Servlet 可以输出以西欧语言(如英语、西班牙语、德语、法语、意大利语、荷兰语等)编写的页面
但为了能正确的显示所有的字符,要做到以下几点:
- 必须设置 Content-Language 响应头
- 使用 HTML 实体显示所有的特殊字符,例如,"ñ" 表示 "ñ","¡" 表示 "¡"
cn/twle/demo/DisplaySpanishServlet.java
// author: 简单教程(www.twle.cn) // Copyright © 2015-2065 www.twle.cn. All rights reserved. package cn.twle.demo; import java.io.*; import java.util.Locale; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name = "DisplaySpanishServlet", urlPatterns = {"display_spanish"}, loadOnStartup = 1) public class DisplaySpanishServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // 设置西班牙语言代码 response.setHeader("Content-Language", "es"); String title = "En Español - Servlet 基础教程 | 简单教程(www.twle.cn)"; String docType = "<!DOCTYPE html> \n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body>\n" + "<p>" + title + "</p>" + "<p>" + "En Español:" + "</p>\n" + "<p>" + "¡Hola Mundo!" + "</p>\n" + "</body></html>"); } }
在浏览器上输入 http://localhost:8080/servlet/display_spanish 显示结果如下