代码实现
@WebFilter(filterName = "SensitiveWordsFilter",urlPatterns = "/*") public class SensitiveWordsFilter implements Filter { List<String > sensitiveWords = new ArrayList<>(); public void init(FilterConfig config) throws ServletException { Enumeration<String> parameterNames = config.getInitParameterNames(); while (parameterNames.hasMoreElements()){ String sensitiveWord = config.getInitParameter(parameterNames.nextElement()); sensitiveWords.add(sensitiveWord); } } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; //增强request下的getParameter方法 HttpServletRequest requestProxy = (HttpServletRequest) Proxy.newProxyInstance( request.getClass().getClassLoader(), request.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //增强getParameter方法 Object returnValue = null; String methodName = method.getName(); if("getParameter".equals(methodName)){ //returnValue就是getParameter方法的返回值,可能存在敏感词 String returnValue1 = (String) method.invoke(request,args); //开始处理敏感词 for (String sensitiveWord:sensitiveWords){ if (returnValue1.contains(sensitiveWord)){ //getParameteer方法的返回值包含敏感词 returnValue1 =returnValue1.replace(sensitiveWord,"***"); } } return returnValue1; }else { returnValue = method.invoke(request,args); } return returnValue; } } ); chain.doFilter(requestProxy, resp); }(断点应用:打关键代码,可用于检查修正错误代码)
(课堂案例) 1,监听器概念
事件源:事件发生的源头监听器:监听事件发生绑定:将监听器绑定到事件源事件:能够触发监听器的事2,Servlet监听器
事件源:request域对象,session域对象,ServletContext域对象监听器:Servlet三种监听器绑定:配置web.xml事件:域对象发生改变1,一类监听器:
ServletRequestListener:监听ServletRequest域对象的创建和销毁HttpSessionListener:监听HttpSesssionListener域对象的创建和销毁ServletContextListener:监听ServiceContextListener域对象的创建和销毁2,开发步骤:
自定义类实现一类监听器重写监听器中的方法配置web.xml3,代码实现 监听器:
public class MyListener02 implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent httpSessionEvent) { System.out.println("session创建"); } @Override public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { System.out.println("session销毁"); } }web.xml
<listener> <listener-class>listener.MyListener01</listener-class> </listener> 事件源:ServletContext域对象监听器:ServletContextListener绑定:web.xml配置事件:ServletContext域对象发生的创建和销毁1,分类:
ServletRequestAttributeListener 监听ServletRequest域对象中的属性变更HttpSessionAttributeListener 监听HttpSession域对象中的属性变更ServletContextAttributeListener 监听ServletContext域对象中的属性变更2, 代码实现
监听器:
public class MyServletContextAttributeListener implements ServletContextAttributeListener { @Override public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) { //监听ServletContext域对象中的属性添加 System.out.println("ServletContext added"); } @Override public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) { //监听ServletContext域对象中的属性值被替换 System.out.println("ServletContext removed"); } @Override public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) { //监听ServletContext域对象中的属性值移除 System.out.println("ServletContext replaced"); } }web.xml:
<listener> <listener-class>listener.MyServletContextAttributeListener</listener-class> </listener>HttpSessionBindingListener 监听session 域中的java对象的状态(绑定与解绑) 绑定:将java对象存储到session域对象 解绑:将java对象从session域对象移除
监听器组成 事件源:java对象 监听器:HttpSessionBindingListener 绑定:java对象实现HttpSessionBindingListener接口 事件:java对象在session中状态改变
代码实现
public class User implements HttpSessionBindingListener { @Override public void valueBound(HttpSessionBindingEvent httpSessionBindingEvent) { System.out.println("UserBound"); } @Override public void valueUnbound(HttpSessionBindingEvent httpSessionBindingEvent) { System.out.println("UserUnound"); } ...... 注意事项: 不需要在web,xml进行绑定,因为已经通过实现接口实现绑定
代码实现: LoginServlet
@WebServlet(name = "LoginServlet",urlPatterns = "/login") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); if("root".equals(username) && "root".equals(password)){ //登录成功,修改登录状态,跳转ShowIndexServlet User existUser = new User(); existUser.setUsername(username); existUser.setPassword(password); request.getSession().setAttribute("existUser",existUser); response.sendRedirect("/day59/showIndex"); }else { //登陆失败,转发到登录页面,重新登陆 request.getRequestDispatcher("login.html").forward(request,response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }ShowIndexServlet
@WebServlet(name = "ShowIndexServlet",urlPatterns = "/showIndex") public class ShowIndexServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User existUser = (User)request.getSession().getAttribute("existUser"); StringBuffer responseBody = new StringBuffer(); if(null == existUser){ //不在登录状态,提示 responseBody.append("您还没有登陆:<a href='/day59/login.html'>请登录</a>"); }else { //在登陆状态 responseBody.append("欢迎回来,"+existUser.getUsername()+" <a href='/day59/logout'>注销</a>"); } ServletContext servletContext = getServletContext(); //获取在线人数 Integer count = (Integer) servletContext.getAttribute("count"); if (null == count){ //没有人在登陆状态,在线人数为0人 count = 0; }else{ //有人在登陆状态,直接输出在线人数count人 } responseBody.append("在线人数为:"+count); response.setContentType("text/html;charset=utf-8"); response.getWriter().write(responseBody.toString()); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }LogoutSevlet
@WebServlet(name = "LogoutServlet",urlPatterns = "logout") public class LogoutServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //注销登录,将existUser从session域中基础 // request.getSession().removeAttribute("existUser"); //注销登录 //注销成功,也可以直接将session销毁 request.getSession().invalidate(); request.getRequestDispatcher("showIndex").forward(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }User
public class User implements HttpSessionBindingListener { @Override public void valueBound(HttpSessionBindingEvent httpSessionBindingEvent) { //有人登录成功,在线人数加1 //判断是否是第一个登录成功的人 //获取ServletContext ServletContext servletContext = httpSessionBindingEvent.getSession().getServletContext(); Integer count = (Integer) servletContext.getAttribute("count"); if(null == count){ //就是第一个登录成功的人 count = 1; }else { //不是第一个登录成功的人 count++; } servletContext.setAttribute("count",count); } @Override public void valueUnbound(HttpSessionBindingEvent httpSessionBindingEvent) { //有人注销登录,在线人数减1 System.out.println("UserUnound"); ServletContext servletContext = httpSessionBindingEvent.getSession().getServletContext(); Integer count = (Integer) servletContext.getAttribute("count"); count--; servletContext.setAttribute("count",count); }login.html
<head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <form action="/day59_02/login" method="get"> 账户:<input type="text" name="username"/><br> 密码:<input type="text" name="password"/><br> <button type="submit">登录</button> </form> </body> </html>