真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

后端springboot+前端Android交互+mysq

1.概述

使用spring boot作為后端框架與Android端配合MySQL進(jìn)行基本的交互,包含了最基本的增刪查改功能.

達(dá)孜網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)公司!從網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開(kāi)發(fā)、APP開(kāi)發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)公司等網(wǎng)站項(xiàng)目制作,到程序開(kāi)發(fā),運(yùn)營(yíng)維護(hù)。創(chuàng)新互聯(lián)公司從2013年成立到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來(lái)保證我們的工作的順利進(jìn)行。專(zhuān)注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)公司。

2.開(kāi)發(fā)環(huán)境

  • win10
  • IDEA
  • tomcat9.0.27
  • mysql8.0.17
  • spring boot

3.后端

(1)新建一個(gè)spring boot項(xiàng)目

可以看這里

(2)Entity

新建User類(lèi)作為實(shí)體類(lèi):

package com.test;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

這里其實(shí)使用的是(1)中的代碼,里面有詳細(xì)的解釋.

(3)Repository

新建UserRepository去實(shí)現(xiàn)增刪查改:

package com.test;

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Repository
public interface UserRepository extends CrudRepository
{
    @Query(value = "select * from user where name = ?1",nativeQuery = true)
    public List findByName(String name);

    @Modifying
    @Query(value = "delete from user where name = ?1",nativeQuery = true)
    public int deleteByName(String name);
}

由于CrudRepository中已經(jīng)包含了"增"與"改",所以按需要實(shí)現(xiàn)自己的"查"與"刪"即可.
CrudRepository的api很簡(jiǎn)單,官方文檔在這里.

  • "增"使用save即可,參數(shù)為實(shí)體類(lèi)
  • "刪"使用deleteById,通過(guò)主鍵刪除,若不想通過(guò)主鍵刪除可以自己編寫(xiě)sql,像上面一樣
  • "查"使用findAll或findById,自定義查找的話需要自己編寫(xiě)sql.
  • "改"也可使用save,注意需要設(shè)置主鍵.

@Query用于設(shè)置sql,nativeQuery表示使用原生sql.

(4)Service

新建一個(gè)MainService.java

package com.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Transactional
@Service
public class MainService {
    @Autowired
    private UserRepository userRepository;

    public Iterable getAllUsers()
    {
        return userRepository.findAll();
    }

    public List findByName(String name)
    {
        return userRepository.findByName(name);
    }

    public boolean add(String name)
    {
        User user = new User();
        user.setName(name);
        userRepository.save(user);
        return true;
    }

    public boolean modify(Integer id,String name)
    {
        User user = new User();
        user.setName(name);
        user.setId(id);
        userRepository.save(user);
        return true;
    }

    public boolean deleteByName(String name)
    {
        return userRepository.deleteByName(name) != 0;
    }
}
  • getAllUsers()返回所有行,Iterable類(lèi)型
  • findByName()根據(jù)name返回所有name相同的行.
  • add直接使用了save,由于save返回的是實(shí)體類(lèi),原本的代碼是這樣寫(xiě)的:
    return userRepository.save(user) != null;

    后端spring boot+前端Android交互+mysq
    但是文檔說(shuō)了不會(huì)為null,所以只能強(qiáng)制返回true了.

  • modify使用了id與name作為參數(shù),新建一個(gè)user,將其作為setter的參數(shù),然后交給save.
  • deleteByName使用了自定義的刪除函數(shù),返回的是int,在UserRepository中這個(gè)int代表sql影響的行數(shù),刪除成功則行數(shù)不為0,刪除失敗,或者沒(méi)有這行數(shù)據(jù)則行數(shù)為0.因此將返回值與0進(jìn)行比較.

(5)Controller

package com.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping(path = "/demo")
public class MainController {
    @Autowired
    private MainService mainService;

    @GetMapping(path = "/getAll")
    public @ResponseBody Iterable getAllUsers()
    {
        return mainService.getAllUsers();
    }

    @PostMapping(path = "/get")
    public @ResponseBody List findByName(String name)
    {
        return mainService.findByName(name);
    }

    @PostMapping(path = "/add")
    public @ResponseBody boolean add(@RequestParam String name)
    {
        return mainService.add(name);
    }

    @PostMapping(path = "/modify")
    public @ResponseBody boolean modify(@RequestParam Integer id,@RequestParam String name)
    {
        return mainService.modify(id,name);
    }

    @PostMapping(path = "/delete")
    public @ResponseBody boolean deleteByName(@RequestParam String name)
    {
        return mainService.deleteByName(name);
    }
}

Controller主要就是幾個(gè)注解,除了getAllUsers使用Get外,其他的都是用Post.另外就是路徑設(shè)置,直接在path中設(shè)置即可.
后端的話到這里就基本完成了,剩下的打包部署操作就.....

4.前端

什么新建工程之類(lèi)的就不說(shuō)了.
直接上MainActivity:

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Looper;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.example.myapplication.model.dao.*;
import com.example.myapplication.model.entity.*;

import java.io.IOException;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button register = findViewById(R.id.register);
        register.setOnClickListener(
                v ->
                {
                    new Thread(()-> {
                        OkHttpClient okHttpClient = new OkHttpClient();
                        String name = ((EditText) findViewById(R.id.name)).getText().toString();
                        FormBody formBody = new FormBody.Builder().add("name", name).build();
                        Request request = new Request.Builder()
                                .url(Constant.ADD)
                                .post(formBody)
                                .build();
                        try (Response response = okHttpClient.newCall(request).execute()) {
                            Looper.prepare();
                            if (Boolean.parseBoolean(response.body().string()))
                            {
                                Toast.makeText(this, "注冊(cè)成功", Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                Toast.makeText(this, "注冊(cè)失敗", Toast.LENGTH_SHORT).show();
                            }
                            Looper.loop();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }).start();
                }
        );
        Button login = findViewById(R.id.login);
        login.setOnClickListener(
                v ->
                {
                    new Thread(()-> {
                        OkHttpClient okHttpClient = new OkHttpClient();
                        String name = ((EditText) findViewById(R.id.name)).getText().toString();
                        FormBody formBody = new FormBody.Builder().add("name", name).build();
                        Request request = new Request.Builder()
                                .url(Constant.GET)
                                .post(formBody)
                                .build();
                        try (Response response = okHttpClient.newCall(request).execute()) {
                            List users = JSONArray.parseArray(response.body().string(),User.class);
                            Looper.prepare();
                            if(users.size() == 0)
                            {
                                Toast.makeText(this,"登錄失敗",Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                Toast.makeText(this,"登錄成功",Toast.LENGTH_SHORT).show();
                            }
                            Looper.loop();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }).start();
                }
        );

        Button delete = findViewById(R.id.delete);
        delete.setOnClickListener(
                v ->
                {
                    new Thread(()-> {
                        OkHttpClient okHttpClient = new OkHttpClient();
                        String name = ((EditText) findViewById(R.id.name)).getText().toString();
                        FormBody formBody = new FormBody.Builder().add("name", name).build();
                        Request request = new Request.Builder()
                                .url(Constant.DELETE)
                                .post(formBody)
                                .build();
                        try (Response response = okHttpClient.newCall(request).execute()) {
                            Looper.prepare();
                            if (Boolean.parseBoolean(response.body().string()))
                            {
                                Toast.makeText(this, "刪除成功", Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                Toast.makeText(this, "刪除失敗", Toast.LENGTH_SHORT).show();
                            }
                            Looper.loop();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }).start();
                }
        );

        Button modify = findViewById(R.id.modify);
        modify.setOnClickListener(
                v ->
                {
                    new Thread(()-> {
                        OkHttpClient okHttpClient = new OkHttpClient();
                        String name = ((EditText) findViewById(R.id.name)).getText().toString();
                        String id = ((EditText)findViewById(R.id.id)).getText().toString();
                        FormBody formBody = new FormBody.Builder()
                                .add("name", name)
                                .add("id",id)
                                .build();
                        Request request = new Request.Builder()
                                .url(Constant.MODIFY)
                                .post(formBody)
                                .build();
                        try (Response response = okHttpClient.newCall(request).execute()) {
                            Looper.prepare();
                            if (Boolean.parseBoolean(response.body().string()))
                            {
                                Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                Toast.makeText(this, "修改失敗", Toast.LENGTH_SHORT).show();
                            }
                            Looper.loop();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }).start();
                }
        );
    }
}

(1)增

OkHttpClient okHttpClient = new OkHttpClient();
String name = ((EditText) findViewById(R.id.name)).getText().toString();
FormBody formBody = new FormBody.Builder().add("name", name).build();
Request request = new Request.Builder()
        .url(Constant.ADD)
        .post(formBody)
        .build();
try (Response response = okHttpClient.newCall(request).execute()) {
    Looper.prepare();
    if (Boolean.parseBoolean(response.body().string()))
    {
        Toast.makeText(this, "注冊(cè)成功", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this, "注冊(cè)失敗", Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}

使用okhttp,通過(guò)FormBody設(shè)置參數(shù),然后創(chuàng)建Request通過(guò)OkHttpClient發(fā)送.
由于后端"增"的方法返回的是一個(gè)true,因此這里將response.body().string()轉(zhuǎn)換成boolean判斷是否操作成功.
稍微提一下,

Looper.prepare();
Looper.loop();

這兩行可以在非UI線程中使用Toast.

(2)刪

OkHttpClient okHttpClient = new OkHttpClient();
String name = ((EditText) findViewById(R.id.name)).getText().toString();
FormBody formBody = new FormBody.Builder().add("name", name).build();
Request request = new Request.Builder()
        .url(Constant.DELETE)
        .post(formBody)
        .build();
try (Response response = okHttpClient.newCall(request).execute()) {
    Looper.prepare();
    if (Boolean.parseBoolean(response.body().string()))
    {
        Toast.makeText(this, "刪除成功", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this, "刪除失敗", Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}

刪這部分也是差不多的,就是改一下url,然后....然后沒(méi)有了....好像很簡(jiǎn)單的樣子?

(3)查

OkHttpClient okHttpClient = new OkHttpClient();
String name = ((EditText) findViewById(R.id.name)).getText().toString();
FormBody formBody = new FormBody.Builder().add("name", name).build();
Request request = new Request.Builder()
        .url(Constant.GET)
        .post(formBody)
        .build();
try (Response response = okHttpClient.newCall(request).execute()) {
    List users = JSONArray.parseArray(response.body().string(),User.class);
    Looper.prepare();
    if(users.size() == 0)
    {
        Toast.makeText(this,"登錄失敗",Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this,"登錄成功",Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}

查這里注意一下后端返回的是List,這里借助阿里的fastjson轉(zhuǎn)換成List.

List users = JSONArray.parseArray(response.body().string(),User.class);

然后判斷有沒(méi)有的話就判斷長(zhǎng)度是否為0即可.

(4)改

OkHttpClient okHttpClient = new OkHttpClient();
String name = ((EditText) findViewById(R.id.name)).getText().toString();
String id = ((EditText)findViewById(R.id.id)).getText().toString();
FormBody formBody = new FormBody.Builder()
        .add("name", name)
        .add("id",id)
        .build();
Request request = new Request.Builder()
        .url(Constant.MODIFY)
        .post(formBody)
        .build();
try (Response response = okHttpClient.newCall(request).execute()) {
    Looper.prepare();
    if (Boolean.parseBoolean(response.body().string()))
    {
        Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this, "修改失敗", Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}

改的話只需一個(gè)額外的ID參數(shù),在FormBody中add一個(gè)即可,不難.

(5)界面




    

界面不詳細(xì)說(shuō)了,不難.

(6)依賴(lài)與其他

后端spring boot+前端Android交互+mysq
注意一下依賴(lài),還有設(shè)置java8.

(7)網(wǎng)絡(luò)權(quán)限

這個(gè)作者之前的文章有說(shuō).
請(qǐng)看這里.

5.測(cè)試

這是"原本的"數(shù)據(jù)庫(kù).
沒(méi)辦法為了測(cè)試.
后端spring boot+前端Android交互+mysq
注冊(cè)一個(gè).
后端spring boot+前端Android交互+mysq
看看數(shù)據(jù)庫(kù):
后端spring boot+前端Android交互+mysq

后端spring boot+前端Android交互+mysq
試試登錄一個(gè)不存在的.
后端spring boot+前端Android交互+mysq
修改:
后端spring boot+前端Android交互+mysq
后端spring boot+前端Android交互+mysq
后端spring boot+前端Android交互+mysq
最后是刪除:
后端spring boot+前端Android交互+mysq
后端spring boot+前端Android交互+mysq
刪除一個(gè)不存在的會(huì)刪除失敗.
后端spring boot+前端Android交互+mysq

6.源碼

  • github
  • 碼云

本文名稱(chēng):后端springboot+前端Android交互+mysq
文章轉(zhuǎn)載:http://weahome.cn/article/pgpjho.html

其他資訊

在線咨詢(xún)

微信咨詢(xún)

電話咨詢(xún)

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部