需求:
当用户绕过登陆直接定位网站资源时,
比如用户模块,用户必须先登录(session中是否有user),然后role是1
http://localhost:7979/myfilter_charset_minganmessage/user/Index.jsp
比如管理员模块:用户必须先登录(session中是否有user),然后role是2
http://localhost:7979/myfilter_charset_minganmessage/admin/Index.jsp
那么我们需要进行访问拦截:使用过滤器技术实现。
过滤器知识点:
1.定义过滤器:一定要实现javax.servlet.Filter接口
2.同时实现接口中的方法:最重要是doFilter方法
3.如果有多个多滤器,希望他们连成一串工作,那么一定要调用
//放行
chain.doFilter(request, response);
4.过滤器定义之后一定要在web.xml中注册,按照注册先后顺序执行过滤器
5.过滤器很强大,请求的时候会依次执行1,2,3,返回响应之后也会依次执行3,2,1
6.访问控制测试的url:
http://localhost:7979/myfilter_charset_minganmessage/login.jsp?tiezi="赖旭红喜欢刘春松"
http://localhost:7979/myfilter_charset_minganmessage/user/index.jsp
http://localhost:7979/myfilter_charset_minganmessage/admin/index.jsp
访问权限过滤器:
/**
* 进行访问资源控制的方法
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("-----come-------accessFilter");
HttpServletRequest httpRequest=null;
if(request instanceof HttpServletRequest)
{
httpRequest=(HttpServletRequest)request;
}
// 拿到用户的请求路径;
String uri=httpRequest.getRequestURI();
//如果用户访问管理员模块的资源
if(uri.contains("/admin/"))
{
HttpSession session=httpRequest.getSession();
User user=(User)session.getAttribute("user");
if(user!=null && user.getRole()==2)
{
//放行
chain.doFilter(request, response);
}
else {
((HttpServletResponse)response).sendRedirect(httpRequest.getContextPath()+"/login.jsp");
}
return;
}
//如果用户访问普通用户模块的资源
else if(uri.contains("/user/"))
{
HttpSession session=httpRequest.getSession();
User user=(User)session.getAttribute("user");
if(user!=null && user.getRole()==1)
{
//放行
chain.doFilter(request, response);
}
else {
((HttpServletResponse)response).sendRedirect(httpRequest.getContextPath()+"/login.jsp");
}
return;
}
//就少了这行代码
else { // /login.jsp
//放行
chain.doFilter(request, response);
}
System.out.println("-----leave-------accessFilter");
}
字符集过滤器:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("------come--CharSetFilter-------");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=UTF-8");
//chain是链的意思,
chain.doFilter(request, response);
System.out.println("------leave--CharSetFilter-------");
}
敏感字符过滤器:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("-----------welcome StringFilter---------");
String content=request.getParameter("tiezi");
if(content!=null)
{
for(String s:mingan_message)
{
System.out.println(s);
content=content.replace(s, "*");//赖旭红*刘春松
}
System.out.println("content:"+content);
}
//过滤完之后重新放入request域中,下个servlet可以拿到
request.setAttribute("tiezi", content);
chain.doFilter(request, response);//该干什么就干什么
System.out.println("-----------leave StringFilter---------");
}