乐优day06,CORS、分页、vue

CORS跨域

解决跨域的方案

目前比较常用的跨域解决方案有3种:

  • Jsonp
    最早的解决方案,利用script标签可以跨域的原理实现。
    限制:
    • 需要服务的支持
    • 只能发起GET请求
  • nginx反向代理
    思路是:利用nginx把跨域反向代理为不跨域,支持各种请求方式
    缺点:需要在nginx进行额外配置,语义不清晰
  • CORS
    规范化的跨域请求解决方案,安全可靠。
    优势:
    • 在服务端进行控制是否允许跨域,可自定义规则
    • 支持各种请求方式
      缺点:
    • 会产生额外的请求

我们这里会采用cors的跨域方案。

什么是cors

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。

它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。

CORS需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE浏览器不能低于IE10。

  • 浏览器端:
    目前,所有浏览器都支持该功能(IE10以下不行)。整个CORS通信过程,都是浏览器自动完成,不需要用户参与。
  • 服务端:
    CORS通信与AJAX没有任何差别,因此你不需要改变以前的业务逻辑。只不过,浏览器会在请求中携带一些头信息,我们需要以此判断是否允许其跨域,然后在响应头中加入一些信息即可。这一般通过过滤器完成即可。

6.3.2.原理有点复杂

浏览器会将ajax请求分为两类,其处理方案略有差异:简单请求、特殊请求。

6.3.2.1.简单请求

只要同时满足以下两大条件,就属于简单请求。:

(1) 请求方法是以下三种方法之一:

  • HEAD
  • GET
  • POST

(2)HTTP的头信息不超出以下几种字段:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-Type:只限于三个值application/x-www-form-urlencoded、multipart/form-data、text/plain

当浏览器发现发起的ajax请求是简单请求时,会在请求头中携带一个字段:Origin.

Origin中会指出当前请求属于哪个域(协议+域名+端口)。服务会根据这个值决定是否允许其跨域。

如果服务器允许跨域,需要在返回的响应头中携带下面信息:

Access-Control-Allow-Origin: http://manage.leyou.com
Access-Control-Allow-Credentials: true
Content-Type: text/html; charset=utf-8
  • Access-Control-Allow-Origin:可接受的域,是一个具体域名或者*(代表任意域名)
  • Access-Control-Allow-Credentials:是否允许携带cookie,默认情况下,cors不会携带cookie,除非这个值是true

有关cookie:

要想操作cookie,需要满足3个条件:

  • 服务的响应头中需要携带Access-Control-Allow-Credentials并且为true。
  • 浏览器发起ajax需要指定withCredentials 为true
  • 响应头中的Access-Control-Allow-Origin一定不能为*,必须是指定的域名

6.3.2.2.特殊请求

不符合简单请求的条件,会被浏览器判定为特殊请求,,例如请求方式为PUT。

预检请求

特殊请求会在正式通信之前,增加一次HTTP查询请求,称为"预检"请求(preflight)。

浏览器先询问服务器,当前网页所在的域名是否在服务器的许可名单之中,以及可以使用哪些HTTP动词和头信息字段。只有得到肯定答复,浏览器才会发出正式的XMLHttpRequest请求,否则就报错。

一个“预检”请求的样板:

OPTIONS /cors HTTP/1.1
Origin: http://manage.leyou.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: X-Custom-Header
Host: api.leyou.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...

与简单请求相比,除了Origin以外,多了两个头:

  • Access-Control-Request-Method:接下来会用到的请求方式,比如PUT
  • Access-Control-Request-Headers:会额外用到的头信息

预检请求的响应

服务的收到预检请求,如果许可跨域,会发出响应:

HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2.0.61 (Unix)
Access-Control-Allow-Origin: http://manage.leyou.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: X-Custom-Header
Access-Control-Max-Age: 1728000
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Content-Length: 0
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Content-Type: text/plain

除了Access-Control-Allow-Origin和Access-Control-Allow-Credentials以外,这里又额外多出3个头:

  • Access-Control-Allow-Methods:允许访问的方式
  • Access-Control-Allow-Headers:允许携带的头
  • Access-Control-Max-Age:本次许可的有效时长,单位是秒,过期之前的ajax请求就无需再次进行预检了

如果浏览器得到上述响应,则认定为可以跨域,后续就跟简单请求的处理是一样的了。

处理方案

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        //1.添加CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //1) 允许的域,不要写*,否则cookie就无法使用了
        config.addAllowedOrigin("http://manage.leyou.com");
        //2) 是否发送Cookie信息
        config.setAllowCredentials(true);
        //3) 允许的请求方式
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        // 4)允许的头信息
        config.addAllowedHeader("*");

        //2.添加映射路径,我们拦截一切请求
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        //3.返回新的CorsFilter.
        return new CorsFilter(configSource);
    }
}

Springboot集成mybatis分页

  • 导包

      <!-- 分页插件pagehelper 三缺一将不可用-->
              <dependency>
                  <groupId>com.github.pagehelper</groupId>
                  <artifactId>pagehelper</artifactId>
                  <version>5.0.0</version>
              </dependency>
              <dependency>
                  <groupId>com.github.pagehelper</groupId>
                  <artifactId>pagehelper-spring-boot-autoconfigure</artifactId>
                  <version>1.2.3</version>
              </dependency>
              <dependency>
                  <groupId>com.github.pagehelper</groupId>
                  <artifactId>pagehelper-spring-boot-starter</artifactId>
                  <version>1.2.3</version>
              </dependency>
              <!-- 分页插件pagehelper -->
    
  • 开始执行业务代码

      		//开始执行分页
              PageHelper.startPage(page , rows);
              //封装一个Example对象
              Example ex = new Example(Brand.class);
      
              //查找列表数据并强转为page对象
              Page<Brand> pageInfo = (Page<Brand>) brandMapper.selectByExample(ex);
    

练习的vue代码

<template>
  <div>
  <!--用于将数据进行一行展示-->
    <v-layout>
    <!--数据使用flex进行封装-->
      <v-flex>
        <v-btn color="info" >新增品牌</v-btn>
      </v-flex>
      <!--中间多余的空格可以使用v-spacer-->
      <v-spacer/>
      <v-flex px-2 pb-2>
      <!--文本框v-text-field,hide-details用于隐藏错误提示区域,append-icon="search"增加搜索图标-->
       <v-text-field hide-details append-icon="search" v-model="key"/>
      </v-flex>
    </v-layout>

    <v-data-table
      :headers="headers" # 头信息
      :items="brands" # 绑定的数据列表名称
      :pagination.sync="pagination" # 分页名称
      :server-items-length="totalBrands" # 总数据条数
      :loading="loading" # 是否加载进度条
      class="elevation-1"
    >

<!--将数据进行展示出来,像一个list列表进行展示-->
      <template slot="items" slot-scope="props">
        <td class="text-xs-center">{{ props.item.id }}</td>
        <td class="text-xs-center">{{ props.item.name }}</td>
        <td class="text-xs-center"><img v-if="props.item.image" :src="props.item.image" width="130" height="40"/></td>
        <td class="text-xs-center">{{ props.item.letter }}</td>
        <td class="text-xs-center">
        <!--v-icon是图标-->
          <v-icon color="info" small>
              edit
          </v-icon>
          <v-icon color="error" small>
              delete
          </v-icon>
        </td>
      </template>

    </v-data-table>
  </div>
</template>

<script>
    export default {
        name: "MyBrand",
        data(){
          return{
          //将属性进行一一的定义出来
            totalBrands:0,
            //定义头信息
            headers:[
              {text: '品牌Id', align: 'center', sortable: true, value: 'id'},
              {text: '品牌名称', align: 'center', sortable: false, value: 'name'},
              {text: '品牌图片', align: 'center', sortable: false, value: 'image'},
              {text: '品牌首字母', align: 'center', sortable: true, value: 'letter'},
              {text: '操作', align: 'center', sortable: false},
            ],
            //内容默认为空
            brands:[],
            //加载完毕之后关闭加载的进度条
            loading: false,
            //分页默认为空
            pagination:{},
            //搜索过滤字段
            key:""
          }
        },
      methods:{
      //通过axios查询数据
        getBrands(){
          this.$http.get('/brand/page',{
            params:{
              page: this.pagination.page, // 当前页
              rows: this.pagination.rowsPerPage, // 每页条数
              sortBy: this.pagination.sortBy, // 排序字段
              desc: this.pagination.descending, // 是否降序
              key: this.key // 查询字段
            }
          }).then(resp => {
          //将查询的结果进行赋值
            console.log(resp.data.allPageTotal);
            this.brands = resp.data.rows;
            this.totalBrands = resp.data.allPageTotal;
            this.loading = false;
          });
        }
      },
      //vue实例创建时开始执行
      created(){
          this.loading = true,
            this.getBrands()
      },
      //开启数据的监控,一旦发生变化,就重新查询
      watch:{
        key(){
          console.log(this.key);
          this.getBrands();
        },
        pagination:{
          deep:true,
          handler(){
            console.log('每页大小:'+this.pagination);
            this.getBrands();
          }
        }
      }
    }
</script>

<style scoped>

</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值