1.过滤器
过滤器(Filter)用来过滤网站的数据,如处理中文乱码,登录验证等。
(1)使用过滤器处理中文乱码
1.Servlet代码
public class CharacterEncodingFilter implements Filter {
//初始化
public void init(FilterConfig filterConfig) throws ServletException {
}
//
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
System.out.println("过滤器执行前:");
chain.doFilter(request, response);
System.out.println("过滤器执行后:");
}
//销毁
public void destroy() {
System.out.println("过滤器销毁");
}
}
2.配置XML文件
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
这样配置可以将servlet路径后的网页乱码过滤
使用showServlet页面进行测试,Servlet代码如下:
public class ShowServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("Hello world!乱码测试");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
配置XML文件,给showServlet页面配置两个路径,一个包含servlet,一个不包含
<servlet>
<servlet-name>showServlet</servlet-name>
<servlet-class>servlet.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>showServlet</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>showServlet</servlet-name>
<url-pattern>/servlet/s1</url-pattern>
</servlet-mapping>
访问http://localhost:8080/s1
访问http://localhost:8080/servlet/s1
2.监听器
帮助开发者监听web中的特定事件
(1)使用监听器统计网页在线人数
1.Servlet
//统计网站在线人数
public class OnlineCountListener implements HttpSessionListener {
//创建Session监听:
//一旦创建session就会触发该事件
public void sessionCreated(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if (onlineCount == null) {
onlineCount = new Integer(1);
} else {
int count = onlineCount.intValue();
onlineCount = new Integer(count++);
}
ctx.setAttribute("OnlineCount", onlineCount);
}
//销毁Session
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
}
}
2.配置XML文件
<listener>
<listener-class>listener.OnlineCountListener</listener-class>
</listener>
3.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>session</title>
</head>
<body>
<h1>
当前有:
<span>
<%=this.getServletConfig().getServletContext().getAttribute("OnlineCount")%>
</span>
人在线
</h1>
</body>
</html>
访问http://localhost:8080