拦截器

基于springMVC的拦截器

springMVC的拦截器是一个AOP的具体应用
该拦截器只能再springMVC中使用

基本的要求:不能拦截首页,表单提交,静态资源

登录判断验证(拦截器的一个具体实现)

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>DispactcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispactcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>EncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>EncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

spring-mvc.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!---->
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    <!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
    <context:component-scan base-package="com.Google.controller"/>
    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>
    <!--配置拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <!--要使用的拦截器-->
            <bean class="com.Google.config.logInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

controller的编写

package com.Google.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Controller
public class testController{
    /*编写一个登录拦截,当没有登入不能进首页,登录了以后才能进,再加一个注销功能*/
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "log";
    }
    @RequestMapping("/Login")
    public String login(@RequestParam("username") String  name, HttpSession session, Model model){
        System.out.printf("name:"+name);
        /*保存session,用于判断是否登录*/
        session.setAttribute("loginINFO",name);
        System.out.println(session.getAttribute("loginINFO"));
        model.addAttribute("name",name);
        return "main";
    }
    @RequestMapping("/toMain")
    public String toMain(){
        return "main";
    }
    @RequestMapping("/logOut")
    public String logOut(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("loginINFO");
        return "main";
    }

}

拦截器的编写(实现了HandlerInterceptor接口的类就叫拦截器)主要编写preHandle方法,这是拦截器的入口

package com.Google.config;

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

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

public class logInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*没有登录不能进入首页*/
        if(request.getRequestURI().contains("Login")){
            return true;
        }
        if(request.getSession().getAttribute("loginINFO")!=null){
            return true;
        }
        //用户没有登录跳转到登录页面
        request.getRequestDispatcher("/WEB-INF/jsp/log.jsp").forward(request,response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

前端的编写

起始页(index.jsp)

<%--
  Created by IntelliJ IDEA.
  User: make
  Date: 2022/2/14
  Time: 12:44
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <h1>
    <a href="${pageContext.request.contextPath}/toLogin">登录</a>
    <a href="${pageContext.request.contextPath}/toMain">首页</a>
  </h1>
  </body>
</html>

登录页面(log.jsp)在WEB-INF/jsp包下

<%--
  Created by IntelliJ IDEA.
  User: make
  Date: 2022/2/14
  Time: 13:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/Login" method="post">
    用户名:<input  type="text" name="username"/>
    密码:<input  type="password" name="password"/>
    <input type="submit" value="登录">
</form>
</body>
</html>

首页页面(log.jsp)在WEB-INF/jsp包下

<%--
  Created by IntelliJ IDEA.
  User: make
  Date: 2022/2/14
  Time: 13:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<p>这里是首页</p>
<h1>${name}</h1>
<a href="${pageContext.request.contextPath}/logOut">注销</a>
</body>
</html>

配置好Tomcat,测试即可

posted @ 2022-02-14 14:11  小罗要有出息  阅读(87)  评论(0编辑  收藏  举报