怎么使用filter实现未登录用户自动跳转到登录页面
展开全部
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
if(req.getSession().getAttribute("user")==null){
req.setAttribute("error", "请你先登录");
//非法请求才会进到这里面,在这里保存请求的url地址,在成功登录后再进行跳转
req.getSession().setAttribute("goUrl", req.getRequestURL()+"?"+ req.getQueryString());
request.getRequestDispatcher("/ulogin.jsp").forward(request, response);
}
else{
chain.doFilter(request, response);
}
}
上面的代码是过滤器中的代码
下面的是servlet中的代码
if(request.getSession().getAttribute("goUrl")!=null){
String url = (String)request.getSession().getAttribute("goUrl");
response.sendRedirect(url);
}
else{
response.sendRedirect("/webshopping/index.jsp");
}
HttpServletRequest req = (HttpServletRequest)request;
if(req.getSession().getAttribute("user")==null){
req.setAttribute("error", "请你先登录");
//非法请求才会进到这里面,在这里保存请求的url地址,在成功登录后再进行跳转
req.getSession().setAttribute("goUrl", req.getRequestURL()+"?"+ req.getQueryString());
request.getRequestDispatcher("/ulogin.jsp").forward(request, response);
}
else{
chain.doFilter(request, response);
}
}
上面的代码是过滤器中的代码
下面的是servlet中的代码
if(request.getSession().getAttribute("goUrl")!=null){
String url = (String)request.getSession().getAttribute("goUrl");
response.sendRedirect(url);
}
else{
response.sendRedirect("/webshopping/index.jsp");
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询