23-注销功能及注销后的首页保护

23-注销功能及注销后的首页保护

概述

本篇博客主要讲注销功能的实现和注销之后用户无法通过url直接访问主页

实践

LogoutServlet.java


package com.kuang.servlet;

import com.kuang.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 功能描述
 *
 * @since 2022-09-06
 */
public class LogoutServlet extends HttpServlet {
    private static final long serialVersionUID = -128515702075179251L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().removeAttribute(Constants.USER_SESSION);
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

.java


package com.kuang.filter;

import com.kuang.pojo.User;
import com.kuang.utils.Constants;

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;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 功能描述
 *
 * @since 2022-09-07
 */
public class SysFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        if (user == null) {
            resp.sendRedirect(req.getContextPath() + "/error.jsp");
        } else {
            filterChain.doFilter(req, resp);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}

web.xml添加注销servlet和过滤器

    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.kuang.filter.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/jsp/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>logout</servlet-name>
        <servlet-class>com.kuang.servlet.LogoutServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>logout</servlet-name>
        <url-pattern>/jsp/logout.do</url-pattern>
    </servlet-mapping>
posted @ 2022-09-07 09:19  Oh,mydream!  阅读(26)  评论(0编辑  收藏  举报