【零基础上手JavaWeb】19 Servlet监听器和国际化详解

写在前面,大家好!我是【跨考菌】,一枚跨界的程序猿,专注于后台技术的输出,目标成为全栈攻城狮!这博客是对我跨界过程的总结和思考。如果你也对Java后端技术感兴趣,抑或是正在纠结于跨界,都可以关注我的动态,让我们一起学习,一起进步~
我的博客地址为:【跨考菌】的博客


上篇【零基础上手JavaWeb】18 基于MVC的客户关系管理系统案例 介绍了一个基于Servlet的MVC架构客户关系管理系统案例,借此熟悉Spring框架底层的原理。本文介绍Servlet监听器和国际化的相关内容。和【跨考菌】一起加油吧~

在这里插入图片描述

如果你有收获,记得帮博主一键三连哦😊


1 JavaWeb监听器

1.1 浅析

JavaWeb的三大组件:
 Servlet
 Listener
 Filter

监听器:
 它是一个接口,内容由我们来实现;
 它需要注册,例如注册在按钮上!
 监听器中的方法,会在特殊事件发生时被调用!

观察者:

  • 事件源;
     小偷
  • 事件;
     偷东西
  • 监听器;
     警察
     监听器中的方法:抓捕

说明:相当于将“抓捕”的操作注册到小偷身上,一旦小偷开始了“偷东西”事件,就会触发“抓捕”操作。

JavaWeb中的监听器

1)事件源:三大域!

  • ServletContext
    生命周期监听:ServletContextListener,它有两个方法,一个在出生时调用,一个在死亡时调用;
     void contextInitialized(ServletContextEvent sce):创建SErvletcontext时
     void contextDestroyed(ServletContextEvent sce):销毁Servletcontext时
    属性监听:ServletContextAttributeListener,它有三个方法,一个在添加属性时调用,一个在替换属性时调用,最后一个是在移除属性时调用。
     void attributeAdded(ServletContextAttributeEvent event):添加属性时;
     void attributeReplaced(ServletContextAttributeEvent event):替换属性时;
     void attributeRemoved(ServletContextAttributeEvent event):移除属性时;
  • HttpSession
    生命周期监听:HttpSessionListener,它有两个方法,一个在出生时调用,一个在死亡时调用;
     void sessionCreated(HttpSessionEvent se):创建session时
     void sessionDestroyed(HttpSessionEvent se):销毁session时
    属性监听:HttpSessioniAttributeListener,它有三个方法,一个在添加属性时调用,一个在替换属性时调用,最后一个是在移除属性时调用。
     void attributeAdded(HttpSessionBindingEvent event):添加属性时;
     void attributeReplaced(HttpSessionBindingEvent event):替换属性时
     void attributeRemoved(HttpSessionBindingEvent event):移除属性时
  • ServletRequest
    生命周期监听:ServletRequestListener,它有两个方法,一个在出生时调用,一个在死亡时调用;
     void requestInitialized(ServletRequestEvent sre):创建request时
     void requestDestroyed(ServletRequestEvent sre):销毁request时
    属性监听:ServletRequestAttributeListener,它有三个方法,一个在添加属性时调用,一个在替换属性时调用,最后一个是在移除属性时调用。
     void attributeAdded(ServletRequestAttributeEvent srae):添加属性时
     void attributeReplaced(ServletRequestAttributeEvent srae):替换属性时
     void attributeRemoved(ServletRequestAttributeEvent srae):移除属性时

2)javaWeb中完成编写监听器:

 写一个监听器类:要求必须去实现某个监听器接口;
 注册,是在web.xml中配置来完成注册!

3)事件对象:

  • ServletContextEvent:ServletContext getServletContext()
  • HttpSessionEvent:HttpSession getSession()
  • ServletRequest:
     ServletContext getServletContext();
     ServletReques getServletRequest();
  • ServletContextAttributeEvent:
     ServletContext getServletContext();
     String getName():获取属性名
     Object getValue():获取属性值
  • HttpSessionBindingEvent:略
  • ServletRequestAttributeEvent :略

感知监听(都与HttpSession相关:HttpSessionBindingListener)
 它用来添加到JavaBean上,而不是添加到三大域上!
 这两个监听器都不需要在web.xml中注册!

HttpSessionBindingListener:添加到javabean上,javabean就知道自己是否添加到session中了。

1.2 JavaWeb监听器概述

在JavaWeb被监听的事件源为:ServletContext、HttpSession、ServletRequest,即三大域对象。
 监听域对象“创建”与“销毁”的监听器;
 监听域对象“操作域属性”的监听器;
 监听HttpSession的监听器。

1.3 创建与销毁监听器

创建与销毁监听器一共有三个:

  • ServletContextListener:Tomcat启动和关闭时调用下面两个方法
     public void contextInitialized(ServletContextEvent evt):ServletContext对象被创建后调用;
     public void contextDestroyed(ServletContextEvent evt):ServletContext对象被销毁前调用;
  • HttpSessionListener:开始会话和结束会话时调用下面两个方法
     public void sessionCreated(HttpSessionEvent evt):HttpSession对象被创建后调用;
     public void sessionDestroyed(HttpSessionEvent evt):HttpSession对象被销毁前调用;
  • ServletRequestListener:开始请求和结束请求时调用下面两个方法
     public void requestInitiallized(ServletRequestEvent evt):ServletRequest对象被创建后调用;
     public void requestDestroyed(ServletRequestEvent evt):ServletRequest对象被销毁前调用。

案例:

package cn.itcast.web.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * ServletContext生死监听:servlet启动时就创建。
 * @author cxf
 *  
 * 可以在这个监听器存放一些在tomcat启动时就要完成的代码!
 */
public class AListener implements ServletContextListener {
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("哇,我来也!");
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("哇,我要挂也!");
	}
}

web.xml:
注册监听器。

<listener>
    <listener-class>cn.itcast.web.listener.AListener</listener-class>
  </listener>

tomcat在启动或者停止时,会输出对应的内容到控制台。

1.4 操作域属性的监听器

当对域属性进行增、删、改时,执行的监听器一共有三个:

  • ServletContextAttributeListener:在ServletContext域进行增、删、改属性时调用下面方法。
     public void attributeAdded(ServletContextAttributeEvent evt)
     public void attributeRemoved(ServletContextAttributeEvent evt)
     public void attributeReplaced(ServletContextAttributeEvent evt)
  • HttpSessionAttributeListener:在HttpSession域进行增、删、改属性时调用下面方法
     public void attributeAdded(HttpSessionBindingEvent evt)
     public void attributeRemoved (HttpSessionBindingEvent evt)
     public void attributeReplaced (HttpSessionBindingEvent evt)
  • ServletRequestAttributeListener:在ServletRequest域进行增、删、改属性时调用下面方法
     public void attributeAdded(ServletRequestAttributeEvent evt)
     public void attributeRemoved (ServletRequestAttributeEvent evt)
     public void attributeReplaced (ServletRequestAttributeEvent evt)

下面对这三个监听器的事件对象功能进行介绍:

  • ServletContextAttributeEvent
     String getName():获取当前操作的属性名;
     Object getValue():获取当前操作的属性值;
     ServletContext getServletContext():获取ServletContext对象。
  • HttpSessionBindingEvent
     String getName():获取当前操作的属性名;
     Object getValue():获取当前操作的属性值;
     HttpSession getSession():获取当前操作的session对象。
  • ServletRequestAttributeEvent
     String getName():获取当前操作的属性名;
     Object getValue():获取当前操作的属性值;
     ServletContext getServletContext():获取ServletContext对象;
     ServletRequest getServletRequest():获取当前操作的ServletRequest对象。

案例:

public class MyListener implements ServletContextAttributeListener,
		ServletRequestAttributeListener, HttpSessionAttributeListener {
	public void attributeAdded(HttpSessionBindingEvent evt) {
		System.out.println("向session中添加属性:" + evt.getName() + "=" + evt.getValue());
	}

	public void attributeRemoved(HttpSessionBindingEvent evt) {
		System.out.println("从session中移除属性:" + evt.getName() + "=" + evt.getValue());
	}

	public void attributeReplaced(HttpSessionBindingEvent evt) {
		System.out.println("修改session中的属性:" + evt.getName() + "=" + evt.getValue());
	}

	public void attributeAdded(ServletRequestAttributeEvent evt) {
		System.out.println("向request中添加属性:" + evt.getName() + "=" + evt.getValue());
	}

	public void attributeRemoved(ServletRequestAttributeEvent evt) {
		System.out.println("从request中移除属性:" + evt.getName() + "=" + evt.getValue());
	}

	public void attributeReplaced(ServletRequestAttributeEvent evt) {
		System.out.println("修改request中的属性:" + evt.getName() + "=" + evt.getValue());
	}

	public void attributeAdded(ServletContextAttributeEvent evt) {
		System.out.println("向context中添加属性:" + evt.getName() + "=" + evt.getValue());
	}

	public void attributeRemoved(ServletContextAttributeEvent evt) {
		System.out.println("从context中移除属性:" + evt.getName() + "=" + evt.getValue());
	}

	public void attributeReplaced(ServletContextAttributeEvent evt) {
		System.out.println("修改context中的属性:" + evt.getName() + "=" + evt.getValue());
	}
}
public class ListenerServlet extends BaseServlet {
	public String contextOperation(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ServletContext context = this.getServletContext();
		context.setAttribute("a", "a");
		context.setAttribute("a", "A");
		context.removeAttribute("a");
		return "/index.jsp";
	}
	
	///
	
	public String sessionOperation(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		session.setAttribute("a", "a");
		session.setAttribute("a", "A");
		session.removeAttribute("a");
		return "/index.jsp";
	}

	///
	
	public String requestOperation(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setAttribute("a", "a");
		request.setAttribute("a", "A");
		request.removeAttribute("a");
		return "/index.jsp";
	}
}
  <body>
    <a href="<c:url value='/ListenerServlet?method=contextOperation'/>">SevletContext操作属性</a>
    <br/>
	<a href="<c:url value='/ListenerServlet?method=sessionOperation'/>">HttpSession操作属性</a>
    <br/>
    <a href="<c:url value='/ListenerServlet?method=requestOperation'/>">ServletRequest操作属性</a> | 
  </body>

1.5 感知监听器HttpSessionBindingListener

特点:

 它用来添加到JavaBean上;
 不是添加到三大域上!
 这两个监听器都不需要在web.xml中注册!

HttpSessionBindingListener:添加到javabean上,javabean就知道自己是否添加到session中了。

案例:
User.java:

package cn.itcast.web.listener;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

public class User implements HttpSessionBindingListener {
	private String username;
	private String password;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(String username, String password) {
		super();
		this.username = username;
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + "]";
	}
	@Override
	public void valueBound(HttpSessionBindingEvent event) {
		System.out.println("啊~,session添加了我!");
	}
	@Override
	public void valueUnbound(HttpSessionBindingEvent event) {
		System.out.println("哇哇哇~,无情的session抛弃了我!");
	}
}

这样User一旦被放到或者移除session上面的两个方法就会自动调用了。

2 国际化

2.1 什么是国际化

国际化就是可以把页面中的中文变成英文。例如在页面中的登录表单:
在这里插入图片描述

2.2 理解国际化

想把页面中的文字修改,那么就不能再使用硬编码,例如下面的页面中都是硬编码:

在这里插入图片描述
上图中的中文想转换成英文,那么就需要把它们都变成活编码:
在这里插入图片描述

2.3 Locale类

创建Locale类对象:
 new Locale(“zh”, “CN”);
 new Locale(“en”, “US”);
你一定对zh、CN或是en、US并不陌生,zh、en表示语言,而CN、US表示国家。一个Locale对象表示的就是语言和国家。

2.4 ResourceBundle类

ReourceBundle类用来获取配置文件中的内容。
下面是两个配置文件内容:
res_zh_CN.properties
在这里插入图片描述
res_en_US.properties
在这里插入图片描述

public class Demo1 {
	@Test
	public void fun1() {
		ResourceBundle rb = ResourceBundle.getBundle("res", new Locale("zh", "CN" ));
		String username = rb.getString("msg.username");
		String password = rb.getString("msg.password");
		System.out.println(username);
		System.out.println(password);		
	}
	
	@Test
	public void fun2() {
		ResourceBundle rb = ResourceBundle.getBundle("res", new Locale("en", "US" ));
		String username = rb.getString("msg.username");
		String password = rb.getString("msg.password");
		System.out.println(username);
		System.out.println(password);		
	}
}

ResourceBundle的getBundle()方法需要两个参数:
 第一个参数:配置文件的基本名称
 第二个参数:Locale
getBundle()方法会通过两个参数来锁定配置文件!

2.5 页面国际化

从请求头中拿到浏览器默认的国际化语言,显示对应内容。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'login.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
<%-- 
把与语言相关的所有字符串都写成变量!!!
 --%>
 <%
 /*
 1. 获取Locale,这是由客户端的浏览器提供的Locale
 2. 创建ResourceBundle
 3. 把所有的语言信息使用rb.getString("xxx")来替换!
 */
 Locale locale = request.getLocale();
 ResourceBundle rb = ResourceBundle.getBundle("res", locale);
 %>
<h1><%=rb.getString("login") %></h1>
<form action="" method="post">
<%=rb.getString("username") %>:<input type="text" name="username"/><br/>
<%=rb.getString("password") %>:<input type="password" name="password"/><br/>
<input type="submit" value="<%=rb.getString("login") %>"/>
</form>
  </body>
</html>

中文环境:
在这里插入图片描述
在这里插入图片描述
英文环境:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值