后端使用SpringBoot,Mybatis去数据库查询,如果用户名密码正确,返回{"msg","success"} , APP打开InfoActivity显示该用户的地址;如果错误,提示框toast提示“用户名密码错误!”。请写出相应代码
时间: 2024-10-24 22:14:12 浏览: 29
Springboot整合MyBatis通过调用API查询MySQL数据库数据
在Spring Boot项目中,结合MyBatis进行数据库操作并处理登录验证流程通常涉及以下几个步骤:
首先,在Spring Data JPA或者MyBatis的Mapper接口中编写查询用户信息的方法:
```java
// UserMapper.java (MyBatis)
public interface UserMapper {
@Select("SELECT * FROM users WHERE username = #{username} AND password = #{password}")
Optional<User> findByUsernameAndPassword(String username, String password);
}
```
然后,在服务层的Controller或Service里处理登录请求:
```java
// UserController.java 或 UserService.java
@Service
public class UserController {
private final UserRepository userRepository; // 这里假设UserRepository是JpaRepository或自定义的UserMapper的代理
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@PostMapping("/login")
public ResponseEntity<String> login(@RequestParam String username, @RequestParam String password) {
User user = userRepository.findByUsernameAndPassword(username, password).orElse(null);
if (user != null) {
// 用户名密码正确,获取地址并响应
Address address = user.getAddress();
return ResponseEntity.ok(new LoginResponse("success", address.getAddressString()));
} else {
// 用户名密码错误
return ResponseEntity.badRequest().body("{'msg': '用户名密码错误!'}");
}
}
}
class LoginResponse {
private String msg;
private Address address;
// 构造函数和getter/setter省略...
}
```
最后,在前端(通常是通过Thymeleaf、Vue.js等)接收响应,并展示结果:
```javascript (Express)
axios.post('/login', { username: '...', password: '...' })
.then(response => {
if (response.data.status === 'success') {
// 用户名密码正确,跳转到InfoActivity
router.push({ name: 'InfoActivity', params: { userAddress: response.data.address } });
} else {
Toast.error(response.data.msg); // 使用Toast组件提示错误信息
}
})
.catch(error => {
console.error('Error:', error.response.data);
Toast.error('服务器错误,请稍后再试');
});
```
阅读全文