天天看點

開發執行個體:後端Java和前端vue實作使用者賬号資訊管理功能

作者:程式設計技術彙

使用者賬号資訊管理是一個常見的功能,可以使用Java和Vue來實作。具體步驟如下:

1、建立資料庫表 需要建立一個User表來存儲使用者賬号資訊。表格中應該包含以下字段:id(主鍵)、username(使用者名)、password(密碼)以及其他一些必要的字段。

2、建立Java後端API 建立後端API來擷取使用者資料并将其存儲到資料庫中。可以使用Spring Boot架構來建立,并使用JPA實作資料庫操作。實作API之前,需要確定資料庫連接配接正确配置。

3、建立Vue前端頁面 Vue.js是一款流行的JavaScript架構,可以用它來開發使用者界面。在Vue中,可以建立一個表放置使用者賬号資訊,并定義相應的輸入和送出按鈕等元素。通過AJAX請求,可以從後端API接收到使用者資訊并展示在表單中。

開發執行個體:後端Java和前端vue實作使用者賬号資訊管理功能

4、連接配接前端與後端 前端和後端之間的互動可以通過RESTful API完成。即前端發送HTTP請求規定的位址和處理方式,後端接收這個請求并所對應處理。通常情況下,前端架構已經提供了Ajax、Axios等等HTTP請求庫。

下面展示一個簡單的執行個體代碼(僅供參考):

Java後端API:

@RestController
public class UserController {
    @Autowired
    private UserService userService;
        // 查詢所有使用者資訊
    @GetMapping("/api/users")
    public List<User> getUserList() {
        return userService.getUserList();
    }

    // 添加使用者
    @PostMapping("/api/user")
    public String saveUser(@RequestBody User user) {
        if (userService.save(user)) {
            return "success";
        } else {
            return "error";
        }
    }

    // 删除使用者
    @DeleteMapping("/api/user/{id}")
    public String deleteUser(@PathVariable int id) {
        if (userService.delete(id)) {
            return "success";
        } else {
            return "error";
        }
    }

    // 更新使用者資訊
    @PutMapping("/api/user/{id}")
    public String updateUser(@PathVariable int id, @RequestBody User user) {
        if (userService.update(id, user)) {
            return "success";
        } else {
            return "error";
        }
    }
}
           

Vue前端頁面:

<template>
  <div>
    <h2>User List</h2>
    <table>
      <thead>
        <tr>
          <th>Username</th>
          <th>Password</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in userList" :key="user.id">
          <td>{{user.username}}</td>
          <td>{{user.password}}</td>
        </tr>
      </tbody>
    </table>
    <h2>Add User</h2>
    <form>
      <label>Username:</label>
      <input type="text" v-model="newUser.username" />
      <label>Password:</label>
      <input type="text" v-model="newUser.password" />
      <button type="button" @click.prevent="addNewUser">Submit</button>
    </form>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "UserManagement",
  data() {
    return {
      userList: [],
      newUser: {
        username: "",
        password: "",
      },
    };
  },
  mounted() {
    // get user list
    axios
      .get("/api/users")
      .then((response) => (this.userList = response.data))
      .catch((error) => console.log(error));
  },
  methods: {
    addNewUser() {
      axios
        .post("/api/user", this.newUser)
        .then((response) => {
          if (response.data === "success") {
            window.location.reload();
          }
        })
        .catch((error) => console.log(error));
    },
  },
};
</script>           

繼續閱讀