过滤器的作用和使用
1.过滤器的作用:
Filter解决是多个Servlet种所存在的公有的代码冗余问题,引入Filter之后,把多个Servlet的冗余代码提取到Filter中,那么这样的用户的请求经过Filter,在访问后续的Servlet,既保护用户功能的完成,同时也解决了代码冗余的问题。
2.过滤器的使用:
Filter的开发步骤:
implements Filter;
package servlets;
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;
public class MyFilterFirst implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
/*
*
* doFilter的作用:把多个servlet中出现的相同代码书写在Filter中
* FilterChain 作用:决定 或影响请求的流程
* chain.doFilter(request,response);在执行代码上面,表示先执行Servlet程序。
*chain.doFilter(request,response); 在执行代码下面,表示先执行Filter程序。
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String servletPath = httpServletRequest.getServletPath(); //获取客户端所请求的脚本文件的文件路径
//不过滤处理登录页面、JS和CSS文件
if (!servletPath.equals("/login.html") && !servletPath.endsWith(".js") && !servletPath.endsWith(".css"))
{
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset = utf-8");
}else{
}
// 传递给下一过滤器
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
在 web.xml中配置Filter;
<filter>
<filter-name>MyFilterFirst</filter-name>
<filter-class>servlets.MyFilterFirst</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilterFirst</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
3.Filter中断用户请求
不要调用chain方法;
chain.doFilter(request,response);
中断请求后可以跳转到其他页面;
public class MyFilterSecond 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;
HttpSession session = req.getSession();
String flag = (String)session.getAttribute("flag");
if(!"y".equals(flag)){
HttpServletResponse resp =(HttpServletResponse) response;
resp.sendRedirect("../JSP/login.jsp");
}
else{
chain.doFilter(request,response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
4. 快捷键alt+shift+s +v可以显示sevrice方法