过滤器的使用
过滤器的使用
Filter原理
使用Filter前后对比
package com.fakelogin.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; public class MyFilter implements Filter{ @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub System.out.println("--------Filter初始化-------"); } }
<?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"> <welcome-file-list> <welcome-file> login.html </welcome-file> <welcome-file> login.htm </welcome-file> <welcome-file> login.jsp </welcome-file> </welcome-file-list> <filter> <filter-name>MyFilter</filter-name> <filter-class>com.fakelogin.filter.MyFilter</filter-class> </filter> <filter-mapping> <filter-name>MyFilter</filter-name> <!-- 拦截所有的请求 --> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.fakelogin.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/servlet/LoginServlet</url-pattern> </servlet-mapping> </web-app>
遇到的一点问题
在写好Filter类并配置好.xml后,
提交表单却不能解决用户名乱码。
经过几次尝试后依然是不起作用,
突然发现MyFilter里有几行输出,
将其删除后程序竟成功跑起来了。
百度云
链接: https://pan.baidu.com/s/13VsNjiTEaUCBofRN5iI2dw 提取码: 6r2g 复制这段内容后打开百度网盘手机App,操作更方便哦
参考链接