过滤器

什么是过滤器

         1示意图:

 

  过滤器的作用:

         1.过滤器的作用好比一个保安。是servlet规范中的技术

         2.用户在访问应用的资源之前或者之后,可以对请求做出一定的处理

  编写过滤器步骤:

         1.编写一个类,实现javax.servlet.Filter接口

      

         2.配置过滤哪些资源 :修改web.xml配置要过滤的映射地址

      

        3.让目标资源执行,放行:

      

     <filter>
<filter-name/>
<filter-class/>
</filter>
<filter-mapping>
<filter-name/>
<url-pattern/> /servlet/* *.jsp
<dispatcher/> REQUEST(默认的) FROWARD INCLUDE ERROR
</filter-mapping>

配置web.xml,指定哪些资源需要过滤

  过滤器的生命周期

           1.过滤器实例由服务器创建的,其中的方法也是由服务器调用的

           2.过滤器在应用被加载时实例化并初始化(调用init方法),只有一次;用户每次访问过滤范围之内的资源,过滤器的DoFilter方法都会执行一次:应用被卸载或者服务器停止时会调用销毁方法(destroy方法)

           3.特点:过滤器中的实例变量,注意线程安全问题;

  过滤器的过滤顺序

         1.责任设计模式:

                

            二:多个过滤器代码执行顺序:

                        

                         

                        总结:多个过滤器过滤相同的资源,过滤顺序按照web中的filter的出现顺序依次进行过滤。类似于栈

Servlet VS Filter:

    1.servlet能做的过滤器都可以做,过滤器比servlet多了一个放行的功能。

    2.servlet在开发中是作为控制器来用的;Filter也可以作为控制器来用

    3.Struct1框架:servlet作为控制器

       Struct2框架:Filter作为控制器

    

  过滤器的简单案例:

            1.过滤器设置提交数据编码:

            

            

          1、解决POST请求参数和响应输出的编码过滤器:

              

              web.xml配置文件:

              

              二:动态资源不要缓存过滤器:

                            

                

                            

                三:控制静态资源的缓存时间:

                              

                                

自动登入过滤器案例

实体类:

 import java.io.Serializable;

 public class User implements Serializable {
private String username;
private String password; public User(){} public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
} }

User

 import java.util.ArrayList;
import java.util.List; public class UserDB {
private static List<User> users = new ArrayList<User>();
static{
users.add(new User("王斐", "123"));
users.add(new User("王昭珽", "123"));
}
public static User findUser(String username,String password){
for(User u:users){
if(username.equals(u.getUsername())&&password.equals(u.getPassword())){
return u;
}
}
return null;
}
public static User findUser(String username){
for(User u:users){
if(username.equals(u.getUsername())){
return u;
}
}
return null;
}
}

UserDB

过滤器类:

 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.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import com.itheima.domain.User;
import com.itheima.domain.UserDB;
import com.itheima.util.Base64Util;
import com.itheima.util.MD5Util;
//实现自动登录的过滤器
public class AutoLoginFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException { HttpServletRequest request;
HttpServletResponse response;
try{
request = (HttpServletRequest)req;
response = (HttpServletResponse)resp;
}catch(Exception e){
throw new RuntimeException("non-http request");
}
//判断用户是否登录
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
//没有登录:自动登录
if(user==null){
//从cookie中取数据:用户名和密码
Cookie cs[] = request.getCookies();
for(int i=0;cs!=null&&i<cs.length;i++){
Cookie c = cs[i];
if("loginInfo".equals(c.getName())){
//再次验证用户名和密码的正确性
String usernameBase64 = c.getValue().split("_")[0];
String passwordMD5 = c.getValue().split("_")[1]; String username = Base64Util.base64decode(usernameBase64);
User dbUser = UserDB.findUser(username);
if(passwordMD5.equals(MD5Util.md5(dbUser.getPassword()))){
//用户名和密码都正确
session.setAttribute("user", dbUser);
} }
}
}
//放行
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException { } public void destroy() { } }

AutoLoginFilter

 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;
import javax.servlet.http.HttpServletResponse;
//动态资源不要缓存
public class DynamicResourceNoCacheFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException { HttpServletRequest request;
HttpServletResponse response;
try{
request = (HttpServletRequest)req;
response = (HttpServletResponse)resp;
}catch(Exception e){
throw new RuntimeException("non-http request");
} response.setHeader("Expires", "-1");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
chain.doFilter(request, response);
} public void destroy() { } }

DynamicResourceNoCacheFilter

 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;
//解决POST请求参数和响应输出的编码过滤器
public class SetCharacterEncodingFilter implements Filter {
private FilterConfig filterConfig;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
} public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
String encoding = "UTF-8";//默认参数
String value = filterConfig.getInitParameter("encoding");
if(value!=null){
encoding = value;
} request.setCharacterEncoding(encoding);//POST请求方式
response.setContentType("text/html;charset="+encoding);
chain.doFilter(request, response);
} public void destroy() { } }

SetCharacterEncodingFilter

控制器类

 import java.io.IOException;

 import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.itheima.domain.User;
import com.itheima.domain.UserDB;
import com.itheima.util.Base64Util;
import com.itheima.util.MD5Util; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String remember = request.getParameter("remember");
User user = UserDB.findUser(username, password);
if(user!=null){
request.getSession().setAttribute("user", user);
username = Base64Util.base64encode(username);
password = MD5Util.md5(password);
//保存cookie
Cookie cookie = new Cookie("loginInfo", username+"_"+password);//用户名_密码
cookie.setPath(request.getContextPath());//当前应用都能获取该Cookie
if(remember!=null){
cookie.setMaxAge(Integer.MAX_VALUE);
}else{
cookie.setMaxAge(0);
}
response.addCookie(cookie); response.getWriter().write("登录成功!2秒后转向主页");
response.setHeader("Refresh", "2;URL="+request.getContextPath());
}else{
response.getWriter().write("错误的用户名或密码");
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

LoginServlet

 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 LogoutServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getSession().removeAttribute("user");
response.getWriter().write("注销成功!2秒后转向主页");
response.setHeader("Refresh", "2;URL="+request.getContextPath());
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

LogoutServlet

油条类:

 import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import sun.misc.BASE64Encoder; public class MD5Util {
public static String md5(String str){
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte b[] = md.digest("123".getBytes());//返回值是二进制,不一定对应着可见字符
//数据指纹 String s = new BASE64Encoder().encode(b);
return s;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}

MD5Util

 import java.io.IOException;
import java.io.UnsupportedEncodingException; import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; public class Base64Util {
public static String base64encode(String str){
BASE64Encoder base64 = new BASE64Encoder();
String s1 = base64.encode(str.getBytes());//GBK
return s1;
}
public static String base64encode(String str,String charaset) throws UnsupportedEncodingException{
BASE64Encoder base64 = new BASE64Encoder();
String s1 = base64.encode(str.getBytes(charaset));
return s1;
}
public static String base64decode(String str) throws IOException{
BASE64Decoder base64 = new BASE64Decoder();
byte b[] = base64.decodeBuffer(str);
return new String(b);//GBK
}
public static String base64decode(String str,String charaset) throws IOException{
BASE64Decoder base64 = new BASE64Decoder();
byte b[] = base64.decodeBuffer(str);
return new String(b,charaset);//GBK
}
}

Base64Util

BASE64编码(很重要)

                        1.原理:3个字节变成4个字节(计算机中存储的都是字节)

                        2.编码原理:

                          1010 0101      1110 0100     1001 1111                 三个字节

                           0010 1001     0001 1110      0001 0010      0001 1111               四个字节(不够就前面补0,补两个)

                        每个字节表示的范围:00000000~0011111, 

                          表示的整数范围:0~63;每一个整数都对应着键盘上的一个可见字符;

                        3.Base64是一个码表;可以把任何的二进制转变为可见字符串(A~Z,a~z,0~9,+/)

                        4.解决汉字存入cookie及MD5加密密码的问题:

 import java.io.IOException;

 import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.itheima.domain.User;
import com.itheima.domain.UserDB;
import com.itheima.util.Base64Util;
import com.itheima.util.MD5Util; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String remember = request.getParameter("remember");
User user = UserDB.findUser(username, password);
if(user!=null){
request.getSession().setAttribute("user", user);
username = Base64Util.base64encode(username);
password = MD5Util.md5(password);
//保存cookie
Cookie cookie = new Cookie("loginInfo", username+"_"+password);//用户名_密码
cookie.setPath(request.getContextPath());//当前应用都能获取该Cookie
if(remember!=null){
cookie.setMaxAge(Integer.MAX_VALUE);
}else{
cookie.setMaxAge(0);
}
response.addCookie(cookie); response.getWriter().write("登录成功!2秒后转向主页");
response.setHeader("Refresh", "2;URL="+request.getContextPath());
}else{
response.getWriter().write("错误的用户名或密码");
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

LoginServlet

 import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import sun.misc.BASE64Encoder; public class MD5Util {
public static String md5(String str){
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte b[] = md.digest("123".getBytes());//返回值是二进制,不一定对应着可见字符
//数据指纹 String s = new BASE64Encoder().encode(b);
return s;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}

MD5Util

 import java.io.IOException;
import java.io.UnsupportedEncodingException; import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; public class Base64Util {
public static String base64encode(String str){
BASE64Encoder base64 = new BASE64Encoder();
String s1 = base64.encode(str.getBytes());//GBK
return s1;
}
public static String base64encode(String str,String charaset) throws UnsupportedEncodingException{
BASE64Encoder base64 = new BASE64Encoder();
String s1 = base64.encode(str.getBytes(charaset));
return s1;
}
public static String base64decode(String str) throws IOException{
BASE64Decoder base64 = new BASE64Decoder();
byte b[] = base64.decodeBuffer(str);
return new String(b);//GBK
}
public static String base64decode(String str,String charaset) throws IOException{
BASE64Decoder base64 = new BASE64Decoder();
byte b[] = base64.decodeBuffer(str);
return new String(b,charaset);//GBK
}
}

Base64Util

过滤器的高级配置

              

1.静态包含:将多个界面作为一个资源,所以过滤器只过滤一次

2.服务器内部转发如果不进行配置xml文件,那就只过滤一次:

巩固装饰设计模式

              

              1、定义一个类实现与被包装类相同的接口

              2、定义一个变量,引用被包装类的实例

              3、定义构造方法,传入被包装类实例

              4、对于要改变的方法,改写即可

              5、对于不需要改变的方法,调用被包装类原有的方法

 package com.base;

 import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader; public class BufferedReaderDemo { public BufferedReaderDemo() {
// TODO Auto-generated constructor stub
} public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Reader r=new FileReader("src/com/base/BufferedReaderDemo.java");
BufferedReader br=new BufferedReader(r);//本身就是一个包装类
MyBufferedReader mbr=new MyBufferedReader(br); String data=null;
while((data=mbr.readLine())!=null){
System.out.println(data);
}
mbr.close();
} }

BufferedReaderDemo

 package com.base;

 import java.io.BufferedReader;
import java.io.IOException; public class MyBufferedReader extends BufferedReader {
private BufferedReader br;
private int num=1; public MyBufferedReader(BufferedReader br) {
// TODO Auto-generated constructor stub
super(br);
this.br=br;
}
//public String readLine() throws IOException{
// return num+++br.readLine();
//}
public String readLine() throws IOException{
String data=br.readLine();
if(data!=null){
data=num+++data;
}
return data;
} //private int num=1;
//public MyBufferedReader(BufferedReader br) {
// super(br);
//}
//public String readLine() throws IOException{
// String data=super.readLine();
// if(data!=null){
// data=num+++data;
// }
// return data;
//}
}

MyBufferedReader

过滤器的高级案例

解决全站中文乱码过滤器(get,post):

案例撸上:

 package com.itheima.filter;

 import java.io.IOException;
import java.io.UnsupportedEncodingException; 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;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
//解决GET和POST请求参数和响应输出的编码过滤器
public class SetAllCharacterEncodingFilter implements Filter {
private FilterConfig filterConfig;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
} public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request;
HttpServletResponse response;
try{
request = (HttpServletRequest)req;
response = (HttpServletResponse)resp;
}catch(Exception e){
throw new RuntimeException("non-http request");
}
String encoding = "UTF-8";//默认参数
String value = filterConfig.getInitParameter("encoding");
if(value!=null){
encoding = value;
} request.setCharacterEncoding(encoding);//POST请求方式
response.setContentType("text/html;charset="+encoding);
MyHttpServletRequest mrequest = new MyHttpServletRequest(request);
chain.doFilter(mrequest, response);
} public void destroy() { } }
class MyHttpServletRequest extends HttpServletRequestWrapper{
private HttpServletRequest request;
public MyHttpServletRequest(HttpServletRequest request){
super(request);
this.request = request;
}
public String getParameter(String name) {
String value = request.getParameter(name);
if(value==null)
return value;
try {
if("get".equalsIgnoreCase(request.getMethod()))
value = new String(value.getBytes("ISO-8859-1"),request.getCharacterEncoding());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return value;
} }

SetAllCharacterEncodingFilter

 <?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>
<filter>
<filter-name>SetAllCharacterEncodingFilter</filter-name>
<filter-class>com.itheima.filter.SetAllCharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SetAllCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

web.xml

脏话过滤器

 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;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse; public class DirtyWordsFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request;
HttpServletResponse response;
try{
request = (HttpServletRequest)req;
response = (HttpServletResponse)resp;
}catch(Exception e){
throw new RuntimeException("non-http request");
}
DirtyWordHttpServletRequest dwrequest = new DirtyWordHttpServletRequest(request);
chain.doFilter(dwrequest, response); } public void destroy() { } }
class DirtyWordHttpServletRequest extends HttpServletRequestWrapper{
private String strs[] = {"傻逼","畜生","禽兽"};
private HttpServletRequest request;
public DirtyWordHttpServletRequest(HttpServletRequest request){
super(request);
this.request = request;
}
@Override
public String getParameter(String name) {
String value = request.getParameter(name);
if(value==null)
return null;
for(String s:strs){
if(value.contains(s)){
value = value.replace(s, "**");
}
}
return value;
} }

DirtyWordsFilter

 <?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>
<filter>
<filter-name>SetAllCharacterEncodingFilter</filter-name>
<filter-class>com.itheima.filter.SetAllCharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SetAllCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <filter>
<filter-name>DirtyWordsFilter</filter-name>
<filter-class>com.itheima.filter.DirtyWordsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>DirtyWordsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

web.xml

HTML标记过滤器

 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;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse; public class HtmlFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request;
HttpServletResponse response;
try{
request = (HttpServletRequest)req;
response = (HttpServletResponse)resp;
}catch(Exception e){
throw new RuntimeException("non-http request");
} HtmlHttpServletRequest hrequest = new HtmlHttpServletRequest(request);
chain.doFilter(hrequest, response); } public void destroy() { } }
class HtmlHttpServletRequest extends HttpServletRequestWrapper{
private HttpServletRequest request;
public HtmlHttpServletRequest(HttpServletRequest request){
super(request);
this.request = request;
}
@Override
public String getParameter(String name) {
String value = request.getParameter(name);
if(value==null)
return null;
value = htmlFilter(value);
return value;
}
private String htmlFilter(String message) {
if (message == null)
return (null); char content[] = new char[message.length()];
message.getChars(0, message.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
switch (content[i]) {
case '<':
result.append("&lt;");
break;
case '>':
result.append("&gt;");
break;
case '&':
result.append("&amp;");
break;
case '"':
result.append("&quot;");
break;
default:
result.append(content[i]);
}
}
return (result.toString());
} }

HtmlFilter

 <?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>
<filter>
<filter-name>SetAllCharacterEncodingFilter</filter-name>
<filter-class>com.itheima.filter.SetAllCharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SetAllCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <filter>
<filter-name>DirtyWordsFilter</filter-name>
<filter-class>com.itheima.filter.DirtyWordsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>DirtyWordsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>HtmlFilter</filter-name>
<filter-class>com.itheima.filter.HtmlFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HtmlFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>ServletDemo1</servlet-name>
<servlet-class>com.itheima.servlet.ServletDemo1</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>ServletDemo1</servlet-name>
<url-pattern>/servlet/ServletDemo1</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

web.xml

Fzip压缩过滤器

过滤器:Filter

 import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.zip.GZIPOutputStream; import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper; public class GzipFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request;
HttpServletResponse response;
try{
request = (HttpServletRequest)req;
response = (HttpServletResponse)resp;
}catch(Exception e){
throw new RuntimeException("non-http request");
}
MyHttpServletResponse myresponse = new MyHttpServletResponse(response); chain.doFilter(request, myresponse);
//压缩代码应放到放行后
byte b[] = myresponse.getBytes();//如何拿到原始的数据字节序列
System.out.println("压缩前大小:"+b.length);
ByteArrayOutputStream out = new ByteArrayOutputStream();//内存数组流:缓存输出流
GZIPOutputStream gout = new GZIPOutputStream(out);
gout.write(b);
gout.close();// 压缩后的数据到ByteArrayOutputStream中了 b = out.toByteArray();//取出压缩后的数据
System.out.println("压缩后大小:"+b.length); //通知浏览器正文的压缩格式
response.setHeader("Content-Encoding", "gzip"); response.getOutputStream().write(b);
} public void destroy() { } } class MyHttpServletResponse extends HttpServletResponseWrapper{
private HttpServletResponse response;
private ByteArrayOutputStream baos = new ByteArrayOutputStream();//存放缓存的字节流输出的数据
private PrintWriter pw;
public MyHttpServletResponse(HttpServletResponse response){
super(response);
this.response = response;
}
//字节流.覆盖该方法的目的,截获原始的数据
public ServletOutputStream getOutputStream() throws IOException {
return new MyServletOutputStream(baos);
}
//字符流输出
public PrintWriter getWriter() throws IOException {
pw = new PrintWriter(new OutputStreamWriter(baos, response.getCharacterEncoding()));
return pw;
}
public byte[] getBytes(){
try {
if(pw!=null)
pw.close();
baos.flush();
} catch (IOException e) {
e.printStackTrace();
}
return baos.toByteArray();
}
} class MyServletOutputStream extends ServletOutputStream{
private ByteArrayOutputStream baos;
public MyServletOutputStream(ByteArrayOutputStream baos){
this.baos = baos;
}
public void write(int b) throws IOException {
baos.write(b);
} }

GzipFilter

 import java.io.IOException;
import java.io.UnsupportedEncodingException; 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;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
//解决GET和POST请求参数和响应输出的编码过滤器
public class SetAllCharacterEncodingFilter implements Filter {
private FilterConfig filterConfig;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
} public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request;
HttpServletResponse response;
try{
request = (HttpServletRequest)req;
response = (HttpServletResponse)resp;
}catch(Exception e){
throw new RuntimeException("non-http request");
}
String encoding = "UTF-8";//默认参数
String value = filterConfig.getInitParameter("encoding");
if(value!=null){
encoding = value;
} request.setCharacterEncoding(encoding);//POST请求方式
response.setCharacterEncoding(encoding);
response.setContentType("text/html;charset="+encoding);
MyHttpServletRequest mrequest = new MyHttpServletRequest(request);
chain.doFilter(mrequest, response);
} public void destroy() { } }
class MyHttpServletRequest extends HttpServletRequestWrapper{
private HttpServletRequest request;
public MyHttpServletRequest(HttpServletRequest request){
super(request);
this.request = request;
}
public String getParameter(String name) {
String value = request.getParameter(name);
if(value==null)
return value;
try {
if("get".equalsIgnoreCase(request.getMethod()))
value = new String(value.getBytes("ISO-8859-1"),request.getCharacterEncoding());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return value;
} }

SetAllCharacterEncodingFilter

控制器:Servlet

 import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream; import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//gzip压缩输出
public class ServletDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data = "<h1>中中</h1>";
ServletOutputStream sos = response.getOutputStream();
sos.write(data.getBytes("UTF-8")); // byte b[] = data.getBytes();
// System.out.println("压缩前大小:"+b.length);
// ByteArrayOutputStream out = new ByteArrayOutputStream();//内存数组流:缓存输出流
// GZIPOutputStream gout = new GZIPOutputStream(out);
// gout.write(b);
// gout.close();// 压缩后的数据到ByteArrayOutputStream中了
//
//
// b = out.toByteArray();//取出压缩后的数据
// System.out.println("压缩后大小:"+b.length);
//
// //通知浏览器正文的压缩格式
// response.setHeader("Content-Encoding", "gzip"); // response.getOutputStream().write(b);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

ServletDemo1

 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 ServletDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data = "你dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd";
PrintWriter out = response.getWriter();
out.write(data);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

ServletDemo2

配置文件:web.xml

 <?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>
<filter>
<filter-name>SetAllCharacterEncodingFilter</filter-name>
<filter-class>com.itheima.filter.SetAllCharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SetAllCharacterEncodingFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>SetAllCharacterEncodingFilter</filter-name>
<url-pattern>*.js</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>SetAllCharacterEncodingFilter</filter-name>
<url-pattern>*.css</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>SetAllCharacterEncodingFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<filter>
<filter-name>GzipFilter</filter-name>
<filter-class>com.itheima.filter.GzipFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>GzipFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>ServletDemo1</servlet-name>
<servlet-class>com.itheima.servlet.ServletDemo1</servlet-class>
</servlet>
<servlet>
<servlet-name>ServletDemo2</servlet-name>
<servlet-class>com.itheima.servlet.ServletDemo2</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>ServletDemo1</servlet-name>
<url-pattern>/servlet/ServletDemo1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ServletDemo2</servlet-name>
<url-pattern>/servlet/ServletDemo2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

web.xml

JavaWeb之过滤器的更多相关文章

  1. [javaweb]Java过滤器与包装设计模式的实用案例.

    在filter中可以得到代表用户请求和响应的request.response对象,因此在编程中可以使用Decorator(装饰器)模式对request.response对象进行包装,再把包装对象传给目 ...

  2. JavaWeb基础—过滤器Filter

    一.概念 JavaWeb三大组件之一(组件都有一个特性,需要在web.xml中配置) 过滤器:会在一组资源(jsp servlet等)的前面执行,可以让请求得到目标资源,也可以终止请求,不再继续 也就 ...

  3. JavaWeb 之过滤器

    1. 什么是过滤器 Servlet 是用来处理请求的, 过滤器是用来拦截请求的. 当用户请求某个 Servlet 时,会先执行部署在这个请求上的 Filter, 而 Filter 决定是否调用 Ser ...

  4. IT兄弟连 JavaWeb教程 过滤器3

    过滤器案例:字符编码过滤器 在JavaWeb程序开发中,由于Web容器内部所使用编码格式并不支持中文字符集,所以,处理浏览器请求中的中文数据就会出现乱码现象. 图3  无字符编码过滤器 从上图可以看出 ...

  5. IT兄弟连 JavaWeb教程 过滤器1

    Servlet过滤器是从Servlet2.3规范开始新增的功能,并在Servlet2.4规范中得到增强,监听器可以监听到Web应用程序启动和关闭.创建过滤器和监听器需要继承相应接口,并对其进行配置. ...

  6. JavaWeb 10_Filter过滤器

    一.什么是Filter? 1.Filter 过滤器它是JavaWeb的三大组件之一-.三大组件分别是: Servlet 程序.Listener 监听器.Filter 过滤器2.Filter 过滤器它是 ...

  7. javaweb登陆过滤器实现

    在web.xml中配置登陆过滤器: <!-- 配置登陆过滤器 --> <filter> <filter-name>loginFilter</filter-na ...

  8. JavaWeb中过滤器Filter的使用示例

    https://github.com/YouXianMing/Java-Web-Study/tree/master/Servlet-Filter 过滤器示例基于以下流程 测试效果如下 web.xml配 ...

  9. JavaWeb基础-过滤器监听器

    过滤器 1定义:过滤器是一个服务器的组件,他可以截取用户端的请求与响应信息,并对这些信息进行过滤;过滤器可以动态地拦截请求和响应,以变换或使用包含在请求或响应中的信息. 2过滤器的工作原理: 3过滤器 ...

  10. JavaWeb的过滤器Filter

    Filter的作用是在请求到达web资源(HTML.css.Servlet.Jsp)之前拦截,做一个预处理. 创建一个类实现Filter接口,在web.xml中对文件进行配置 <filter&g ...

随机推荐

  1. mybatis--Spring整合mybatis

    今天学习了mybatis整合Spring开发,做了一个mybatis+spring的小实例 (1)首先,创建数据库my,并在数据库my中创建表user create database my; use ...

  2. 505,display,float,position之间的关系(有疑问)

    (display属性设置元素如何显示) 如果display取值为none,那么position和float都不起作用,这种情况下元素不产生框 否则,如果position设置框是绝对定位,float的计 ...

  3. Codeforces Global Round 6D(VECTOR<ARRAY<INT,3> >)

    一个人只要存在债务关系,那么他的债务可以和这整个债务关系网中任何人连边,和他当初借出或欠下的人没有关系.只需要记录他的债务值即可. #define HAVE_STRUCT_TIMESPEC #incl ...

  4. logstash output到kafka记录与总结( No entry found for connection 2)

    简述 本文记录logstash的output配置为kafka的过程.这里是简单的例子,输入为stdin,本文主要目的是为了记录在这次配置过程中遇到的问题和解决的过程及总结. 关于kafka集群的搭建可 ...

  5. 【Python】如何处理Excel中的数据

    我们平时在做自动化测试的时候,可能会涉及到从表格中去读取或者存储数据,我们除了可以使用openpyxl来操作excel,当然也可以利用pandas来完成,这篇随笔只是我在学习过程中的简单记录,其他的功 ...

  6. 普通的javaweb项目和用maven管理的javaweb project的目录结构的区别

      图一,图二 这种就是单独的建立普通的(也就是没有用maven管理包)javaweb项目的结构目录,这种需要将普通的jar依赖放到lib目录下,之后通过bulid   图一

  7. 清华大学慕课 (mooc) 数据结构-邓俊辉-讲义-合并版

    邓公的数据结构一直好评如潮,可惜我如今才开始学习它.QAQ 昨天,<数据结构 (2020 春)>的讲义已经推到清华大学云盘上了.苦于 10 拼页的打印版不易在 PC 上阅读(手机上更是如此 ...

  8. Javascript——(2)DOM

    1.DOM 1)直接寻找 (1)document.getElementById()     //根据ID获取一个标签: (2)   document.getElementsByName()    // ...

  9. Windows系统重装记录

    材料: u盘(需4g以上) windows官方镜像 附:windows个版本比较 步骤: u盘格式化(为了装启动盘系统需要清空数),备份系统盘所需要的的数据 下载适合自己的官方镜像,可从该网站下载(官 ...

  10. iframe多层嵌套时,Jquery获取元素

    在项目中,尤其是后台管理项目,会使用到iframe嵌套的网页,说起iframe,真的是个让人头疼的东西,能避开是最好避开.不然要请随身备好氧气瓶哈(因为管理和调试过程中往往会被气缺氧!!!哈哈哈~~~ ...