結合 AngularJS 的 MVVM 雙向綁定與 Groovy 的動態語言優勢(基於 Spark 微框架),快速構建一個前後端分離的登錄 Demo。適合原型驗證、內部工具、Serverless 函數改造場景。
<!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>
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 || '請求失敗';
});
};
});
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, '用戶名或密碼錯誤')
}
}
}
}
CREATE TABLE test_user (username VARCHAR(50), password VARCHAR(50)); 插入測試數據。Application.groovy → Run。https://localhost:9090/index.html。![]()
圖示:瀏覽器 → AngularJS Controller → $http.post → Spark Router → Groovy SQL → SQL Server → 返回 JSON → AngularJS 更新 View
@Valid / 手動校驗,防止 XSS/SQL 注入。