馒头bun

利用spring框架提供的HandlerInterceptorAdapter,实现自定义拦截器

package com.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
 * @description 利用spring框架提供的HandlerInterceptorAdapter,实现自定义拦截器
 */
public class UserLoginInterceptorBySpring extends HandlerInterceptorAdapter {
    // 在业务处理器处理请求之前被调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //把登录的用户名放到Session会话里,用户登录时通过获取会话username对象判断用户之前有没有登录系统
        String username = (String) request.getSession().getAttribute("username");
        if (null == username) {
            // 跳转到登录页面
            request.getRequestDispatcher("/login").forward(request, response);
            return false;
        } else {
            return true;
        }
    }

    // 在业务处理器处理请求完成之后,生成视图之前执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");

    }

    // 在DispatcherServlet完全处理完请求之后被调用,可用于清理资源
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}

**********************
xml配置文件

    <mvc:interceptors>
        <mvc:interceptor>
            <!-- 定义拦截的路由,com.controller包下的所有Controller -->
            <mvc:mapping path="/**" />
            <mvc:exclude-mapping path="/login" />
            <mvc:exclude-mapping path="/reg" />
            <mvc:exclude-mapping path="/register" />
            <!-- 拦截方法 -->
            <bean class="com.utils.UserLoginInterceptorBySpring"/>
        </mvc:interceptor>
    </mvc:interceptors>


************************
//登录时的控制器
package com.controller;

import com.dao.Sys_userDAO;
import com.model.Sys_user;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Create with IntelliJ iDEA.
 *
 * @Auther:哈
 * @Date:2020/9/23 9:30
 * 接收前端的用户名和密码,并进行判断,然后把用户名放到Session会话里
 */
@Controller
public class Login_checkController {

    @RequestMapping("/login")
    public String login(String userName, String nuse, HttpServletRequest req){
        String username = userName;//接收用户名
        String password = nuse;//接收密码
        Sys_user result = dao.loginCheck(username,password);//调用方法,校验用户名密码是否正确
       if (result!=null){
           req.getSession().setAttribute("username",username);//把用户名放到Session会话作用域中
            return "main";
       }else {
           return "redirect:/index.jsp";
       }
    }
}

posted on 2020-10-31 13:53  馒头bun  阅读(183)  评论(0编辑  收藏  举报

导航