2.一個(gè)簡(jiǎn)單的過濾器
1.任何過濾器都要實(shí)現(xiàn)javax.servlet.Filter 接口
2.在web.xml 中對(duì)過濾器進(jìn)行配置代兵,說明Url的范圍
3.在過濾器的doFilter()方法中編寫過濾器的功能代碼
//MyFirstFilter .java
package com.imooc.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 MyFirstFilter implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("過濾器已被銷毀");//tomcat停止時(shí),這里會(huì)執(zhí)行
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("過濾器已生效");//每一個(gè)請(qǐng)求過來以后乾忱,在這里進(jìn)行攔截處理
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
System.out.println("過濾器初始化成功");//web應(yīng)用啟動(dòng)時(shí)自動(dòng)執(zhí)行
}
}
//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>first_filter</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- filter標(biāo)簽用于說明哪個(gè)類是過濾器惯疙,并在應(yīng)用啟動(dòng)時(shí)誉券,自動(dòng)加載 -->
<filter>
<filter-name>MyFirstFilter</filter-name>
<filter-class>com.imooc.filter.MyFirstFilter</filter-class>
</filter>
<!--
filter-mapping 標(biāo)簽用于說明過濾器對(duì)URL應(yīng)用的范圍瓶摆,要點(diǎn)有二:
1.filter-name 過濾器名稱與filter.filter-name保持一致
2.url-pattern 說明過濾器作用范圍阁危,/* 代表對(duì)所有URL進(jìn)行過濾
-->
<filter-mapping>
<filter-name>MyFirstFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
//HelloServlet.java
package com.imooc.filter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloServlet
*/
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public HelloServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("Hello World");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
只要是訪問http://localhost:8080/first_filter/
下的任何有效地址,由于web.xml配置的是/*
,都會(huì)執(zhí)行doFilter方法
擂煞,輸出過濾器生效
3.過濾器的兩種開發(fā)方式
3.1 配置形式
3.2 注解形式
xml配置的過濾器優(yōu)先執(zhí)行于注解配置的過濾器,但是項(xiàng)目中不要對(duì)兩種形式混用
//注解形式
package com.imooc.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;
import javax.servlet.annotation.WebFilter;
/**
* Servlet Filter implementation class MyAnnotationFilter
*/
@WebFilter(filterName="MyAnnotationFilter",urlPatterns="/*")
public class MyAnnotationFilter implements Filter {
/**
* Default constructor.
*/
public MyAnnotationFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
System.out.println("注解形式過濾器已經(jīng)生效");
// pass the request along the filter chain
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
4字符集過濾器
package com.imooc.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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CharacterEncodingFilter 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
HttpServletRequest req = (HttpServletRequest)request;
//HttpServletRequest的父接口是ServletRequest
req.setCharacterEncoding("UTF-8");
HttpServletResponse res = (HttpServletResponse)response;
response.setContentType("text/html;charset=UTF-8");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
其實(shí)就是趴乡,request和response對(duì)于中文字符对省,都需要命令設(shè)置。原來是放在doGet或者doPost中晾捏,因?yàn)檫^濾器每條request和response都會(huì)在這里處理蒿涎,因此在可以在過濾器這里設(shè)置字符集命令會(huì)很方便
5過濾器參數(shù)化標(biāo)簽
5.1
如上圖,在web.xml中定義參數(shù)
如上圖惦辛,在CharacterEncodingFilter.java 中加載參數(shù)劳秋,然后使用
過濾器參數(shù)化標(biāo)簽的好處,
在web.xml中定義參數(shù)胖齐,因?yàn)閣eb.xml是文本玻淑,不用編譯,修改參數(shù)呀伙,重啟應(yīng)用就可以用了补履,如果在程序中寫死,需要重新便宜区匠,而且比較麻煩
5.2 也可以使用注解
6 UrlPattern設(shè)置過濾范圍
6.1 配置模式
//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>url-pattern</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>UrlPatternFilter</filter-name>
<filter-class>com.imooc.filter.UrlPatternFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UrlPatternFilter</filter-name>
<url-pattern>/test.jsp</url-pattern> <!-- 精準(zhǔn)攔截 -->
</filter-mapping>
<filter-mapping>
<filter-name>UrlPatternFilter</filter-name>
<url-pattern>/</url-pattern> <!-- 攔截根目錄 -->
</filter-mapping>
<filter-mapping>
<filter-name>UrlPatternFilter</filter-name>
<url-pattern>/*</url-pattern> <!-- 攔截根目錄后面的所有 -->
</filter-mapping>
</web-app>
//UrlPatternFilter.jsp
package com.imooc.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;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*@WebFilter(filterName="UrlPatternFilter" , urlPatterns= {
"/","/Servlet/*","*.jsp"
})*/
public class UrlPatternFilter implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
System.out.println("攔截到:" + req.getRequestURL());
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
//test.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
I'm test page!
</body>
</html>
//index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
I'm index.jsp
</body>
</html>
//SampleServlet1 .java
package com.imooc.filter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SampleServlet1
*/
@WebServlet("/servlet/sample1")
public class SampleServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SampleServlet1() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("I'm "+ this.getClass().getSimpleName());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
//
package com.imooc.filter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SampleServlet1
*/
@WebServlet("/")
public class SampleServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SampleServlet2() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("I'm "+ this.getClass().getSimpleName());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
//SampleServlet2.java
package com.imooc.filter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SampleServlet1
*/
@WebServlet("/")
public class SampleServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SampleServlet2() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("I'm "+ this.getClass().getSimpleName());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
注意:
- index.jsp 是默認(rèn)首頁(yè)干像,在訪問
http://localhost:8080/url-pattern/
時(shí)會(huì)訪問默認(rèn)首頁(yè),但是默認(rèn)首頁(yè)的存在驰弄,會(huì)使映射地址也為
@WebServlet("/")
public class SampleServlet2 extends HttpServlet {
的servlet失效麻汰,因此戚篙,在實(shí)際開發(fā)中岔擂,盡量避免使用默認(rèn)首頁(yè),避免帶來一些訪問失效的問題
6.2 使用注解
7.過濾鏈
//FilterB
package com.imooc.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;
import javax.servlet.annotation.WebFilter;
@WebFilter(filterName="FilterB" , urlPatterns="/*")
public class FilterB implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("I'm Filter B");
chain.doFilter(request, response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
//FilterC.java
package com.imooc.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;
import javax.servlet.annotation.WebFilter;
@WebFilter(filterName="FilterC" , urlPatterns="/*")
public class FilterC implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("I'm Filter C");
chain.doFilter(request, response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
//FilterZ.java
package com.imooc.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;
import javax.servlet.annotation.WebFilter;
@WebFilter(filterName="FilterZ" , urlPatterns="/*")
public class FilterZ implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("I'm Filter Z");
chain.doFilter(request, response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
//HelloServlet.java
package com.imooc.filter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloServlet
*/
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public HelloServlet() {
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().print("Hello World!");
System.out.println("Hello World!");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>filter-chain</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>FilterA</filter-name>
<filter-class>com.imooc.filter.FilterA</filter-class>
</filter>
<filter>
<filter-name>FilterB</filter-name>
<filter-class>com.imooc.filter.FilterB</filter-class>
</filter>
<filter>
<filter-name>FilterC</filter-name>
<filter-class>com.imooc.filter.FilterC</filter-class>
</filter>
<filter-mapping>
<filter-name>FilterA</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>FilterB</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>FilterC</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
注意:
1.在配置文件web.xml中,是根據(jù)·filter-mapping·的順序決定過濾鏈的順序掘鄙,而在注解中嗡髓,是根據(jù)過濾器的類名的按照名稱升序排序,顯然前者更靠譜浊伙,后者不可控蛹稍。
2.chain.doFilter(request, response);
可控制是否繼續(xù)傳遞唆姐,利用它奉芦,可以對(duì)特定條件的東西判斷是否執(zhí)行該函數(shù)声功。
8.多端設(shè)備頁(yè)面自動(dòng)設(shè)備
思路:不同的設(shè)備先巴,如手機(jī)和電腦的顯示界面是不同的冒冬,對(duì)于不同設(shè)備的request简烤,應(yīng)該返回適合當(dāng)前設(shè)備的頁(yè)面
package com.imooc.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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DeviceAdapterFilter 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
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
//在請(qǐng)求的地址前加上辨識(shí)的字符横侦,重構(gòu)URI
/*
/index.html
PC: /desktop/index.html
MOBILE: /mobile/index.html
/test.html
PC: /desktop/test.html
MOBILE: /mobile/test.html
*/
String uri = req.getRequestURI();
System.out.println("URI:"+uri);
if(uri.startsWith("/desktop") || uri.startsWith("/mobile")) {
//本來就有標(biāo)識(shí)符枉侧,那么就直接傳遞
chain.doFilter(request, response);
}else {
String userAgent = req.getHeader("user-agent");
String targetURI = "";
if(userAgent.indexOf("android")!=-1 || userAgent.indexOf("iphone")!=-1) {
targetURI = "/mobile"+uri;
System.out.println("移動(dòng)端設(shè)備正在訪問榨馁,重新跳轉(zhuǎn)URI:" + targetURI);
res.sendRedirect(targetURI);
}else {
targetURI = "/desktop"+uri;
System.out.println("移動(dòng)端設(shè)備正在訪問,重新跳轉(zhuǎn)URI:" + targetURI);
res.sendRedirect(targetURI);
}
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>device-adapter</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>DeviceAdapterFilter</filter-name>
<filter-class>com.imooc.filter.DeviceAdapterFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>DeviceAdapterFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
</web-app>