12.Java web--过滤器与监听器
1)过滤器
就是为请求与目标之间加一个或多个过滤器
自定义过滤器要实现Filter接口
下面是定义一个所有Servlet的请求中文不乱码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | /** * 用于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配置差不多
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <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使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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的配置
1 2 3 | <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类上标注,如
1 2 3 | @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注释之下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | @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
1 2 3 4 | <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可以异步
1 2 3 4 5 6 7 | @WebFilter (filterName= "CharsetFilter" ,asyncSupported= true ) 或者 <filter> <filter-name>CharsetFilter</filter-name> <filter- class >crm.CharsetFilter</filter- class > <async-supported> true </async-supported> </filter> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2017-10-23 移动端上传图片