使用springboot实现登陆注册,给出从数据库表结构到前端的代码
时间: 2023-05-25 22:02:25 浏览: 119
SpringBoot实现登陆注册源码
A:
1. 数据库表结构:
创建用户表
```
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id 主键',
`username` varchar(50) NOT NULL COMMENT '用户名',
`password` varchar(50) NOT NULL COMMENT '密码',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
`phone` varchar(15) DEFAULT NULL COMMENT '手机号',
`create_time` datetime NOT NULL COMMENT '注册时间',
`update_time` datetime NOT NULL COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';
```
2. 后端代码:
使用Spring Boot,可以通过Spring Security实现用户的登录和注册,示例代码如下:
> UserController.java
```java
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/register")
public Result register(@RequestBody User user) {
boolean result = userService.addUser(user);
if (result) {
return Result.success("注册成功!");
} else {
return Result.fail("注册失败!");
}
}
@PostMapping("/login")
public Result login(@RequestBody User user) {
String token = userService.login(user.getUsername(), user.getPassword());
if (token == null) {
return Result.fail("登录失败,用户名或密码错误!");
} else {
return Result.success(token);
}
}
}
```
> UserService.java
```java
@Service
public class UserService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findUserByUsername(username);
if (user != null) {
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
new ArrayList<>());
} else {
throw new UsernameNotFoundException("用户不存在!");
}
}
public boolean addUser(User user) {
if (userRepository.findUserByUsername(user.getUsername()) != null) {
return false;
}
user.setCreateTime(new Date());
user.setUpdateTime(new Date());
userRepository.save(user);
return true;
}
public String login(String username, String password) {
try {
UserDetails userDetails = loadUserByUsername(username);
if (userDetails != null && new BCryptPasswordEncoder().matches(password, userDetails.getPassword())) {
return jwtTokenUtil.generateToken(userDetails);
}
} catch (Exception e) {
}
return null;
}
}
```
3. 前端代码:
可以使用Vue.js实现,示例代码如下:
> Login.vue
```vue
<template>
<div>
<h2>用户登录</h2>
<div>
<label>用户名:</label>
<input v-model="user.username" type="text" />
</div>
<div>
<label>密码:</label>
<input v-model="user.password" type="password" />
</div>
<div>
<button @click="login">登录</button>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "Login",
data() {
return {
user: {
username: "",
password: ""
}
};
},
methods: {
login() {
axios.post("/api/login", this.user).then(response => {
let token = response.data.data;
localStorage.setItem("token", token);
this.$router.replace("/index");
}).catch(error => {
alert(error.response.data.message);
})
}
}
};
</script>
```
> Register.vue
```vue
<template>
<div>
<h2>用户注册</h2>
<div>
<label>用户名:</label>
<input v-model="user.username" type="text" />
</div>
<div>
<label>密码:</label>
<input v-model="user.password" type="password" />
</div>
<div>
<label>邮箱:</label>
<input v-model="user.email" type="text" />
</div>
<div>
<button @click="register">注册</button>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "Register",
data() {
return {
user: {
username: "",
password: "",
email: ""
}
};
},
methods: {
register() {
axios.post("/api/register", this.user).then(response => {
alert(response.data.message);
this.$router.push("/login");
}).catch(error => {
alert(error.response.data.message);
})
}
}
};
</script>
```
完整示例代码可参考:
https://github.com/JeffLi1993/springboot-learning-example/tree/master/springboot-security-jwt-authentication-example-with-kotlin
阅读全文