首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

全棧實戰:HTML + AngularJS + Groovy 實現輕量級登錄系統

     編輯:Java 綜合教學

全棧實戰:HTML + AngularJS + Groovy 實現輕量級登錄系統

結合 AngularJS 的 MVVM 雙向綁定與 Groovy 的動態語言優勢(基於 Spark 微框架),快速構建一個前後端分離的登錄 Demo。適合原型驗證、內部工具、Serverless 函數改造場景。

技術棧

  • 前端:AngularJS 1.4.6 + Bootstrap 3.3.4(CDN 引入)
  • 後端:Groovy 2.x + Spark Java 2.x(內嵌 Jetty)
  • 數據庫:SQL Server (JTDS 驅動) / 可換任意 JDBC 支持數據庫

前端:index.html(聲明式模板)

<!DOCTYPE html>
<html ng-app="app" lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>登錄系統</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
    <script src="scripts/app.js"></script>
</head>
<body ng-controller="LoginController">
    <div class="container" style="margin-top: 50px; max-width: 400px;">
        <form ng-submit="login()" class="form-horizontal">
            <div class="form-group">
                <label class="col-sm-3 control-label">用戶名</label>
                <div class="col-sm-9">
                    <input type="text" class="form-control" ng-model="user.username" placeholder="請輸入用戶名" required>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">密碼</label>
                <div class="col-sm-9">
                    <input type="password" class="form-control" ng-model="user.password" placeholder="請輸入密碼" required>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-3 col-sm-9 text-danger">{{info}}</div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-3 col-sm-9">
                    <button type="submit" class="btn btn-primary btn-block">登錄</button>
                </div>
            </div>
        </form>
    </div>
</body>
</html>

前端邏輯:scripts/app.js(AngularJS 模塊)

angular.module('app', [])
.controller('LoginController', function($scope, $http) {
    $scope.user = {};
    $scope.info = '歡迎登錄';

    $scope.login = function() {
        console.log('提交數據:', $scope.user);
        $http.post('/login', $scope.user)
            .then(function(res) {
                console.log('響應:', res.data);
                if (res.status === 200) {
                    alert('登錄成功');
                    // window.location.href = '/dashboard'; // 跳轉
                }
            }, function(reason) {
                $scope.info = reason.data || '請求失敗';
            });
    };
});

後端:Application.groovy(Spark 路由 + Groovy SQL)

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
import groovy.sql.Sql
import static spark.Spark.*

class Application {
    static JsonSlurper jsonSlurper = new JsonSlurper()
    static Sql db = Sql.newInstance(
        "jdbc:jtds:sqlserver://127.0.0.1:1433/lrtest;instance=sql2008",
        "username", "password",
        "net.sourceforge.jtds.jdbc.Driver"
    )

    static void main(String[] args) {
        port(9090)
        staticFileLocation("/static")  // 靜態資源目錄 src/main/resources/static

        get("/hello") { req, res -> "Hello World" }

        post("/login") { req, res ->
            println "請求體: ${req.body()}"
            def user = jsonSlurper.parseText(req.body())
            println "解析用戶: $user"

            // 參數化查詢防注入
            def row = db.firstRow(
                "SELECT * FROM test_user WHERE username = ? AND password = ?",
                [user.username, user.password]
            )

            if (row) {
                halt(200, new JsonBuilder(row).toString())
            } else {
                halt(400, '用戶名或密碼錯誤')
            }
        }
    }
}

運行與驗證

  1. 確保數據庫建表:CREATE TABLE test_user (username VARCHAR(50), password VARCHAR(50)); 插入測試數據。
  2. IDEA 安裝 Groovy 插件,右鍵 Application.groovy → Run。
  3. 瀏覽器訪問 https://localhost:9090/index.html。
  4. 輸入正確憑證 → 彈窗「登錄成功」;錯誤憑證 → 顯示「用戶名或密碼錯誤」。

架構關係圖解

AngularJS + Groovy 登錄架構圖

圖示:瀏覽器 → AngularJS Controller → $http.post → Spark Router → Groovy SQL → SQL Server → 返回 JSON → AngularJS 更新 View

優化與擴展方向

  • 密碼加密:前端/後端雙端 BCrypt/Argon2 加密,禁止明文存儲/傳輸。
  • JWT Token:登錄成功返回 JWT,後續請求攜帶 Authorization Header,實現無狀態認證。
  • 輸入驗證:後端加入 @Valid / 手動校驗,防止 XSS/SQL 注入。
  • 靜態資源分離:生產環境前端構建產物部署至 Nginx/CDN,後端純 API 服務。
  • 遷移至 Spring Boot + Vue/React:企業級項目建議使用成熟生態棧。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved