Spring+Vue实现登录注册

登录的视图页面

        在views里创建一个LoginView.vue,且配置一下路由

LoginView.vue代码

<div>
  <div style="width: 400px; height: 350px; margin: 150px auto; background-color:rgba(107,149,224,0.5); border-radius: 10px">
    <div style="width: 100%; height: 100px; font-size: 30px; line-height: 100px; text-align: center; color: #4a5ed0">欢迎登录</div>
    <div style="margin-top: 25px; text-align: center; height: 320px;">
      <el-form :model="admin">
        <el-form-item>
          <el-input v-model="admin.name" prefix-icon="el-icon-user" style="width: 80%" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="admin.password" prefix-icon="el-icon-lock" style="width: 80%" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 80%; margin-top: 10px" type="primary" @click="login()">登录</el-button>
        </el-form-item>
      </el-form>

    </div>
  </div>
</div>

     页面呈现: 

router:

import LoginView from '../views/LoginView.vue'
{
  path: '/login',
  name: 'login',
  component: LoginView
},

后端代码逻辑

AdminController

@PostMapping("/login")
public Result login(@RequestBody Admin admin) {
    Admin loginUser = adminService.login(admin);
    return Result.success(loginUser);
}

AdminService 

public Admin login(Admin admin) {
    // 1. 进行一些非空判断
    if (admin.getName() == null || "".equals(admin.getName())) {
        throw new CustomException("用户名不能为空");
    }
    if (admin.getPassword() == null || "".equals(admin.getPassword())) {
        throw new CustomException("密码不能为空");
    }
    // 2. 从数据库里面根据这个用户名和密码去查询对应的管理员信息,
    Admin user = adminDao.findByNameAndPassword(admin.getName(), admin.getPassword());
    if (user == null) {
        // 如果查出来没有,那说明输入的用户名或者密码有误,提示用户,不允许登录
        throw new CustomException("用户名或密码输入错误");
    }
    // 如果查出来了有,那说明确实有这个管理员,而且输入的用户名和密码都对;
    return user;
}

AdminMapper 

@Select("select * from admin where name = #{name} and password = #{password} limit 1")
Admin findByNameAndPassword(@Param("name") String name, @Param("password") String password);

 全局异常捕获

GlobalExceptionHandler

package com.example.exception;

import com.example.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice(basePackages="com.example.controller")
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //统一异常处理@ExceptionHandler,主要用于Exception
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(HttpServletRequest request, Exception e){
        log.error("异常信息:",e);
        return Result.error("系统异常");
    }

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public Result customError(HttpServletRequest request, CustomException e){
        return Result.error(e.getMsg());
    }
}

 CustomException(自定义异常)

package com.example.exception;

public class CustomException extends RuntimeException {
    private String msg;

    public CustomException(String msg) {
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

 注册同理

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Spring Boot和Vue.js是两个非常流行的开源框架,可以用来构建Web应用程序。使用Spring Boot和Vue.js可以实现登录注册功能,具体步骤如下: 1. 创建Spring Boot项目 使用Spring Initializr创建一个新的Spring Boot项目,添加所需的依赖项,如Spring Security和Spring Data JPA。 2. 创建数据库表 使用MySQL或其他关系型数据库创建用户表,包括用户名、密码、电子邮件等字段。 3. 创建REST API 使用Spring Boot创建REST API,包括注册和登录功能。注册API将用户信息保存到数据库中,登录API将验证用户凭据并生成JWT令牌。 4. 创建Vue.js应用程序 使用Vue CLI创建一个新的Vue.js应用程序,使用Vue Router和Vuex管理应用程序状态和路由。 5. 创建登录和注册页面 使用Vue.js创建登录和注册页面,包括表单和验证逻辑。在表单提交时,调用REST API进行用户验证和注册。 6. 集成JWT令牌 在Vue.js应用程序中集成JWT令牌,将令牌保存在本地存储中,并在每个请求中发送令牌。 7. 部署应用程序 将Spring Boot应用程序和Vue.js应用程序部署到服务器上,确保它们可以相互通信。 通过以上步骤,就可以使用Spring Boot和Vue.js实现登录注册功能。 ### 回答2: Spring Boot是一个帮助开发者快速构建Web应用程序的开发框架,它提供了许多功能强大的插件和工具,可以轻松地搭建一个初始的项目结构。Vue.js 是流行的开源 JavaScript 框架,它提供了一个灵活可扩展的前端开发体验,可用于从小型单页面应用到大型企业级 Web 应用程序的构建。 在Spring Boot中实现登录和注册功能主要需要通过Spring Security对用户验证进行设置。首先,需要将Spring Security集成到Spring Boot中,从而进行认证和授权。为此,我们需要在项目中添加相关的依赖,并定义一个配置类来启用Spring Security。在配置类中,需要进行对用户验证和密码加密等相关设置。 注册功能的实现需要通过前端页面来进行用户信息的录入,并使用Vue.js进行表单提交。在Vue.js的基础上,我们可以使用axios向后端发送POST请求来提交用户信息。在后端,我们需要编写Controller来处理用户信息的存储操作,并使用JPA来保存用户数据到数据库中。 登录功能的实现需要验证用户在数据库中是否存在,并验证用户输入的密码和数据库中的密码是否匹配。在Spring Security的配置类中,我们可以设置对登录请求的处理和登录成功后的跳转页面。 总之,Spring Boot和Vue.js的结合可以实现一个简单但完整的登录注册功能,使我们可以快速构建一个轻便可靠的Web应用程序。 ### 回答3: Spring Boot 是一款用于构建微服务的,基于 Spring 框架的开源项目,而 Vue 是一款轻量级的MVVM框架,它能够快速构建前端应用程序。Spring Boot 和 Vue.js 的结合,可以让我们快速开发高效的全栈应用程序。在实现登录注册的过程中,我们通常会使用 Spring Security 安全组件来实现用户身份验证和授权操作。 在 Spring Boot 后端实现登录注册 1. 导入 Spring Security 相关依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 配置 Spring Security 认证 在 Spring Boot 应用中配置 Spring Security 认证的方案比较简单,只需要在 SecurityConfig 类中对认证策略进行配置即可。下面是一个示例配置,其中包括了登录页面的信息,用户认证方式等。 ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private PasswordEncoder passwordEncoder; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/") .failureUrl("/login?error=true") .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/"); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder); } } ``` 3. 配置认证细节 在上一步中,我们指定了一个名为 userDetailsService 的服务,它实现Spring Security 的 UserDetailsService 接口。这个接口定义了查找用户信息和验证用户信息的方法。在此,我们需要自己实现此接口: ``` @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Optional<User> userOptional = userRepository.findByUsername(username); if (!userOptional.isPresent()){ throw new UsernameNotFoundException("Username " + username + " not found"); } User user = userOptional.get(); return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthorities(user)); } private Collection<? extends GrantedAuthority> getAuthorities(User user) { return user.getRoles().stream() .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getName())) .collect(Collectors.toList()); } } ``` 注意,这里还需要在 User 类中添加角色信息,再和数据库交互。上述示例代码中,我们使用了 UserRepository 对象对数据库进行操作,并在 loadUserByUsername() 方法中对用户进行身份验证,并返回一个具有权限的 UserDetails 接口实现。 在 Vue.js 前端实现登录注册 Vue.js 是一款灵活且面向数据的 JavaScript 框架,它提供了一些有用的构建模块,如路由器、状态管理等等。在实现登录注册前端页面时,我们可以利用 Vue.js 提供的基本构建模块,进行快速的应用开发。 1. 安装 Vue.js 在开始使用 Vue.js 之前,我们需要安装 Vue.js 的 npm 包,这可以通过以下命令在终端或命令行中执行: ``` npm install vue ``` 2. 编写前端代码 在编写前端页面代码时,我们可以使用 Vue.js 提供的模板指令,例如 v-model、v-bind 等等来进行页面渲染和操作。下面是一个简单的登录页面示例: ``` <template> <div> <h1>Login Form</h1> <form> <div> <label for="username">Username:</label> <input type="text" id="username" v-model="username"> </div> <div> <label for="password">Password:</label> <input type="password" id="password" v-model="password"> </div> <button @click="login()">Login</button> </form> </div> </template> <script> export default { data() { return { username: '', password: '' } }, methods: { login() { // 在这里实现前端登录验证逻辑 } } } </script> ``` 在这个代码段中,我们通过 v-model 指令来绑定了表单输入域的值,然后在 methods 中定义了一个 login() 方法,用于在点击登录按钮时进行登录验证操作。我们可以通过调用后台 Spring Boot API 来实现此操作。 3. 实现前后端交互 在前后端交互方面,我们可以使用 axios 库来进行异步请求操作。下面是一个 Vue.js 调用后台登录接口的示例: ``` <script> import axios from 'axios' export default { data() { return { username: '', password: '' } }, methods: { login() { axios.post('/api/login', {username: this.username, password: this.password}) .then(response => { if(response.data.status == 'success') { alert('登录成功!'); } else { alert('登录失败,请检查用户名或密码!'); } }) .catch(error => { console.error(error); }) } } } </script> ``` 在这个代码段中,我们使用了 Vue.js 插件 axios,调用了一个后台登录接口。在该接口中,我们传入了用户名和密码,并在登录成功后发回一个 success 消息。这里需要注意,登录接口的路径和主机地址需要根据实际情况进行调整。 最后,我们需要将前端和后端代码整合到一起,并进行测试,以确保登录和注册功能正常运行。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值