iT邦幫忙

0

Spring Boot 前後端問題

  • 分享至 

  • xImage

我正在用Spring boot做一個簡易的註冊登入網頁
但我這學期才第一次接觸spring boot 和 用java 連資料庫 還有java script
所以不知道這個Spring boot 是怎麼運作和那個annotation 的功能
我只知道POST GET 這兩個method是幹嘛的
學校什麼資料庫、資料結構、網頁開發教的東東都沒用到啊

然後我是以老師的程式為例子 加上 看網路上的資料拼拼湊湊出 我的程式

/images/emoticon/emoticon02.gif

我的問題是我資料傳不進我的資料庫

以下是我的程式碼
html

<!DOCTYPE html>
<html lang="en">
<head>
    <!--Required meta tags-->
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">

   <!-- Bootstrap CSS-->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <title>Register Page</title>
</head>
<body>
<form  method="post">
    使用者名稱:<input type="text" id = "username" name="username"><br>
    密碼:<input type="password" id = "password" name="password"><br>
    <button type="button" id="register">註冊</button>>
    <br>

</form>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

 <!--Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
        crossorigin="anonymous"></script>

<script>
      $('#register').click(function() {
        $.ajax({
            // The URL for the request
          url: "register",

          // Whether this is a POST or GET request
          type: "POST",

          data : { "username" : $("#username").val() ,"password" : $("#password").val()   },
          
          dataType : "json",
        })
        
      });
</script>

Controller程式

package fcu.fcu.controller;

import fcu.fcu.model.account;
import fcu.fcu.service.accountRegister;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;


@RestController
public class accountController {
    @Autowired
    accountRegister accountRegisterManager;

    private int num=1;

    @ResponseBody
    @RequestMapping("/register")
    public void PostData(@PathVariable("username")String username, @PathVariable("password")String password){
        account account1 = new account(num,username,password);
        accountRegisterManager.insertAccount(account1);
        num++;
        return;
    }

}

service 程式

package fcu.fcu.service;
import fcu.fcu.database.Sql2oDbHandler;
import fcu.fcu.model.account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.sql2o.Connection;
import java.util.List;
@Service
public class accountRegister {

    @Autowired
    private Sql2oDbHandler sql2oDbHandler;
    private account account;
    public accountRegister() {

    }

    public void insertAccount(account account){
        String insertQuery =
                "INSERT INTO account (Account_ID, User_name, User_password) " +
                 "VALUES (:id, :name, :user_password)";
        try (Connection con = sql2oDbHandler.getConnector().beginTransaction()) {
            con.createQuery(insertQuery)
                    .addParameter("id", account.getID())
                    .addParameter("name", account.getUName())
                    .addParameter("password", account.getPassword())
                    .executeUpdate();
            // Remember to call commit() when a transaction is opened,
            // default is to roll back.

        }

    }
}

然後資料庫是可以連接成功的 我確定
因為老師的程式可以連 資料庫部分我完全照抄

請教網上大神/images/emoticon/emoticon41.gif

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
海綿寶寶
iT邦大神 1 級 ‧ 2021-12-17 11:23:07

// Remember to call commit() when a transaction is opened,
// default is to roll back.

先補個 commit() 看看結果是否正確

如果仍不正確
就要分段找問題
Controller 是否有接收到資料?
1.沒有,是 Controller / HTML 的問題
2.有,就是 service 寫資料庫的問題

OscarCS iT邦新手 5 級 ‧ 2021-12-17 23:24:11 檢舉

1
呃 我現在出現了一個500 status 但我去查500是什麼意思 網路有人說前端問題也有說是後端問題0.0
不過我不知道有沒有傳進controller誒

500 通常是後端問題(server internal error)

OscarCS iT邦新手 5 級 ‧ 2021-12-23 17:00:41 檢舉

我找到問題啦 謝謝你幫我看 結果是資料庫打錯一個字母 我吐了

0
summer78520
iT邦見習生 ‧ 2021-12-19 16:59:18

用這個方式post到後端試試看

<form action="/register" method="post">
    使用者名稱:<input type="text" id = "username" name="username"><br>
    密碼:<input type="password" id = "password" name="password"><br>
    <button type="submit" >註冊</button>>
    <br>

</form>
@Controller
public class accountController {
    @Autowired
    accountRegister accountRegisterManager;

    private int num=1;

    @RequestMapping("/register", method=RequestMethod.POST)
    public void PostData(@RequestParam("username")String username, @RequestParam("password")String password){
        account account1 = new account(num,username,password);
        accountRegisterManager.insertAccount(account1);
        num++;
        return;
    }

}
OscarCS iT邦新手 5 級 ‧ 2021-12-23 16:59:53 檢舉

謝謝你抽空幫我看 雖然我最後不是用你這個方式但還是非常感謝你

OscarCS iT邦新手 5 級 ‧ 2021-12-23 17:05:39 檢舉

借你的回答貼程式哦
register.html


<!DOCTYPE html>
<html lang="en">
<head>
    <!--Required meta tags-->
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">

   <!-- Bootstrap CSS-->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <title>Register Page</title>
</head>
<body>
<form  id="register" method="post">
    使用者名稱:<input type="text" id= "username" name = "username" ><br>
    密碼:<input type="password" id= "password" name = "password" ><br>
    <button type="button"  id= "button_register" name="register" class = "register" >註冊</button>
    <br>

</form>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

 <!--Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
        crossorigin="anonymous"></script>

<script>


      $('#button_register').click(function(){


        console.log($('#username').val());
        console.log($('#password').val());

        $.ajax({
            // The URL for the request
          url: "/register",

          // Whether this is a POST or GET request
          type: "POST",

          data : {username:$('#username').val(),password:$('#password').val()} ,

          dataType : "json",

          error: function () {
            console.log("fail");
          },
          success: function () {
            console.log("ok");
          },

        });
      });
</script>

accountController.java

package fcu.fcu.controller;

import fcu.fcu.model.account;
import fcu.fcu.service.accountRegister;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;


@RestController
public class accountController {
    @Autowired
    accountRegister accountRegisterManager;




    @PostMapping("/register")
    public void PostData(@RequestParam("username")String username, @RequestParam("password")String password){
        accountRegisterManager.insertAccount(username,password);

        return;
    }



}

accountRegister.java

package fcu.fcu.service;
import fcu.fcu.database.Sql2oDbHandler;
import fcu.fcu.model.account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.sql2o.*;
import java.util.List;
@Service
public class accountRegister {

    @Autowired
    private Sql2oDbHandler sql2oDbHandler;
    private account account;
    public accountRegister() {

    }

    public void insertAccount( String username, String password){
        String insertQuery =
                "INSERT INTO account ( User_name, User_password) "

                + "VALUES (:name, :user_password)";
        try (Connection con = sql2oDbHandler.getConnector().open()) {
            con.createQuery(insertQuery)
                    .addParameter("name",username )//account.getUName()
                    .addParameter("user_password",password) //account.getPassword()
                    .executeUpdate();
            // Remember to call commit() when a transaction is opened,
            // default is to roll back.
            //con.commit();
        }

    }
}

這是我程式最後長的模樣
現在我要來寫登入啦感謝有回答我的人

我要發表回答

立即登入回答