JavaWeb26(SMBMS项目搭建03)

登录功能优化

实现注销功能

  • 移除session
  • 返回登陆页面

LogoutServlet.java

package com.hao.servlet.user;

import com.hao.util.Constants;

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

public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //移除Session
        req.getSession().removeAttribute(Constants.USER_SESSION);
        //返回登陆页面
        resp.sendRedirect(req.getContextPath()+"/login.jsp");
    }
}

在xml中注册

<!--    注销-->
    <servlet>
        <servlet-name>LogoutServlet</servlet-name>
        <servlet-class>com.hao.servlet.user.LogoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LogoutServlet</servlet-name>
        <url-pattern>/jsp/logout.do</url-pattern>
    </servlet-mapping>

登录拦截优化

  • 编写过滤器
  • 注册过滤器

SysFilter.java

package com.hao.filter;

import com.hao.pojo.User;
import com.hao.util.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SysFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
        if (user==null){//说明对象已被移除
            response.sendRedirect("/SMBMS/error.jsp");
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }


    }

    public void destroy() {

    }
}

注册

<!--    登陆过滤器-->
    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.hao.filter.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/jsp/*</url-pattern>
    </filter-mapping>

访问测试

  • 正常登录
    在这里插入图片描述
  • 退出
    在这里插入图片描述
  • 直接访问网址
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值