1. 数据库设置
假设我们有一个名为users
的数据库表,结构如下:
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(100) NOT NULL
);
2. 后端实现 (Spring Boot)
创建Spring Boot项目
可以使用Spring Initializr生成一个Spring Boot项目,选择依赖项Spring Web
和Spring Data JPA
以及MySQL Driver
。
配置数据库连接
在application.properties
文件中配置数据库连接:
spring.datasource.url=jdbc:mysql://localhost:3306/yourdatabase
spring.datasource.username=yourusername
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
创建用户实体类和仓库
import javax.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String username;
@Column(nullable = false)
private String password;
// getters and setters
}
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
创建服务类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
public User save(User user) {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
return userRepository.save(user);
}
public User findByUsername(String username) {
return userRepository.findByUsername(username);
}
}
配置安全性
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login", "/register").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
创建控制器
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private UserService userService;
@PostMapping("/register")
public String register(@RequestBody User user) {
if (userService.findByUsername(user.getUsername()) != null) {
return "User already exists";
}
userService.save(user);
return "User registered successfully";
}
@PostMapping("/login")
public String login(@RequestBody User user) {
User existingUser = userService.findByUsername(user.getUsername());
if (existingUser != null && new BCryptPasswordEncoder().matches(user.getPassword(), existingUser.getPassword())) {
return "Login successful";
} else {
return "Invalid username or password";
}
}
}
3. 前端实现 (Vue.js)
创建Vue项目
可以使用Vue CLI创建一个新的Vue项目。
vue create my-project
cd my-project
安装Axios
使用Axios进行HTTP请求。
npm install axios
创建登录页面和注册页面
Login.vue
<template>
<div>
<h2>Login</h2>
<form @submit.prevent="login">
<div>
<label for="username">Username:</label>
<input type="text" v-model="username" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" v-model="password" required>
</div>
<button type="submit">Login</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
username: '',
password: ''
};
},
methods: {
login() {
axios.post('/api/auth/login', {
username: this.username,
password: this.password
})
.then(response => {
alert(response.data);
})
.catch(error => {
console.error(error);
alert('An error occurred.');
});
}
}
};
</script>
Register.vue
<template>
<div>
<h2>Register</h2>
<form @submit.prevent="register">
<div>
<label for="username">Username:</label>
<input type="text" v-model="username" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" v-model="password" required>
</div>
<button type="submit">Register</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
username: '',
password: ''
};
},
methods: {
register() {
axios.post('/api/auth/register', {
username: this.username,
password: this.password
})
.then(response => {
alert(response.data);
})
.catch(error => {
console.error(error);
alert('An error occurred.');
});
}
}
};
</script>
配置Vue代理
为了在开发环境中解决跨域问题,配置vue.config.js
来代理API请求:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true
}
}
}
};
4. 启动项目
启动Spring Boot应用
确保您的Spring Boot应用在端口8080
上运行。
./mvnw spring-boot:run
启动Vue应用
确保您的Vue应用在开发模式下运行。
npm run serve
5. 测试
通过浏览器访问Vue应用,测试注册和登录功能。
结论
这是一个简单的登录功能实现示例,基于Spring Boot和Vue.js。为了实际应用,应该考虑更多的安全性和错误处理机制,如使用JWT进行认证,保护API端点,输入验证和错误处理。