一 : 过滤器Filter简述
过滤器是一个运行在服务端的程序,先于与之相关的servlet或JSP页面运行,实现对请求资源的过滤的功能,符合条件放行,不符合条件不放行,并且可以对目标资源访问前后进行逻辑处理.
二 : 书写一个Filter过滤器
① : 编写一个过滤器的类实现Filter接口
② : 实现接口中尚未实现的方法(着重实现doFilter方法)
public class QuickFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("qucikFilterRunning");
//放行请求
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
③ : 在web.xml中进行配置,主要是配置要对哪些资源进行过滤
<filter-name>QuickFilter</filter-name>
<filter-class>com.TianTianBaby.web.Filter.QuickFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>QuickFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
三 : Filter的API详解
( 1 )filter生命周期及其生命周期相关的方法
Filter接口有三个方法,都是与Filter的生命周期相关的方法
-
init
(FilterConfig filterConfig)
代表filter对象初始化方法,filter对象创建时执行 -
doFilter
(ServletRequest request, ServletResponse response, FilterChain chain)
代表filter执行过滤的核心方法,如果某资源在已经被配置到这个filter进行过滤的话,那么每次访问这个资源都会执行doFilter方法 -
destory()
代表是filter销毁方法,当filter对象销毁时执行该方法
Filter对象的生命周期 :
Filter何时创建 : 服务器启动时就创建该filter对象
Filter何时销毁 : 服务器关闭filter销毁
( 2 )FilterAPI
-
init
(FilterConfig)
config代表Filter对象的配置信息的对象,内部封装是该filter的配置信息.
public class QuickFilter2 implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//获得web.xml 中filter的名称
String name = filterConfig.getFilterName();
System.out.println(name);
//当前filter初始化参数
String parm = filterConfig.getInitParameter("aaa");
System.out.println(parm);
//获得servletContext
filterConfig.getServletContext();
}
-
destory
()
filter对象销毁时执行 -
doFilter(ServletRequest,ServletResponse,FilterChain)
FilterChain
:过滤器链对象,通过该对象的doFilter方法可以放行该请求
ServletRequest/ServletResponse
:每次在执行doFilter方法时 web容器负责创建一个request和一个response对象作为doFilter的参数传递进来。该request个该response就是在访问目标资源的service方法时的request和response。
四 : 配置
url-pattern配置时
- 完全匹配 /sertvle1
- 目录匹配 /aaa/bbb/* ----最多的
/user/:访问前台的资源进入此过滤器
/admin/:访问后台的资源时执行此过滤器 - 扩展名匹配 *.abc *.jsp
url-pattern可以使用servlet-name替代,此时filter 对配置的servlet起作用
dispatcher:访问的方式(了解)
REQUEST:默认值,代表直接访问某个资源时执行filter
FORWARD:转发时才执行filter
INCLUDE: 包含资源时执行filter
ERROR:发生错误时 进行跳转是执行filter
五 : 自动登录demo
- WEB-Servlet
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
//获取数据
String username = request.getParameter("username");
String password = request.getParameter("password");
UserService service = new UserService();
User user = null;
try {
user = service.login(username,password);
} catch (SQLException e) {
e.printStackTrace();
}
if (user != null) {
//登录成功
//判断用户是否勾选
String autoLogin = request.getParameter("autoLogin");
if (autoLogin != null) {
//编码
String username_code = java.net.URLEncoder.encode(username, "UTF-8");
Cookie cookie_name = new Cookie("cookie_name", username_code);
Cookie cookie_pass = new Cookie("cookie_pass", password);
cookie_name.setPath(request.getContextPath());
cookie_pass.setPath(request.getContextPath());
cookie_name.setMaxAge(60*60);
response.addCookie(cookie_name);
response.addCookie(cookie_pass);
}
//将登录用户user对象存到session中
session.setAttribute("user", user);
response.sendRedirect(request.getContextPath());
}else {
session.setAttribute("loginInfo", "用户名密码错误");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
- WEB-Filter
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
//获得用户Cookie中用户名和密码进行登录操作
//获得cookie
HttpServletRequest res = (HttpServletRequest)request;
HttpServletResponse rep = (HttpServletResponse)response;
String cookie_username = null;
String cookie_pass = null;
Cookie[] cookies = res.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("cookie_name")) {
cookie_username = cookie.getValue();
}
if (cookie.getName().equals("cookie_pass")) {
cookie_pass = cookie.getValue();
}
}
}
if (cookie_username != null && cookie_pass != null) {
//登录
UserService service = new UserService();
User user = null;
try {
user = service.login(cookie_username,cookie_pass);
//将登录用户user对象存到session中
res.getSession().setAttribute("user", user);
} catch (SQLException e) {
e.printStackTrace();
}
}
System.out.println("自动登录");
//放行
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
六 : 全局解决中文乱码demo
用此filter解决所有servlet中文乱码问题
- WEB-Filter
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
//request.setCharacterEncoding("UTF-8");
//在传递request之前对request的getParameter方法进行增强
/*
* 装饰者模式(包装)
*
* 1、增强类与被增强的类要实现统一接口
* 2、在增强类中传入被增强的类
* 3、需要增强的方法重写 不需要增强的方法调用被增强对象的
*
*/
//被增强的对象
HttpServletRequest req = (HttpServletRequest) request;
//增强对象
EnhanceRequest enhanceRequest = new EnhanceRequest(req);
chain.doFilter(enhanceRequest, response);
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
class EnhanceRequest extends HttpServletRequestWrapper{
private HttpServletRequest request;
public EnhanceRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
//对getParaameter增强
@Override
public String getParameter(String name) {
String parameter = request.getParameter(name);//乱码
try {
parameter = new String(parameter.getBytes("iso8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return parameter;
}
}
网友评论