【Springmvc拦截器】实现登录

用户要先登录,才能使用功能。现实中的例子,如学校的教务系统,只公开展示登录页面,只有登录成功,才能浏览其他信息。

拦截器可以用来判断该用户是否登录,如果不登录,就进行拦截。

代码部分

项目路径

1、login.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
    <% pageContext.setAttribute("page",request.getContextPath());%>
</head>
<body>
    <form action="${page}/users/login" method="post">
        username:<input type="text" name="username"/><br>
        password:<input type="password" name="password"/><br>
        <input type="submit" value="登录">

    </form>
</body>
</html>

2、success.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>SUCCESS</title>
    <% pageContext.setAttribute("page",request.getContextPath());%>
    <!--绝对url指向指定栈点-->
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
${key}
</body>
</html>

3、MyTwoInter.java

package com.qingruan.servlet;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class MyTwoInter implements HandlerInterceptor {

    //目标方法运行之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyTwoInter...preHandle()");
        //表示继续执行后续的操作
        return true;
    }

    //目标方法运行之后运行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyTwoInter...postHandle()");
    }

    //在整个请求完成之后的操作
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyTwoInter...afterCompletion()");
    }
}

4、UsersController.java

package com.qingruan.servlet;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Contro

猜你喜欢

转载自blog.csdn.net/xjj1128/article/details/128208158