Filter的使用

 

 要自己创建一个URL过滤的Filter,必须继承HttpServlet和实现Filter接口。

 HttpServlet是javax.servlet.http.HttpServlet的类;

 Filter是javax.servlet.Filter的接口;

 public class RoleFilter extends HttpServlet implements Filter {

private String msg = "";

 

public boolean test(int node) {

// TODO Auto-generated method stub

return false;

}

 

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException {

// TODO Auto-generated method stub

HttpServletResponse httpServletResponse = (HttpServletResponse) response;

HttpServletRequest httpServletRequest = (HttpServletRequest) request;

String url = httpServletRequest.getRequestURI();

System.out.println(url);

if (url.equals("/roleDemo/")) {

chain.doFilter(httpServletRequest, httpServletResponse);

} else if (url.endsWith(".jsp")) {

httpServletRequest.setAttribute("msg", msg);

chain.doFilter(httpServletRequest, httpServletResponse);

} else {

httpServletResponse.setCharacterEncoding("GB2312");

httpServletRequest.setCharacterEncoding("GB2312");

msg = "你没有登录!";

httpServletResponse.sendRedirect(httpServletRequest

.getContextPath()

+ "/error.jsp");

}

}

 

public void init(FilterConfig filterConfig) throws ServletException {

// TODO Auto-generated method stub

 

}

 

你可能感兴趣的:(职场,filter,休闲)