JavaWeb-Filter和Listener
MVC
- M model 模型
- V view 视图
- C controller 控制器
Filter
Filter也称之为过滤器,它是Servlet技术中最实用的技术,Web开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或静态 html 文件等进行拦截,从而实现一些特殊的功能。
FilterDemo.java
package com.th0r.filter;
import javax.servlet.*;
import java.io.IOException;
public class FilterDemo implements Filter {
//在容器开始时就会执行
@Override
public void init(FilterConfig filterConfig) {
System.out.println("init");
}
@Override
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("执行后");
}
@Override
public void destroy() {
System.out.println("destroy");
}
}
web.xml
<filter>
<filter-name>filter</filter-name>
<filter-class>com.th0r.filter.FilterDemo</filter-class>
</filter>
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>/demo</url-pattern>
</filter-mapping>
Listener
监听器用于监听Web应用中某些对象的创建、销毁、增加,修改,删除等动作的发生,然后作出相应的响应处理。当监听范围的对象的状态发生变化的时候,服务器自动调用监听器对象中的方法。常用于统计网站在线人数、系统加载时进行信息初始化、统计网站的访问量等等。
ListenerDemo.java
package com.th0r.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class ListenerDemo implements HttpSessionListener {
//Session一旦创建就会触发
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
ServletContext ctx = httpSessionEvent.getSession().getServletContext();
Integer onlineCount = (Integer) ctx.getAttribute("onlineCount");
if (onlineCount == null){
onlineCount = new Integer(1);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count+1);
}
ctx.setAttribute("onlineCount", onlineCount);
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
ServletContext ctx = httpSessionEvent.getSession().getServletContext();
Integer onlineCount = (Integer) ctx.getAttribute("onlineCount");
if (onlineCount == null){
onlineCount = new Integer(0);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count-1);
}
ctx.setAttribute("onlineCount", onlineCount);
}
}
web.xml
<listener>
<listener-class>com.th0r.listener.ListenerDemo</listener-class>
</listener>
GUI
监听器在GUI编程中经常使用
package com.th0r.listener;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class GuiDemo {
public static void main(String[] args) {
Frame frame = new Frame("Hello!"); //新建一个窗体
Panel panel = new Panel(null); //面板
frame.setLayout(null); //窗体布局
frame.setBounds(200, 200, 200, 200);
frame.setBackground(Color.blue);
panel.setBounds(50, 50, 100 ,100);
panel.setBackground(Color.gray);
frame.add(panel);
frame.setVisible(true);
//监听事件
frame.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
System.out.println("打开");
}
@Override
public void windowClosing(WindowEvent e) {
System.out.println("关闭中");
System.exit(0);
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("关闭");
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
System.out.println("激活");
}
@Override
public void windowDeactivated(WindowEvent e) {
System.out.println("未激活");
}
});
}
}
登录验证
sys目录内的内容只有admin能够访问
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login</title>
</head>
<body>
输入你的账号
<form action="/servlet/login" method="post">
<input type="text" name="username">
<input type="submit" value="提交">
</form>
</body>
</html>
LoginServlet
package com.th0r.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
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("USER_SESSION", req.getSession().getId());
resp.sendRedirect("/sys/home.jsp");
} else {
resp.sendRedirect("/error.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
sys/home.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>登录成功</h1>
<a href="/servlet/logout" >注销</a>
</body>
</html>
SysFilter.java
package com.th0r.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SysFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
if (req.getSession().getAttribute("USER_SESSION") == null){
resp.sendRedirect("/error.jsp");
}
filterChain.doFilter(req,resp);
}
@Override
public void destroy() {
}
}
home.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>登录成功</h1>
<a href="/servlet/logout" >注销</a>
</body>
</html>
LogoutServlet.java
package com.th0r.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object user_session = req.getSession().getAttribute("USER_SESSION");
if (user_session != null){
req.getSession().removeAttribute("USER_SESSION");
resp.sendRedirect("/login.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
web.xml
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.th0r.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.th0r.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.th0r.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/sys/*</url-pattern>
</filter-mapping>