我尝试使用Springboot和Flutter技术创建一个移动登录页面。我是新开发的。 Tomcat正常启动并连接到db。我使用模拟器 Pixel 4 api 31 来测试我的应用程序。
dart 文件中的 url http://192.168.2.6:8080/users/login' 是否正确?当按下登录按钮时
I/flutter ( 7730): Error: 404
出现了。
我也尝试将login_page.dart文件中的url更改为'http://localhost:8080/users/login'、'http://127.0.0.1:8080/users/login'和http://'127.0 .0.2':8080/users/login' 但我收到连接拒绝错误。 这是代码:
应用程序.java
@SpringBootApplication
@EnableJpaRepositories("org.example.repository.*")
@ComponentScan(basePackages = { "org.example.controller.*" })
@EntityScan("org.example.model.*")
public class App
{
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
用户控制器.java
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
private UserMapper userMapper; // Inject UserMapper here
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping("/register") // in mobile app doesn't need all users should be registered by corresponding gym
public ResponseEntity<UserDTO> registerUser(@RequestBody UserDTO userDTO) {
// Receive and validate userDTO from the client
// Map userDTO to a User entity
User userEntity = userService.registerUser(userDTO);
// Map the resulting User entity to a UserDTO for the response
UserDTO registeredUserDTO = UserMapper.mapToDTO(userEntity);
return ResponseEntity.ok(registeredUserDTO);
}
@PostMapping("/login")
public ResponseEntity<UserDTO> loginUser(@RequestBody UserDTO userDTO) throws AuthenticationException {
// Validate the loginRequest, e.g., check for null values
// Map userDTO to a User entity
UserDTO loginUserDTO = userService.loginUser(userDTO);
return ResponseEntity.ok(loginUserDTO);
}
应用程序.属性
server.port=8080
server.tomcat.threads.max=200
server.connection-timeout=5s
server.max-http-header-size=8KB
server.tomcat.max-swallow-size=2MB
server.tomcat.max-http-post-size=2MB
spring.datasource.url=jdbc:mysql://localhost:3306/testdbgymapp?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto=update
login_page.dart(Flutter 应用程序)
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'home_page.dart';
class LoginDemo extends StatefulWidget {
@override
_LoginDemoState createState() => _LoginDemoState();
}
class _LoginDemoState extends State<LoginDemo> {
final TextEditingController usernameController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
Future<void> loginUser() async {
final response = await http.post(
Uri.parse('http://192.168.2.6:8080/users/login'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'username': usernameController.text,
'password': passwordController.text,
}),
);
if (response.statusCode == 200) {
// Successful login
Navigator.push(
context, MaterialPageRoute(builder: (_) => HomePage()));
} else if (response.statusCode == 400) {
// Invalid username or password
print('Invalid username or password');
} else {
// Handle other error cases
print('Error: ${response.statusCode}');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text("Login Page"),
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 60.0),
child: Center(
child: Container(
width: 200,
height: 150,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(50.0)),
child: Image.asset('asset/images/gymApp-logo.png')),
),
),
Padding(
//padding: const EdgeInsets.only(left:15.0,right: 15.0,top:0,bottom: 0),
padding: EdgeInsets.symmetric(horizontal: 15),
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email',
hintText: 'Enter valid email id as [email protected]'),
),
),
Padding(
padding: const EdgeInsets.only(
left: 15.0, right: 15.0, top: 15, bottom: 0),
//padding: EdgeInsets.symmetric(horizontal: 15),
child: TextField(
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter secure password'),
),
),
TextButton(
onPressed: (){
//TODO FORGOT PASSWORD SCREEN GOES HERE
},
child: Text(
'Forgot Password',
style: TextStyle(color: Colors.blue, fontSize: 15),
),
),
Container(
height: 50,
width: 250,
decoration: BoxDecoration(
color: Colors.blue, borderRadius: BorderRadius.circular(20)),
child: TextButton(
onPressed: () {
loginUser();
},
child: Text(
'Login',
style: TextStyle(color: Colors.white, fontSize: 25),
),
),
),
SizedBox(
height: 130,
),
Text('New User? Create Account')
],
),
),
);
}
}
您可以通过输入轻松测试这一点
curl -XPOST localhost:8000/users/login
在你的控制台中。
如果两者都在本地运行,“IP”通常是
localhost
而不是 192.168.x.x
。
如果您使用 Android 模拟器,请检查以下文档:
https://developer.android.com/studio/run/emulator-networking#networkaddresses