验证码(前后端分离)

来源: 易途老师实训课程

CrossDomainFilter.java

package com.etoak.filter;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;


import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
//跨域的过滤器\
//@Slf4j
//@Configuration
public class CrossDomainFilter implements Filter {
    
    

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
    
    
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		// 允许所有的请求域名访问我们的跨域资源,可以固定单个或者多个内容
		httpResponse.setHeader("Access-Control-Allow-Origin", "*");//
		// httpResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:9090");// 允许所有的请求域名访问我们的跨域资源,可以固定单个或者多个内容
		httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");// 允许何种请求方法访问该跨域资源服务器
		httpResponse.setHeader("Access-Control-Max-Age", "3600");// 预检请求的有效期,单位为秒。有效期内,不会重复发送预检请求
		httpResponse.addHeader("Access-Control-Allow-Headers",
				"Accept, Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With");// 允许所有的请求header访问,可以自定义设置任意请求头信息
		httpResponse.setHeader("Access-Control-Allow-Credentials", "true");// 是否允许用户发送、处理cookie
		httpResponse.setHeader("Access-Control-Expose-Headers","code");
		chain.doFilter(request, httpResponse);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
    
    
		//log.info("-----CrossDomainFilter init -------");
	}

	@Override
	public void destroy() {
    
    

	}

}

PetApp.java

package com.etoak;

import com.etoak.filter.CrossDomainFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class PetApp {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(PetApp.class,args);
    }

//    SpringBoot注册跨域过滤器
    @Bean
    public FilterRegistrationBean<CrossDomainFilter> filterRegistrationBean() {
    
    

//        创建注册过滤器的对象
        FilterRegistrationBean<CrossDomainFilter> filter = new FilterRegistrationBean<>();
//        注册过滤器
        filter.setFilter(new CrossDomainFilter());
//        设置优先级 1表示最高级别
        filter.setOrder(1);
        // /*表示拦截所有请求
        filter.addUrlPatterns("/*");
        return filter;
    }
}

main.js


/*引入axios*/
import axios from "axios";
/*设置默认访问路径*/
axios.defaults.baseURL = 'http://localhost:8000/pet'
/*在Vue中挂在anxios*/
Vue.prototype.$http = axios

回到登陆页面Login.vue

<template  class="login">
  <div id="login" class="login">
    <!--  :src 单向绑定          v-model    -->
    <mochi-box style="margin-left: 43%; margin-top: 14%;"  shiba="tuna" mood="drool" blush left-eye="wink" right-eye="laugh" left-ear="down" right-ear="down">
      <el-form :model="loginForm" :rules="rules" ref="loginForm" style="width: 310px">
        <el-form-item prop="name">
          <el-input v-model="loginForm.name" placeholder="请输入用户名:我爱赢政"></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入用户密码"></el-input>
        </el-form-item>

        <el-form-item prop="securityCode">
          <el-row :gutter="20">
            <el-col :span="11">
              <el-input v-model="loginForm.securityCode" placeholder="请输入验证码"></el-input>
            </el-col>
<!-- ------------------------------------------------------------------>

            <el-col :span="7">
              <img :src="url" alt="加载失败">
            </el-col>
            <el-col :span="6">
              <el-button type="text" @click="getCode()">看不清</el-button>
            </el-col>
          </el-row>
<!-- ------------------------------------------------------------------>

        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="submitForm('loginForm')">登录</el-button>
          <el-button type="text" style="margin-left: 0px;" @click="resetForm('loginForm')">还没有账号?点我注册</el-button>
        </el-form-item>
      </el-form>
    </mochi-box>
  </div>
</template>

<script>
import MochiBox from "@/components/Mochi/MochiBox.vue";
export default {
    
    
  name: 'Login',
  components:{
    
    
    MochiBox
  },
  data(){
    
    
    return{
    
    
      url:{
    
    },
      loginForm:{
    
    
        name:'',
        password:'',
        securityCode:''
      },
      rules:{
    
    
        name: [
          {
    
     required: true, message: '请输入用户名', trigger: 'blur' },
          {
    
     min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          {
    
     required: true, message: '请输入密码', trigger: 'blur' },
          {
    
     min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        securityCode: [
          {
    
     required: true, message: '请输入验证码', trigger: 'blur' },
          // { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods:{
    
    
    submitForm(formName) {
    
    
      this.$refs[formName].validate((valid) => {
    
    
        if (valid) {
    
    
          alert('submit!');
        } else {
    
    
          console.log('error submit!!');
          return false;
        }
      });
    },


//  ----------------------------------------------------


    //获取后端验证码
    getCode(){
    
    
      this.$http.get('/user/getCode',{
    
    responseType:'blob'}).then(res => {
    
    
        let blob = new Blob([res.data]);
        this.url = window.URL.createObjectURL(blob);

      } )
    }
  },
  //当页面数据加载完毕的时候就会触发的方法
  created() {
    
    
    this.getCode();
  }


//  ----------------------------------------------------
}
</script>

<style scoped>
.login{
    
    
  height: 100%;
  background: url("../../assets/img/background-img.jpg") repeat no-repeat;
  background-size: cover;
}
</style>

效果图:

效果图

猜你喜欢

转载自blog.csdn.net/weixin_42692989/article/details/122249936