SpringMVC:拦截器小练习和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">

<!--    声明,注册springmvc的核心对象DispatcherServlet-->
    <servlet>
        <servlet-name>myweb</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!--        自定义springmvc读取的配置文件的位置-->
        <init-param>
            <!--springmvc的配置文件属性-->
            <param-name>contextConfigLocation</param-name>
            <!-- 指定自定义文件的位置-->
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>

<!--        在tomcat启动后,创建Servlet对象
               load-on-startup:表示tomcat启动后创建对象的顺序,它的值是正数,数值越小 tomacat创建对象越早
-->
        <load-on-startup>1</load-on-startup>

    </servlet>

<!--    所有的*..do请求交给myweb中央处理器处理-->
    <servlet-mapping>
        <servlet-name>myweb</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <!--注册声明过滤器,解决post请求乱码问题-->
    <filter>
        <filter-name>characterEncodingFilter</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>
        <!--强制请求对象(HttpServletRequest)使用encoding编码的值-->
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <!--强制应答对象(HttpServletResponse)使用encoding编码的值-->
        <init-param>
            <param-name>forceReponsetEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <!--
           /*:表示强制所有的请求先通过过滤器处理
         -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

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

<!-- 用了注解需要注解扫描器:声明组件扫描器:包扫描-->
    <context:component-scan base-package="com.bjpowernode.controller"/>

<!--    声明springmvc框架中的视图解析器,帮助开发人员设置视图文件的路径-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀:视图文件的路径-->
        <property name="prefix" value="/WEB-INF/view/"/>
        <!-- 后缀:视图文件的扩展名-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--声明拦截器:拦截器可以有0个或多个
       在框架中保存多个拦截器是ArrayList集合
       按照声明的先后顺序先放入到ArrayList集合中
    -->
    <mvc:interceptors>
        <!--声明第一个拦截器-->
        <mvc:interceptor>
            <!--
               指定拦截器的请求uri地址
               path:就是uri地址,可以通配符 ** 可以表示任意字符、文件或多级目录和目录中的文件
               /user/**  :以user开头的请求都会诶拦截
               /** :所有请求都会被拦截
            -->
            <mvc:mapping path="/**"/>
            <!--声明拦截器对象-->
            <bean class="com.bjpowernode.handler.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

</beans>

拦截器:MyInterceptor:

package com.bjpowernode.handler;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

//拦截器类:拦截用户的请求
public class MyInterceptor implements HandlerInterceptor {


    /**
     *preHandle预处理方法:
     *   重要:是整个项目的入口,门户。当preHandle返回true 请求可以被处理
     *       preHandle返回false 请求到此方法就被截止
     * 参数:
     *   Object hander:被拦截的对象
     *   返回值boolean:
     *   true:表示请求验证通过,可以执行处理器的方法
     *     拦截器的MyInterceptor的preHandle()
     *     =====打印MyController中的do.some()方法===
     *     拦截器的MyInterceptor的postHandle()
     *     拦截器的MyInterceptor的afterCompletion()
     *   false:请求没有通过拦截器验证,请求达到拦截器就截止了。请求没有被处理
     *     拦截器的MyInterceptor的preHandle()
     *
     * 特点:
     * 1.该方法是在控制器方法(MyController的doSome方法)之前先执行的,用户的请求先到达此方法。
     * 2.在这个方法可以获取请求信息,验证请求是否符合要求。
     *   可以验证用户是否登录,验证用户是否有权限访问某个链接地址(url)。
     *   如果验证失败,可以截断请求,请求不能被处理。
     *   如果验证成功,可以放行请求,此时控制器方法才能执行。
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("11111拦截器的MyInterceptor的preHandle()");

        //计算的业务逻辑,根据计算结果,返回true或者false

        String loginName="";
        //从session中获取name的值
        Object attr = request.getSession().getAttribute("name");
        if (attr!=null){
           loginName=(String)attr;
        }
        if (!"zs".equals(loginName)){
            //不能访问系统,给用户提示
            request.getRequestDispatcher("/tips.jsp").forward(request,response);
            return false;
        }
        return true;
    }
}

控制器:MyController:

package com.bjpowernode.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MyController {

    @RequestMapping(value = "/some.do")
    public ModelAndView doForword(String name,Integer age) {
        System.out.println("=====打印MyController中的do.some()方法===");
        //处理some.do请求了,相当于service调用处理完成了
        ModelAndView mv=new ModelAndView();

        mv.addObject("myname",name);
        mv.addObject("myage",age);

        mv.setViewName("show");
        return mv;
    }
}

 

login.jsp:

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/6/25
  Time: 15:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
   模拟登录,zs登录系统
   <%
       session.setAttribute("name","zs");
   %>

</body>
</html>

logout.jsp:

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/6/25
  Time: 15:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
   退出系统,从session中删除数据
   <%
       session.removeAttribute("name");
   %>

</body>
</html>

tips.jsp:

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/6/25
  Time: 8:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
   tips.jsp 请求被拦截,非zs不能访问系统
</body>
</html>

show.jsp:

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/6/7
  Time: 19:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
 <h3>/WEB-INF/view/show.jsp.从request作用域获取数据</h3>
  <h3>myname数据:${myname}</h3>
  <h3>myage数据:${myage}</h3>
</body>
</html>

index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/6/7
  Time: 17:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>Title</title>
    <base href="<%=basePath%>">
</head>
<body>
  <p>拦截器</p>
    <form action="some.do" method="post">
      姓名:<input type="text" name="name"><br>
      年龄:<input type="text" name="age"><br>
    <input type="submit" value="提交请求">
    </form>


</body>
</html>

 

想要提交数据通过首先需要访问login.jsp,将zs的数据存入到session中:

 

从新发出提交请求数据:

 

 把zs从session中消除,之后才能不能发起请求:访问logout.jsp:

在次发起请求:

 

 

 

Sp[ringMVC:执行流程分析:

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喵俺第一专栏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值