标签:tco set amp response override app void nal ide
过滤器
过滤器概念:
过滤器也是一种特殊的 servlet, 需要在配置文件中进行配置或者使用注解进行配置,
过滤器可以将指定的请求拦截下来, 之后对被拦截的请求进行相关的处理或者验证,
处理完毕之后将拦截的请求继续方向
要实现过滤器需要使用到一个接口 "javax.servlet.Filter".
Demo: 使用过滤器处理字符编码
1.定义过滤器
1 public class MyFilter implements Filter { 2 @Override 3 public void init(FilterConfig filterConfig) throws ServletException { 4 System.out.println("过滤器初始化"); 5 } 6 @Override 7 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 8 throws IOException, ServletException { 9 System.out.println("对拦截的请求进行处理,之后放行"); 10 //向下转型 11 HttpServletRequest req = (HttpServletRequest)request; 12 HttpServletResponse resp = (HttpServletResponse)response; 13 //统一处理字符编码 14 resp.setContentType("text/html;charset=utf-8"); 15 req.setCharacterEncoding("utf-8"); 16 //放行请求 17 chain.doFilter(req, resp); 18 } 19 @Override 20 public void destroy() { 21 System.out.println("过滤器销毁"); 22 } 23 }
2.配置 web.xml 文件
<!-- 配置过滤器 --> <filter> <filter-name>myFilter</filter-name> <filter-class>com.sxt.mvcpro.filter.MyFilter</filter-class> </filter> <filter-mapping> <filter-name>myFilter</filter-name> <!-- 过滤器处理所有的路径 --> <url-pattern>/*</url-pattern> </filter-mapping>
3.定义表单
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <base href="/MvcPro/"/> 10 <meta charset="UTF-8"> 11 <title>Insert title here</title> 12 </head> 13 <body> 14 <form action="emp/login" method="POST"> 15 <fieldset> 16 用户名??: <input type="text" name="username" placehodler="输入用户名"><br><br> 17 密 码 ?: <input type="password" name="pwd" placehodler="输入密码"><br/><br/> 18 <input style="margin-left:60px" type="submit" value="提交"> 19 <input type="reset" value="重置"> 20 </fieldset> 21 </form> 22 </body> 23 </html>
标签:tco set amp response override app void nal ide
原文地址:https://www.cnblogs.com/yslf/p/10752755.html