拦截器实验步骤

拦截器实验步骤

开发环境:
IDEA

文章目录

      • 拦截器实验步骤
        • 1. 创建工程文件,导入web支持
        • 2.在web.xml当中导入spring以及servlet
        • 4. 编写applicationContext.xml文件
        • 5. 构造目录结构
        • 6. 创建拦截器的包,在该包下新建拦截器:MyIntercepter
        • 7. 测试代码
        • 8. 对设置的拦截器进行注册
      • 实例:登录验证
        • 1. 创建工程文件,导入web支持并写入相关配置
      • 2.编写applicationContext.xml文件
        • 3. 在原来的包下面创建LoginInterceptor.java拦截器
        • 4. 注册拦截器
        • 5. 编写对应的controller
        • 6. 前端界面

1. 创建工程文件,导入web支持

2.在web.xml当中导入spring以及servlet

 <servlet>
        <servlet-name>springmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>

        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:applicationContext.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>


    <filter>
        <filter-name>characterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>characterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

4. 编写applicationContext.xml文件


<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">

       <context:component-scan base-package="com.zengwei.controller"/>
    
       <mvc:default-servlet-handler/>
    
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                         <property name="failOnEmptyBeans" value="false"/>
                    bean>
                property>
            bean>
        mvc:message-converters>
    mvc:annotation-driven>
    
   
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
          <property name="prefix" value="/WEB-INF/jsp/"/>
          <property name="suffix" value=".jsp"/>
      bean>
beans>

5. 构造目录结构

创建包:com.zengwei.controller

至此基本的项目架构已经搭好,可启动tomcat进行测试,注意在项目当中加入lib目录同时导入依赖文件

6. 创建拦截器的包,在该包下新建拦截器:MyIntercepter

package com.zengwei.intercepter;

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

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

public class MyIntercepter implements HandlerInterceptor {

    //此函数返回值为true 则表示执行下一个拦截器,放行
    //若为false则表示不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

7. 测试代码

package com.zengwei.intercepter;

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

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

public class MyIntercepter implements HandlerInterceptor {

    //此函数返回值为true 则表示执行下一个拦截器,放行
    //若为false则表示不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("==========>处理前");
        return true;
    }
    //后面两个负责产生拦截日志
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("==========>处理后");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("==========》清理");
    }
}

8. 对设置的拦截器进行注册

//在applicationContext.xml文件当中加入

<mvc:interceptors>
    <mvc:interceptor>

        <mvc:mapping path="/**"/>
        <bean class="com.zengwei.intercepter.MyIntercepter"/>
    mvc:interceptor>
mvc:interceptors>
beans>

实例:登录验证

1. 创建工程文件,导入web支持并写入相关配置

 
        springmvc
        org.springframework.web.servlet.DispatcherServlet

        
            contextConfigLocation
            classpath:applicationContext.xml
        
        1
    
    
        springmvc
        /
    


    
        characterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
    
    
        characterEncodingFilter
        /*
    

2.编写applicationContext.xml文件


<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">

       <context:component-scan base-package="com.zengwei.controller"/>

       <mvc:default-servlet-handler/>
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                         <property name="failOnEmptyBeans" value="false"/>
                    bean>
                property>
            bean>
        mvc:message-converters>
    mvc:annotation-driven>

      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
          <property name="prefix" value="/WEB-INF/jsp/"/>
          <property name="suffix" value=".jsp"/>
      bean>

3. 在原来的包下面创建LoginInterceptor.java拦截器

package com.zengwei.intercepter;

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

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

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();

        //放行的判断,1.有session但没有东西,2. 有session有东西
       if(request.getRequestURI().contains("login"))
       {
           return true;
       }
        if(session.getAttribute("loginuser")!=null)
        {
            return true;
        }
       //判断什么情况下没有登录,1.没有session肯定没有登录,

        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
        return false;
    }
}

4. 注册拦截器

在applicationContext当中加入


<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/User/**"/>
        <bean class="com.zengwei.intercepter.LoginInterceptor"/>
    mvc:interceptor>
mvc:interceptors>

5. 编写对应的controller

//LoginController
package com.zengwei.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/User")
public class LoginController {
    @RequestMapping("/login")
    public String Login(HttpSession session, String username, String passwd, Model model)
    {
        //正常登录后需要把用户信息存入session当中方便以后或者用户访问期间调入信息
       session.setAttribute("loginuser",username);
       model.addAttribute("name",username);
        return "main";
    }
    @RequestMapping("/main")
    public String Main()
    {
        return "main";
    }
    @RequestMapping("/tologin")
    public String toLogin()
    {
        return "login";
    }
    @RequestMapping("/goout")
    public String goout(HttpSession session)
    {
        session.removeAttribute("loginuser");
        return "main";
    }
}

6. 前端界面

//index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

  
    $Title$
  
  
  

登录

首页

//main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    首页


首页

${name}

注销

//login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    登录页面


  
用户名: 密码:

你可能感兴趣的:(SSM框架)