老师 为什么我写的代码没有拦截js和图标里面的内容啊

来源:1-2 Interceptor使用技巧

星辰很精彩

2023-02-11 00:23:06

视频中的:

https://img.mukewang.com/climg/63e66d0009154bc815460837.jpg

我的结果:

https://img.mukewang.com/climg/63e66de70913cf0819041022.jpg

https://img.mukewang.com/climg/63e66e3509def79119201030.jpg

代码如下:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.imooc</groupId>
    <artifactId>restful</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>


    <repositories>
        <repository>
            <id>aliyun</id>
            <name>aliyun</name>
            <url>https://maven.aliyun.com/repository/public</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.14.2</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.14.2</version>
        </dependency>

        <!--添加jackson注解形式-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.14.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

</project>

拦截器代码:

package com.imooc.restful.interceptor;


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

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

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //请求产生后 还没有进入Controller之前 执行 true就继续执行 false 不继续执行
        System.out.println(request.getRequestURL() + "-URL准备执行");
        //System.out.println(request.getRequestURI() + "-URI准备执行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println(request.getRequestURL() + "-目标处理成功");
        //controller方法 返回以后 还没有生成响应以前
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println(request.getRequestURL() + "-响应内容已产生");
        //产生响应文本以后 自动执行

    }
}

restful代码:

package com.imooc.restful.controller;

import com.imooc.restful.entity.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


//设置单个跨域请求
//@CrossOrigin(origins = {"http://localhost:8080", "http://www.imooc.com" })
//@CrossOrigin(origins = "*",maxAge = 3600)//每一个网址都能访问  maxAge表示将预检结果保存多少秒 之后再执行预检请求
@RestController//默认返回的是 当前方法的数据
@RequestMapping("/restful")
public class RestfulController {

    @GetMapping("/request")
    //@ResponseBody
    public String doGetRestful() {
        return "{\"message\":\"返回结果查询\"}";
    }

    @PostMapping("/request/{rid}")
    //@ResponseBody
    public String doPostRestful(@PathVariable("rid") Integer requestId, Person person) {
        System.out.println("姓名:" + person.getName() + ":" + "年龄:" + person.getAge());
        //会自动将rid的数据注入到路径中
        return "{\"message\":\"数据新建成功\",\"id\":" + requestId + "}";
    }

    @PutMapping("/request")
    //@ResponseBody
    public String doPutRestful(Person person) {
        System.out.println("姓名:" + person.getName() + ":" + "年龄:" + person.getAge());
        return "{\"message\":\"数据更新成功\"}";
    }

    @DeleteMapping("/request")
    //@ResponseBody
    public String doDeleteRestful() {
        return "{\"message\":\"数据删除成功\"}";
    }

    //加入json数据包之后会自动生成json序列化
    @GetMapping("/person")
    public Person findByPersonId(Integer id) {
        Person person = new Person();
        if (id == 1) {
            person.setName("张三");
            person.setAge(20);
        } else if (id == 2) {
            person.setName("李四");
            person.setAge(23);
        }
        return person;
    }

    @GetMapping("/persons")
    public List<Person> findPersons() {
        List<Person> people = new ArrayList<Person>();
        Person p1 = new Person();
        p1.setName("王五");
        p1.setAge(26);
        p1.setCreateTime(new Date());
        people.add(p1);
        Person p2 = new Person();
        p2.setName("李四");
        p2.setAge(27);
        p2.setCreateTime(new Date());
        people.add(p2);
        return people;
    }
}

person代码:

package com.imooc.restful.entity;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.util.Date;

public class Person {
    private String name;
    private Integer age;
    //json时间处理方式
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date createTime;

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

client.html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Restful实验室</title>
    <script src="jquery-3.3.1.min.js"></script>
    <script>
        $(function () {
            $("#btnGet").click(function () {
                $.ajax({
                    url: "/restful/request",
                    type: "get",
                    dataType: "json",
                    success: function (json) {
                        $("#message").text(json.message);
                    }
                });
            })
        });

        $(function () {
            $("#btnPost").click(function () {
                $.ajax({
                    url: "/restful/request/100",
                    type: "post",
                    data: "name=lily&age=23",
                    dataType: "json",
                    success: function (json) {
                        $("#message").text(json.message + ":" + json.id);
                    }
                })

            });
        });

        $(function () {
            $("#btnPut").click(function () {
                $.ajax({
                    url: "/restful/request",
                    type: "put",
                    data: "name=lily&age=23",
                    dataType: "json",
                    success: function (json) {
                        $("#message").text(json.message);
                    }
                })

            });
        });

        $(function () {
            $("#btnDelete").click(function () {
                $.ajax({
                    url: "/restful/request",
                    type: "delete",
                    dataType: "json",
                    success: function (json) {
                        $("#message").text(json.message);
                    }
                })

            });
        });


        $(function () {
            $("#btnPersons").click(function () {
                $.ajax({
                    url: "/restful/persons",
                    type: "get",
                    dataType: "json",
                    success: function (json) {
                        console.info(json);
                        for (var i = 0; i < json.length; i++) {
                            var p =  json[i];
                            $("#divPersons").append("<h2>" + p.name + "-" + p.age + "-" + p.createTime+"</h2>");
                        }
                    }
                })
            });
        })
    </script>
</head>
<body>
    <input type="button" id="btnGet" value="发送get请求">
    <input type="button" id="btnPost" value="发送post请求">
    <input type="button" id="btnPut" value="发送put请求">
    <input type="button" id="btnDelete" value="发送delete请求">
    <h1 id="message"></h1>
    <input type="button" id="btnPersons" value="查询所有人员">
    <div id="divPersons"></div>
</body>
</html>

applicationContext.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/mvc
          http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--设置要使用的注解类 在那些包下面-->
    <context:component-scan base-package="com.imooc.restful"></context:component-scan>
    <!--启用springmvc注解形式-->
    <mvc:annotation-driven>
        <!--处理响应后的编码格式-->
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=utf-8</value>
                        <value>application/json;charset=utf-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!--忽略静态资源-->
    <mvc:default-servlet-handler/>

    <!--设置全局跨域请求-->
    <mvc:cors>
        <mvc:mapping path="/restful/**"
                     allowed-origins="http://localhost:8080,http://com.imooc.com"
                     max-age="3600"/>
    </mvc:cors>

    <mvc:interceptors>
        <mvc:interceptor>
            <!--对所有的请求进行拦截-->
            <mvc:mapping path="/**"/>
            <bean class="com.imooc.restful.interceptor.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

</beans>

jquery-3.3.1.min.js代码我就用的课上的


idea界面整体截图:同时上面标记那个啥意思啊?

https://img.mukewang.com/climg/63e6701509d0bdb819041022.jpg



写回答

2回答

好帮手慕小蓝

2023-02-11

同学你好,测试同学的代码之后,是可以正常显示js和icon的,猜测同学这里没有正常显示是因为浏览器缓存过js和icon文件,访问时没有请求服务器导致的。

建议同学清除一下浏览器缓存再尝试一下。

http://img.mukewang.com/climg/6071555b095b0c9c05590274.jpg

祝学习愉快~

1

星辰很精彩

提问者

2023-02-11

谢谢老师,已经解决,还有一个问题,请问idea提示这个是什么意思?要怎么操作呀63e72e1c00019c5109520511.jpg
0

0 学习 · 9886 问题

查看课程