Vue+springboot登录验证之二

2021-04-30 10:30

阅读:419

标签:context   配置   init   访问   local   目录   mic   message   结果   

前一篇已经将前端的服务写好了,现在记录一下后台的(很简单主要目的就是记录vue的学习,这里没有登录拦截有时间会更新做一个有登录拦截)

首先要使用idea创建一个项目Vue-springboot项目目录如下

技术图片


依赖包:

 

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.0modelVersion>

    groupId>vue-springbootgroupId>
    artifactId>testartifactId>
    version>1.0-SNAPSHOTversion>
    parent>
        groupId>org.springframework.bootgroupId>
        artifactId>spring-boot-starter-parentartifactId>
        version>2.1.4.RELEASEversion>
        relativePath/>
    parent>
dependencies>
    dependency>
        groupId>org.springframework.bootgroupId>
        artifactId>spring-boot-starter-webartifactId>
    dependency>
dependencies>
project>

 

 

 

1.创建一个用户类User

package com.test.entity;

/**
 * @Author zly
 * @Date 2020/6/30 16:24
 */
public class User {
    private String userName;
    private String password;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

 

2.创建一个UserService

package com.test.service;

import com.test.entity.CommonResult;
import com.test.entity.User;

/**
 * @Author zly
 * @Date 2020/6/30 16:26
 */
public interface UserService {
    CommonResult getLoginUser(User user);
}

 

3.创建实现类UserServiceImpl

package com.test.service.impl;

import com.test.entity.CommonResult;
import com.test.entity.User;
import org.springframework.stereotype.Service;
import com.test.service.UserService;

/**
 * @Author zly
 * @Date 2020/6/30 16:29
 */
@Service
public class UserServiceImpl implements UserService {

    @Override
    public CommonResult getLoginUser(User user) {
        if ("blackCatFish".equals(user.getUserName()) && "123456".equals(user.getPassword())) {
            return CommonResult.success("登录成功");
        } else {
            return CommonResult.failed("用户名或者密码错误");
        }

    }
}

 

4.创建一个api 暴露出接口 UserController

package com.test.controller;

import com.test.entity.CommonResult;
import com.test.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.test.service.UserService;

/**
 * @Author zly
 * @Date 2020/6/30 16:43
 */
@RestController
@RequestMapping("/user/")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public CommonResult getLogin(@RequestBody User user) {
        return userService.getLoginUser(user);
    }
}

 

5.定义一个统一的数据返回值

package com.test.entity;

import com.test.enums.IErrorCode;
import com.test.enums.ResultCode;

public class CommonResult {
    private long code;
    private String message;
    private T data;
 
    protected CommonResult() {
    }
 
    protected CommonResult(long code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
 
    /**
     * 成功返回结果
     *
     * @param data 获取的数据
     */
    public static  CommonResult success(T data) {
        return new CommonResult(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
    }
 
    /**
     * 成功返回结果
     *
     * @param data    获取的数据
     * @param message 提示信息
     */
    public static  CommonResult success(T data, String message) {
        return new CommonResult(ResultCode.SUCCESS.getCode(), message, data);
    }
 
    /**
     * 失败返回结果
     *
     * @param errorCode 错误码
     */
    public static  CommonResult failed(IErrorCode errorCode) {
        return new CommonResult(errorCode.getCode(), errorCode.getMessage(), null);
    }
 
    /**
     * 失败返回结果
     *
     * @param message 提示信息
     */
    public static  CommonResult failed(String message) {
        return new CommonResult(ResultCode.FAILED.getCode(), message, null);
    }
 
    /**
     * 失败返回结果
     */
    public static  CommonResult failed() {
        return failed(ResultCode.FAILED);
    }
 
    /**
     * 参数验证失败返回结果
     */
    public static  CommonResult validateFailed() {
        return failed(ResultCode.VALIDATE_FAILED);
    }
 
    /**
     * 参数验证失败返回结果
     *
     * @param message 提示信息
     */
    public static  CommonResult validateFailed(String message) {
        return new CommonResult(ResultCode.VALIDATE_FAILED.getCode(), message, null);
    }
 
    /**
     * 未登录返回结果
     */
    public static  CommonResult unauthorized(T data) {
        return new CommonResult(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage(), data);
    }
 
    /**
     * 未授权返回结果
     */
    public static  CommonResult forbidden(T data) {
        return new CommonResult(ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage(), data);
    }
 
    public long getCode() {
        return code;
    }
 
    public void setCode(long code) {
        this.code = code;
    }
 
    public String getMessage() {
        return message;
    }
 
    public void setMessage(String message) {
        this.message = message;
    }
 
    public T getData() {
        return data;
    }
 
    public void setData(T data) {
        this.data = data;
    }
}

 

6.定义一个枚举类

package com.test.enums;

public interface IErrorCode {
    long getCode();
    String getMessage();
}
package com.test.enums;

public enum ResultCode implements IErrorCode {
    SUCCESS(200, "操作成功"),
    FAILED(500, "操作失败"),
    VALIDATE_FAILED(404, "参数检验失败"),
    UNAUTHORIZED(401, "暂未登录或token已经过期"),
    FORBIDDEN(403, "没有相关权限");
    private long code;
    private String message;
 
    private ResultCode(long code, String message) {
        this.code = code;
        this.message = message;
    }
 
    public long getCode() {
        return code;
    }
 
    public String getMessage() {
        return message;
    }
}

 

启动后端端口设置为8081访问前端页面点击登录的时候会有这个问题

Access to XMLHttpRequest at ‘http://localhost:8081/user/login‘ from origin ‘http://localhost:8086‘ has been blocked by CORS policy: Response to preflight request doesn‘t pass access control check: No ‘Access-Control-Allow-Origin‘ header is present on the requested resource.

技术图片

这个是跨域的问题 

在后台项目中引入跨域配置

package com.cmbchina.ccd.itpm.project.filter;


import org.springframework.context.annotation.Configuration;

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class CorsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest rep = (HttpServletRequest) req;
        String originStr = rep.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", originStr);
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "authorization,Origin, No-Cache, X-Requested-With, " +
                                                           "If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, " +
                                                           "Content-Type, X-E4M-With");
        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {
    }
}

再点击登录就能跳到table页面了

技术图片

Vue+springboot登录验证之二

标签:context   配置   init   访问   local   目录   mic   message   结果   

原文地址:https://www.cnblogs.com/blackCatFish/p/13228607.html


评论


亲,登录后才可以留言!