我是靠谱客的博主 鲤鱼小蚂蚁,最近开发中收集的这篇文章主要介绍详细:springmvc登录拦截器实现,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

一言不合上代码

第一步:web.xml配置

 <filter>
        <description>登录过滤器</description>
        <filter-name>loginFilter</filter-name>
        <filter-class>com.imu.tools.LoginFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>loginFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

注:com.imu.tools.LoginFilter 必须在项目中创建该类否则会爆红 LoginFilter 为你的拦截器实现类 将会实现Filter 接口

第二步:创建LoginFilter类并实现

package com.imu.tools;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;


public class LoginFilter implements Filter {

    public static List<String> pattenURL = new ArrayList<String>();

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession();
        // 登陆url
        String loginUrl = httpRequest.getContextPath() + "/login";
        String url = httpRequest.getRequestURI().toString();

        /*
         * 注:在pattenURL中的全部不拦截
         * url.indexOf(urlStr) > -1  表示urlStr在url中出现过,出现就不拦截
         * */
        for (String urlStr : pattenURL) {
            if(url.indexOf(urlStr) > -1){
                chain.doFilter(request, response);
                return;
            }
        }

        /*
         * 超时处理,ajax请求超时设置超时状态,页面请求超时则返回提示并重定向
         * session.getAttribute("")是获取到登录人的session信息
         * */
        if (session.getAttribute("sess_user") == null) {
            // 判断是否为ajax请求
            if (httpRequest.getHeader("x-requested-with") != null
                    && httpRequest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
                httpResponse.addHeader("sessionstatus", "timeOut"); //返回超时标识
                httpResponse.addHeader("loginPath", loginUrl);// 返回url
                chain.doFilter(request, response);// 不可少,否则请求会出错
            } else {
                //alert('会话过期,请重新登录');
                String str = "<script language='javascript'>"
                        + "window.top.location.href='"
                        + loginUrl
                        + "';</script>";
                response.setContentType("text/html;charset=UTF-8");// 解决中文乱码
                try {
                    PrintWriter writer = response.getWriter();
                    writer.write(str);
                    writer.flush();
                    writer.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            chain.doFilter(request, response);
        }
    }

    /*
     * 在pattenURL中的全部不拦截,所以上面会使用:path.indexOf(urlStr) > -1
     * */
    public void init(FilterConfig arg0) throws ServletException {
        pattenURL.add("/login");//登录jsp
        pattenURL.add("/dolog");//处理登录逻辑
        pattenURL.add("/reg");//注册方法
        pattenURL.add("/index");//首页
        pattenURL.add("css");//css
        pattenURL.add("image");//image
        pattenURL.add("js");//js
        pattenURL.add("fonts");//fonts
        pattenURL.add("png");
    }

}

注意:在书写过程中要改的部分

1.判断session处改成你的session保存的名

2.请勿遗忘

 pattenURL.add("/dolog");//处理登录逻辑     
此处非常容易遗忘,如果忘写了,他会拦截你表单处理提交的controller函数。惯性思维只是将某些页面做不拦截项

3.登陆url

第三步:登录 LoginController

import com.imu.entity.User;
import com.imu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
public class LoginController {
    @Autowired
    UserService userService;
    /**
     * 实现登录验证
     *
     */
    @RequestMapping(value = "/dolog",method = RequestMethod.POST)
    public String doLogin(HttpSession session, HttpServletRequest request, HttpServletResponse response, ModelMap modelMap){
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        User user = userService.doLogin(email,password);
        response.setCharacterEncoding("utf-8");

        if(user == null)
        {
            System.out.println("***************session*********** null");
            try {
                PrintWriter out = response.getWriter();
                out.print("<script>alert('email or password is error...'); window.location='/login' </script>");
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "login";
        }
        else
        {
           session.setAttribute("sess_user",user);
           System.out.println("***************session********  "+ user.getuName());
            return "redirect:/index";
        }

    }

}
到此结束!

最后

以上就是鲤鱼小蚂蚁为你收集整理的详细:springmvc登录拦截器实现的全部内容,希望文章能够帮你解决详细:springmvc登录拦截器实现所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(31)

评论列表共有 0 条评论

立即
投稿
返回
顶部