Javaweb过滤器——登录过滤

一、实现功能

将登录成功之后的界面过滤,在没有用户登录的条件下,无法直接访问网站的登录成功界面
Javaweb过滤器——登录过滤_第1张图片


1、登录界面

一个简单的表单

"loginservlet" method="post"> 用户名:type="text" name="username"> 密码:type="password" name="password"> type="submit">

2、servlet判断用户名密码,是否登录成功

@WebServlet("/loginservlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //设置编码
        request.setCharacterEncoding("utf-8");

        //读取表单中的用户名密码
        String name = request.getParameter("username");
        String password = request.getParameter("password");

        // 若用户名密码符合条件,跳转到成功页面,否则跳转到失败页面,将登录的用户名保存在usernname中
        if ("张三".equals(name) && "123".equals(password)) {
            HttpSession session = request.getSession();
            session.setAttribute("username", name);
            response.sendRedirect("success.jsp");//此时调用过滤器
        } else {
            response.sendRedirect("fail.jsp");
        }
    }
}


3、Filter控制是否能访问登录成功界面

//设置要过滤的页面
@WebFilter(value = {"/success.jsp"})
public class LoginFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        HttpSession session = httpServletRequest.getSession();

        //如果username不为空,说明用户已经登录,过滤器放行。否则跳转到登录页面
        if (session.getAttribute("username") != null) {
            chain.doFilter(httpServletRequest, httpServletResponse);
        } else {
            httpServletResponse.sendRedirect("login.jsp");
        }
    }
}

你可能感兴趣的:(JavaWeb)