12.Java web--过滤器与监听器
1)过滤器
就是为请求与目标之间加一个或多个过滤器
自定义过滤器要实现Filter接口
下面是定义一个所有Servlet的请求中文不乱码
/** * 用于servlet输出中文乱码的过滤 */ @WebFilter("/CharsetFilter") public class CharsetFilter implements Filter { private String encode; public CharsetFilter() { // TODO Auto-generated constructor stub } public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if(encode!="") { response.setCharacterEncoding(encode); response.setContentType("text/html;charset="+encode); } //FilterChain的作用是进入下一步过滤或直接到达请求目标 chain.doFilter(request, response); } public void init(FilterConfig fConfig) throws ServletException { //获取web.xml定义的参数 encode=(String)fConfig.getInitParameter("encode"); } }
相关要在web.xml配置,与servlet配置差不多
<filter> <filter-name>CharsetFilter</filter-name> <filter-class>crm.CharsetFilter</filter-class> <!-- 定义一些初始参数 --> <init-param> <param-name>encode</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharsetFilter</filter-name> <!-- /*是通配符的写法,也可指定为某一个servlet或jsp页进行过滤 如/index.jsp --> <url-pattern>/*</url-pattern> </filter-mapping>
2)监听器
可以监听web状态变化,web容器产生的相应事件
1.Servlet上下监听
有两个接口:
ServletContextListener接口:监听ServletContext的创建与删除
ServletAttributeListener接口:监听ServletContext属性的增加、删除、修改(application范围)
例子,ServletAtrributeListener使用
public class MyServletAttributeListener implements ServletContextAttributeListener { public MyServletAttributeListener() { // TODO Auto-generated constructor stub } //有新属性加入时触发 public void attributeAdded(ServletContextAttributeEvent scae) { // TODO Auto-generated method stub ServletContext context= scae.getServletContext(); System.out.println("新增name:"+scae.getName()+"="+scae.getValue()); } public void attributeRemoved(ServletContextAttributeEvent scae) { System.out.println("删除name:"+scae.getName()+"="+scae.getValue()); } public void attributeReplaced(ServletContextAttributeEvent scae) { System.out.println("修改name:"+scae.getName()+"="+scae.getValue()); } }
web.xml的配置
<listener> <listener-class>crm.MyServletAttributeListener</listener-class> </listener>
2.HTTP会话监听接口
HttpSessionListenner:监听会话的创建、销毁
HttpSessionActivationListener:监听HTTP会话的active\passivate
HttpBindingListener:当有对象加入移除session时触发,唯一一个不需要在web.xml配置,只要实例化即可启用
HttpSessionAttributeListener:设置session的Attribute时触发
3.Servlet请求监听
ServletRequestListener :ServletRequest的创建与变更
ServletRequestAttributeListener :ServletRequest的Attribute变化时
3)新增注释
像Servlet、Filter、Listener、WebInitParam等都要在web.xml配置,现在新增在类的实现方法,不需要再在web.xml配置
只要在自定义的Servlet类上标注,如
@WebServlet(name="MyServlet",value= "/MyServlet", initParams= {@WebInitParam(name="weburl",value="http://www.x.com")}) public class MyServlet extends HttpServlet { }
2. @WebFilter
3.WebListener
@WebListener("用于XXX")
4. @WebInitParam
5. @MultipartConfig
用于上传文件,用在Servlet类,且在@WebServlet注释之下
@WebServlet("/UpServlet") @MultipartConfig(location="E:\\study\\java\\crm\\WebContent") public class UpServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public UpServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); String path=getServletContext().getRealPath("/");//获取服务器地址 Part p=request.getPart("file1");//获取用户选择的文件 if(p.getContentType().contains("image")) { //仅处理图片的上传 ApplicationPart ap=(ApplicationPart)p; String fnName=ap.getName(); p.write( "E:\\study\\java\\crm\\WebContent\\upload\\aa.jpg"); out.write("上传成功"); } } }
要指定multipart/form-data
<form action="/crm/UpServlet" method="post" enctype="multipart/form-data"> <input type="file" name="file1" id="file1" /> <button type="submit">提交</button> </form>
6)异步处理
Servlet和Filter可以异步
@WebFilter(filterName="CharsetFilter",asyncSupported=true) 或者 <filter> <filter-name>CharsetFilter</filter-name> <filter-class>crm.CharsetFilter</filter-class> <async-supported>true</async-supported> </filter>