由于之前那篇文章是在大學期間好多東西都不太懂的時候寫的,放到現(xiàn)在再來看總感覺到處都是問題(或者說已經(jīng)看不懂啦)。但是看到每天上漲的那點閱讀量,想了想還是把這個再用相對正常的方式再重寫一遍吧。
為了省事本項目的服務端采用SpringBoot + MybatisPlus開發(fā),要是Java水平還不夠的小伙伴就自己再稍微努力努力?(°?°)?
一、服務端
首先對SpringBoot提一嘴,這玩意是用來簡化Spring應用的初始搭建以及開發(fā)過程的。
創(chuàng)建好工程之后在pom文件中導入相關依賴,用到的大概有mysql、druid、mybatis。mybatis-plus、fastjson、lombok等。
隨后對配置信息進行設置,這里采用yml文件的格式。
server:
port: 80
spring:
#數(shù)據(jù)庫相關配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db1?serverTimezone=UTC
username: root
password: 1234
#設置數(shù)據(jù)源為druid
type: com.alibaba.druid.pool.DruidDataSource
cache:
redis:
time-to-live: 1800000
mybatis-plus:
global-config:
db-config:
id-type: assign_id
configuration:
#在映射實體或者屬性時,將數(shù)據(jù)庫中表名和字段名中的下劃線去掉,按照駝峰命名法映射
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
隨后就是緊張刺激(并不)的代碼開發(fā)啦。
由于本項目只是為了實現(xiàn)Android訪問MySQL數(shù)據(jù)庫,就只是模擬實現(xiàn)了一個用戶登錄功能。
先準備好MySQL中的數(shù)據(jù):
對應好實體類中的User類:
@Data
public class User {
private Integer id;
private String userId;
private String userName;
private String password;
private String phoneNumber;
private String sex;
private String personalSignature;
}
由于使用了MybatisPlus,所以數(shù)據(jù)層會顯的非常簡單:
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
業(yè)務層接口:
public interface UserService extends IService<User> {
Result<User> login(String userId, String password);
}
業(yè)務層實現(xiàn):
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public Result<User> login(String userId, String password) {
// 1、校驗參數(shù)
if (StringUtils.isBlank(userId) || StringUtils.isBlank(password)) {
return Result.error("請輸入賬號和密碼");
}
// 2、構造查詢條件
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getUserId, userId);
queryWrapper.eq(User::getPassword, password);
User user = userMapper.selectOne(queryWrapper);
// 3、判斷查詢結果
if (user != null) {
return Result.success(user);
} else {
return Result.error("賬號或密碼錯誤");
}
}
}
表現(xiàn)層:
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public Result<User> login(@RequestBody Map<String, String> userInfo) {
log.info("用戶登錄");
String userId = userInfo.get("userId");
String password = userInfo.get("password");
return userService.login(userId, password);
}
}
其中的Result為通用的返回結果類,包含了狀態(tài)碼、錯誤信息以及返回數(shù)據(jù)等內(nèi)容。
至此,服務端的開發(fā)就告一段落。運行啟動類,進行調(diào)試。
二、Android端
創(chuàng)建完工程后簡單的寫兩個頁面,一個用于登錄,一個用于展示信息。
對頁面控件進行初始化完成后,給按鈕添加一個點擊事件:
btn_login.setOnClickListener(v -> {
String id = et_id.getText().toString();
String pwd = et_pwd.getText().toString();
// 判斷用戶輸入賬號和密碼是否為空
if (StringUtil.isNotEmpty(id) && StringUtil.isNotEmpty(pwd)){
loginTest(id, pwd);
}else {
ToastUtil.showShort( LoginActivity.this, "請輸入賬號和密碼");
}
});
具體實現(xiàn)思路是:使用OkHttp向服務端發(fā)送請求,將服務端返回的JSON數(shù)據(jù)用GSON進行解析,從而將在數(shù)據(jù)庫中獲取到的信息進行展示。具體實現(xiàn)如下:
private void loginTest(String id, String pwd) {
new Thread(() -> {
try {
// 創(chuàng)建OKHttp客戶端
OkHttpClient client = new OkHttpClient();
// 構造消息體(不是JSON格式)
RequestBody requestBody = new FormBody.Builder()
.add("userId", id)
.add("password", pwd)
.build();
// 發(fā)送post請求
Request request = new Request.Builder()
.url("http://server.natappfree.cc:39945/user/login")
.post(requestBody)
.build();
// 獲取響應
Response response = client.newCall(request).execute();
String userInfo = response.body().string();
// 利用GSON將返回的JSON格式數(shù)據(jù)轉化為對象
Gson gson = new Gson();
Result result = gson.fromJson(userInfo, Result.class);
// 判斷返回結果,確認登錄是否成功
if (result == null) {
ToastUtil.showShortInThread(LoginActivity.this, "登錄失敗");
return;
}
if (result.getCode() == 1 && result.getData() != null) {
String userStr = result.getData().toString();
User user = gson.fromJson(userStr, User.class);
Intent intent = new Intent(LoginActivity.this, UserInfoActivity.class);
intent.putExtra("User", user);
startActivity(intent);
} else {
ToastUtil.showShortInThread(LoginActivity.this, result.getMsg());
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
其中的請求地址使用了NATAPP內(nèi)網(wǎng)穿透工具將本地的端口進行映射,使得外網(wǎng)也可以訪問。(免費隧道每次啟動時地址會發(fā)生變化)
啟動項目:
登錄頁面
輸入正確的賬號密碼信息,點擊登錄,并沒有反應。檢查服務器后發(fā)現(xiàn)報了一個異常:
2023-02-22 17:42:58.922? WARN 9424 --- [p-nio-80-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
經(jīng)排查發(fā)現(xiàn),在服務端接收參數(shù)時使用了@RequestBody注解,表示我們接收的是一個JSON格式的數(shù)據(jù),但是OkHttp發(fā)送的數(shù)據(jù)并不是JSON數(shù)據(jù),因此在這里報了異常。那么只要在接收參數(shù)時直接用兩個變量接收即可解決這個問題,修改UserController中的代碼:
@PostMapping("/login")
public Result<User> login(String userId, String password) {
log.info("用戶登錄");
return userService.login(userId, password);
}
重啟服務,后再次嘗試登陸:
訪問成功,撒花?ヽ(°▽°)ノ?文章來源:http://www.zghlxwxcb.cn/news/detail-401233.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-401233.html
到了這里,關于Android連接MySQL數(shù)據(jù)庫的方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!