监听器和国际化

一 监听器

作用:监听特定对象的创建或销毁,属性的变化。

Servlet中需要监听的对象:

request/session/servletContext

监听器接口:
一、监听对象创建/销毁的监听器接口
Interface ServletRequestListener 监听request对象的创建或销毁
Interface HttpSessionListener 监听session对象的创建或销毁
Interface ServletContextListener 监听servletContext对象的创建或销毁

二、监听对象属性的变化
Interface ServletRequestAttributeListener 监听request对象属性变化: 添加、移除、修改
Interface HttpSessionAttributeListener 监听session对象属性变化: 添加、移除、修改
Interface ServletContextAttributeListener 监听servletContext对象属性变化

三、session相关监听器
Interface HttpSessionBindingListener 监听对象绑定到session上的事件(不用在web.xml中配置)
Interface HttpSessionActivationListener(了解) 监听session序列化及反序列化的事件

监听器开发步骤:
1. 写一个普通java类,实现相关接口;
2. 在web.xml中配置

    <listener>
        <listener-class>cn.itcast.a_life.MyRequestListener</listener-class>
    </listener>

二 国际化

Locale类:封装语言,国家信息的对象。

jdk中的API:

Locale locale = Locale.getDefault();//当前系统默认的语言环境
locale.getLanguage();// 获取语言简称

servlet中的API:

request.getLocal();

2.1 国际化分为两部分:

2.1.1 静态数据国际化
固定的文本,如:用户名,密码
步骤:

1 在src文件夹下创建 properties 文件
2 properties文件命名规则:基础名语言简称国家简称.properties(如:msg_zh_US.properties)
3 获取国际化资源文件(2中的properties文件)通过ResourceBundle类
4 在properties里面添加kek-value 如:hello = 你好

示例代码:

Local local = Local.CHINA;//假设是中文环境
//创建工具类对象 包名:properties文件所在的文件夹名称   基础名:msg  
ResourceBundle bundle = ResourceBundle.getBundle("包名.基础名",local);
bundle.getString("hello");

2.1.2 动态数据国际化

数值,时间,货币,日期等在程序运行时动态产生的数据。

代码示例:

 //模拟语言环境
 Locale locale = Locale.US;
 NumberFormat nf = null;
 //国际化货币
 double money = 100;
 nf=NumberFormat.getCurrencyInstance(locale);
 nf.format(money);//国际化货币
 nf.parse("$100");//解析货币

 //国际化数字
 nf=NumberFormat.getNumberInstance();
 nf.format(10000);//国际化数字
 nf.format(10,000);//解析数字

 //国际化百分比
 nf=NumberFormat.getPercentInstace();

 //国际化日期
 int dateStyle = DateFormat.FULL;//full,long,medium,short
 int timeStyle = DateFormat.FULL;//full,long,medium,short
 DateFormat df = DateFormat.getDateTimeInstance(dateStyle,timeStyle,locale);
 String date = df.format(new Date());

2.1.3 jsp页面国际化

引入jstl国际化与格式化标签库

<%@taglib uri ="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

<fmt:setLocale value="${pageContext.request.locale}"/> //设置本地化对象
<fmt:setBundle basename="包名.基础名" var="bundle"/>//设置工具类
<fmt:message><fmt:message>//输出国际化的文本

//使用
<fmt:message key = 'hello' bundle="${bundle}"><fmt:message>

格式化标签

//格式化金额
//0.00保留两位小数自动补零   #.##不自动补零
<fmt:formatNumber pattern = "0.00" value="100"></fmt:formatNumber>
//格式化日期
<%
   request.setAttribute("date",new Date());
%>
<fmt:formatNumber pattern = "yyyy-MM-dd" value="${date}"></fmt:formatNumber>

猜你喜欢

转载自blog.csdn.net/smile_po/article/details/78553724