11、Filter(重点)
Filter:过滤器,用来过滤网站的数据;
- 处理中文乱码
- 登陆验证...
Filter开发步骤:
导包
编写过滤器
导包不要错
实现Filter接口,重写对应的方法即可
public class CharacterEncodingFilter implements Filter { //初始化:web服务器启动,就已经初始化了,随时等待过滤对象出现! public void init(FilterConfig filterConfig) throws ServletException { System.out.println("CharacterEncodingFilter初始化"); } //Chain : 链 /* 1. 过滤器中的所有代码,在过滤特定请求的时候都会执行 2. 必须要让过滤器继续通行 filterChain.doFilter(servletRequest,servletResponse); */ public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); servletResponse.setContentType("text/html;charset=UTF-8"); System.out.println("CharacterEncodingFilter执行前..."); filterChain.doFilter(servletRequest,servletResponse); //让我们的请求继续走,如果不写,程序到这里就被拦截停止! System.out.println("CharacterEncodingFilter执行后..."); } //销毁:web服务器关闭的时候,过滤器会销毁 public void destroy() { System.out.println("CharacterEncodingFilter销毁"); } }
在web.xml中配置 Filter
<servlet> <servlet-name>ShowServlet</servlet-name> <servlet-class>com.kuang.servlet.ShowServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ShowServlet</servlet-name> <url-pattern>/servlet/show</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ShowServlet</servlet-name> <url-pattern>/show</url-pattern> </servlet-mapping> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <!--只要是 /servlet的任何请求,都会经过这个过滤器--> <url-pattern>/servlet/*</url-pattern> <!--<url-pattern>/*</url-pattern>--> </filter-mapping>
12、监听器
实现一个监听器的接口; (有N中)
编写一个监听器
实现监听器的接口...
//统计网站在线人数 : 统计session public class OnlineCountListener implements HttpSessionListener { //创建session监听:看你的一举一动 //一旦创建一个session就会触发一次这个事件! public void sessionCreated(HttpSessionEvent httpSessionEvent) { ServletContext context = httpSessionEvent.getSession().getServletContext(); System.out.println(httpSessionEvent.getSession().getId()); Integer onlineCount = (Integer) context.getAttribute("OnlineCount"); if (onlineCount==null){ onlineCount = new Integer(1); }else { int count = onlineCount.intValue(); onlineCount = new Integer(count+1); } context.setAttribute("OnlineCount",onlineCount); } //销毁session监听 //一旦销毁session就会触发一次这个事件! public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { ServletContext context = httpSessionEvent.getSession().getServletContext(); Integer onlineCount = (Integer) context.getAttribute("OnlineCount"); if (onlineCount==null){ onlineCount = new Integer(0); }else { int count = onlineCount.intValue(); onlineCount = new Integer(count-1); } context.setAttribute("OnlineCount",onlineCount); } /* Session销毁: 1. 手动销毁 getSession.invalidate() 2. 自动销毁 在web.xml中设置session过期时间 */ }
web.xml中注册监听器
<!--注册监听器--> <listener> <listener-class>com.kuang.listener.OnlineCountListener</listener-class> </listener>
看情况是否使用!
13、过滤器、监听器常见应用
监听器:GUI编程中经常使用;
public class TestPanel1 {
public static void main(String[] args) {
Frame frame = new Frame("中秋节快乐"); //新建一个窗体
Panel panel = new Panel(null); //面板
frame.setLayout(null); //设置窗体的布局
frame.setBounds(50,50,300,300);
frame.setBackground(Color.blue); //设置背景颜色
panel.setBounds(70,70,70,70); //设置背景颜色
panel.setBackground(Color.GREEN);
frame.add(panel);
frame.setVisible(true);
//监听事件,监听关闭事件,使用适配器
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
实现:用户登录之后才能进入主页!用户注销后就不能进入主页了!
用户登陆之后,向Session中放入用户的数据
进入主页的时候要判断用户是否已经登录;要求:在过滤器中实现!
//ServletRequest HttpServletRequest HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; if (httpServletRequest.getSession().getAttribute(Constant.USER_SESSION)==null){ httpServletResponse.sendRedirect("/error.jsp"); } filterChain.doFilter(servletRequest, servletResponse);
项目全部代码:
public class Constant {
public final static String USER_SESSION = "USER_SESSION";
}
=============================================================
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取前端请求的参数
String username = req.getParameter("username");
if (username.equals("admin")){ //登陆成功
req.getSession().setAttribute(Constant.USER_SESSION,req.getSession().getId());
resp.sendRedirect("/sys/success.jsp");
}else { //登录失败
resp.sendRedirect("/error.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
==========================================================================
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object user_session = req.getSession().getAttribute(Constant.USER_SESSION);
if (user_session!=null){
req.getSession().removeAttribute(Constant.USER_SESSION);
resp.sendRedirect("/Login.jsp");
}else {
resp.sendRedirect("/Login.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
===============================================================================
public class SysFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
/*
实现会员分级:
if (req.getSession().setAttribute(Constant.USER_SESSION).level==VIP1){
response.sendRedirect("/vip1/index.jsp");
}
if (req.getSession().setAttribute(Constant.USER_SESSION).level==VIP2){
response.sendRedirect("/vip2/index.jsp");
}
if (req.getSession().setAttribute(Constant.USER_SESSION).level==VIP3){
response.sendRedirect("/vip3/index.jsp");
}
*/
//ServletRequest HttpServletRequest
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
if (httpServletRequest.getSession().getAttribute(Constant.USER_SESSION)==null){
httpServletResponse.sendRedirect("/error.jsp");
}
filterChain.doFilter(servletRequest, servletResponse);
}
public void destroy() {
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>错误</h1>
<h3>没有权限,用户名错误</h3>
<p><a href="/Login.jsp">返回登录页面</a></p>
</body>
</html>
====================================================================
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>主页</h1>
<p><a href="/servlet/logout">注销</a></p>
</body>
</html>
=======================================================================
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>登录</h1>
<form action="/servlet/login" method="post">
用户名:<input type="text" name="username"><br>
<input type="submit">
</form>
</body>
</html>
========================================================================
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.kuang.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/servlet/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.kuang.servlet.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/servlet/logout</url-pattern>
</servlet-mapping>
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.kuang.servlet.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/sys/*</url-pattern>
</filter-mapping>
</web-app>