Servlet 3.1 国际化 - 区域设置 - 货币

Servlet 可以使用 java.text.NumberFormat 类及其静态方法 getCurrencyInstance() 来格式化数字(比如 long 类型或 double 类型)为特定于区域设置的货币

cn/twle/demo/CurrencyLocaleServlet.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;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.Date;

@WebServlet(name = "CurrencyLocaleServlet", urlPatterns = {"currency_locale"}, loadOnStartup = 1) 
public class CurrencyLocaleServlet extends HttpServlet{

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
    // 设置响应内容类型
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    // 获取客户端的区域设置
    Locale locale = request.getLocale( );
    NumberFormat nft = NumberFormat.getCurrencyInstance(locale);
    String formattedCurr = nft.format(1000000);

    String title = "特定于区域设置的货币 - Servlet 基础教程 | 简单教程(www.twle.cn)";
    String docType = "<!DOCTYPE html> \n";
      out.println(docType +
      "<title>" + title + "</title>" +
      "<p>" + title + "</p>" + 
      "<p>" + formattedCurr + "</p>");
  }
}

在浏览器上输入 http://localhost:8080/servlet/currency_locale 显示结果如下

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2018 简单教程 twle.cn All Rights Reserved.