JavaWeb三大组件
1、都需要在web.xml中进行配置
Servlet
Listener(2个感知监听器不需要配置)
Filter
2.过滤器
它会在一组资源(jsp、servlet、.css、.html)的前面执行!
它可以让请求得到目标资源,也可以不让请求达到!
* 过滤器有拦截请求的能力!
登录:
允许访问AServlet、BServlet、CServlet
----------------------
过滤器如何编写
1、写一个类实现Filter接口
2、在web.xml中进行配置
Filter
void init(FilterConfig)
*创建之后,马上执行;Filter会在服务器启动时就创建
void destory()
*销毁之前执行!在服务器关闭时销毁
void doFilter(ServletRequest,ServletResponse,FilterChain)
*每次过滤时都会执行
Filter是单例的!
web.xml
<filter>
<filter-name>xxx</filter-name>
<filter-calss>cn.itcast.web.filter.AFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>xxx</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
指定servlet-name:点名过滤,可以过滤多个
---------------------------
FilterConfig-->与ServletConfig相似
*获取初始化参数:getInitParameter()
*获取过滤器名称:getFilterName()
*获取application:getServletContext()
FilterChain
*doFilter(ServletRequest,ServletResponse):放行!
放行就相当于调用了目标servlet的service方法,执行完了还要执行我们后面的方法
---------------------------
---------------------------
多过滤器
FilterChain#doFilter()方法:
执行目标资源或者执行下一个过滤器!如果没有下一个过滤器那么就执行目标资源,如果有那么执行下一个过滤器!
---------------------------
过滤器的四种拦截方式
*请求 DISPATCHER
*转发 FORWAED
*包含 INCLUDE
*错误 ERROR
在filter-mapping中配置
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
ERROR是拦截什么呢?就是web.xml中配置了错误页面然后自动进入了错误的页面的请求
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
------------------------
多个过滤器的执行顺序
说是在<filter-mapping>的配置顺序决定了过滤器的执行顺序
------------------------
过滤器的应用场景:
*执行目标资源之前做预处理工作,例如设置编码,这种通常都会放行,只是在目标资源执行之前做一些准备操作
*通过条件判断是否放行,例如教研当前用户是否已经登录,或者用户IP是否已经被禁用
*在目标资源执行之后,做一些后续的特殊处理工作,例如把目标资源输出的数据进行处理
几个例子:
1、分ip统计访问次数:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'a.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> <h1>去</h1> </body> </html> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'b.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> <h1>好</h1> </body> </html> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'show.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> <h1 align="center">显示结果</h1> <table align="center" width="60%"> <tr> <th>IP</th> <th>次数</th> </tr> <c:forEach items="${applicationScope.amp }" var="entry"> <td>${entry.key }</td> <td>${entry.value }</td> </c:forEach> </table> </body> </html> package cn.itcast.web.filter; import java.io.IOException; import java.util.Map; import java.util.Set; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import sun.reflect.ReflectionFactory.GetReflectionFactoryAction; /** * 从application中获取Map * 从request中得到当前客户端的ip * 进行统计工作,结果保存到map * @author Administrator * */ public class AFilter implements Filter{ private FilterConfig fconfig; public void destroy() { } @SuppressWarnings("unchecked") public void doFilter(ServletRequest request, ServletResponse response , FilterChain chain) throws IOException, ServletException { /* * 1、得到application中的map * 2、从request中获取当前客户端ip地址 * 3、查看map中是否存在这个ip对应的访问次数,如果存在,把次数+1再保存回去 * 4、如果不存在这个ip,那么说明是第一个访问本站,设置访问次数为1 */ ServletContext application=fconfig.getServletContext(); Map<String,Integer> map=(Map<String, Integer>) application.getAttribute("amp"); String ip=request.getRemoteAddr(); if(map.containsKey(ip)){ int cnt=map.get(ip); map.put(ip, cnt+1); }else{ map.put(ip, 1); } application.setAttribute("amp", map); chain.doFilter(request, response); } public void init(FilterConfig fconfig) throws ServletException { this.fconfig=fconfig; } } package cn.itcast.web.listener; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class AListener implements ServletContextListener{ public void contextDestroyed(ServletContextEvent sce) { } /** * 在服务器启动时创建Map,保存到ServletContext */ public void contextInitialized(ServletContextEvent sce) { Map<String,Integer> map=new LinkedHashMap<String, Integer>(); ServletContext application=sce.getServletContext(); application.setAttribute("amp", map); } } <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>AFilter</filter-name> <filter-class>cn.itcast.web.filter.AFilter</filter-class> </filter> <filter-mapping> <filter-name>AFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>cn.itcast.web.listener.AListener</listener-class> </listener> </web-app>
2、粗粒度权限管理(游客,管理员,会员的权限)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'a.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> <h1>欢迎欢迎,管理员先生登录</h1> <a href="<c:url value='/index.jsp'/>">游客入口</a><br/> <a href="<c:url value='/user/u.jsp'/>">会员入口</a><br/> <a href="<c:url value='/admin/a.jsp'/>">管理员入口</a><br/> </body> </html> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'a.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> <h1>会员先生,您早上好</h1> <a href="<c:url value='/index.jsp'/>">游客入口</a><br/> <a href="<c:url value='/user/u.jsp'/>">会员入口</a><br/> <a href="<c:url value='/admin/a.jsp'/>">管理员入口</a><br/> </body> </html> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.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> <h1>你就是个游客而已</h1> <a href="<c:url value='/index.jsp'/>">游客入口</a><br/> <a href="<c:url value='/user/u.jsp'/>">会员入口</a><br/> <a href="<c:url value='/admin/a.jsp'/>">管理员入口</a><br/> </body> </html> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <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> <h1>登录</h1> <div>${msg }</div> <form action="<c:url value='LoginServlet'/>" method="post"> 用户名:<input type="text" name="username"/> <input type="submit"/> </form> </body> </html> package cn.itcast.web.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); /* * 1、获取用户名 * 2、判断用户名中是否包含itcast * 3、如果包含就是管理员 * 4、如果不包含,就是普通会员 * 5、要把登录的用户名保存到session中 * 6、转发到index.jsp */ String username=req.getParameter("username"); if(username.contains("itcast")){ req.getSession().setAttribute("admin", username); }else{ req.getSession().setAttribute("username", username); } req.getRequestDispatcher("/index.jsp").forward(req, resp); } } package cn.itcast.web.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class AdminFilter implements Filter{ public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { /* * 得到session, * 判断session域中是否存在admin,如果存在放行 * ,否则,大会login.jsp,并告诉它不要瞎溜达 */ HttpServletRequest req=(HttpServletRequest) request; String name=(String) req.getSession().getAttribute("admin"); if(name!=null){ chain.doFilter(request, response); }else{ req.setAttribute("msg", "您可能是个啥,但不是管理员!"); req.getRequestDispatcher("/login.jsp").forward(request, response); } } public void init(FilterConfig filterConfig) throws ServletException { } } package cn.itcast.web.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class UserFilter implements Filter{ public void destroy() { } public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { /* * 得到session, * 判断session域中是否存在admin,如果存在放行 * 判断session中是否存在username,如果存在,放行,否则,大会login.jsp,并告诉它不要瞎溜达 */ HttpServletRequest req=(HttpServletRequest) arg0; String name=(String)req.getSession().getAttribute("admin"); if(name!=null){ arg2.doFilter(arg0, arg1); } name=(String) req.getSession().getAttribute("username"); if(name!=null){ arg2.doFilter(arg0, arg1); }else{ req.setAttribute("msg", "您啥都不是,不要瞎溜达!"); req.getRequestDispatcher("/login.jsp").forward(arg0, arg1); } } public void init(FilterConfig arg0) throws ServletException { } } <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>LoginServlet</servlet-name> <servlet-class>cn.itcast.web.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>UserFilter</filter-name> <filter-class>cn.itcast.web.filter.UserFilter</filter-class> </filter> <filter-mapping> <filter-name>UserFilter</filter-name> <url-pattern>/user/*</url-pattern> </filter-mapping> <filter> <filter-name>AdminFilter</filter-name> <filter-class>cn.itcast.web.filter.AdminFilter</filter-class> </filter> <filter-mapping> <filter-name>AdminFilter</filter-name> <url-pattern>/admin/*</url-pattern> </filter-mapping> </web-app>
3、全站编码问题

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.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> <a href="<c:url value='/AServlet?username=张三'/>">点击这里</a><br/> <form action="<c:url value='/AServlet'/>" method="post"> 用户名:<input type="text" name="username" value="李四"/> <input type="submit" value="提交"/> </form> </body> </html> package cn.itcast.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String username=request.getParameter("username"); response.getWriter().println(username); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String username=request.getParameter("username"); response.getWriter().println(username); } } package cn.itcast.web.filter; import java.io.UnsupportedEncodingException; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class EncodingRequest extends HttpServletRequestWrapper{ public EncodingRequest(HttpServletRequest request) { super(request); } public String[] getParameterValues(String name) { String[] paramValues=super.getParameterValues(name); if(paramValues==null) return null; try { for(int i=0;i<paramValues.length;i++){ String param=paramValues[i]; if(param==null){ continue; }else{ paramValues[i]=new String(param.getBytes("iso-8859-1"),"utf-8"); } } return paramValues; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public String getParameter(String name) { try { String value=super.getParameter(name); if(value==null) return null; return new String(value.getBytes("iso-8859-1"),"utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public Map getParameterMap() { Map<String,String> map=super.getParameterMap(); if(map==null) return null; Set<String> keys=map.keySet(); try { for(String key:keys){ String value=map.get(key); if(value==null){ continue; }else{ value=new String(value.getBytes("iso-8859-1"),"utf-8"); map.put(key, value); } } return map; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } package cn.itcast.web.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class EncodingFilter implements Filter{ public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { /*处理post请求的编码问题*/ request.setCharacterEncoding("utf-8"); HttpServletRequest req=(HttpServletRequest) request; /*处理get请求的编码问题*/ // String username=request.getParameter("username"); // username=new String(username.getBytes("iso-8859-1"),"utf-8"); 只能读不能写 /* * 掉包request * 1、写一个request的装饰类 * 2、在放行时使用我们自己的request * */ if(req.getMethod().equalsIgnoreCase("get")){ EncodingRequest er=new EncodingRequest(req); chain.doFilter(er, response); }else{ chain.doFilter(req, response); } } public void init(FilterConfig arg0) throws ServletException { } } <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>AServlet</servlet-name> <servlet-class>cn.itcast.web.servlet.AServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AServlet</servlet-name> <url-pattern>/AServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>EncodingFilter</filter-name> <filter-class>cn.itcast.web.filter.EncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>