使用 java 和 angularjs 的网络应用程序
Web app using java and angularjs
我正在尝试创建简单的市场 Web 应用程序。我想添加一个登录功能以在我的数据库中添加用户,但我不明白,我如何在 js 脚本中 "call" 我的注册方法(来自 java)。目前,我的网络应用程序实际做的唯一一件事是显示来自用户的记录(我手动添加的)-table.
这是我的数据库管理器:
`public class DatabaseManager {
public static String host = "localhost";
public static String port = "5432";
public static String dbname = "market";
public static String user = "postgres";
public static String pass = "123456";
public static String url = "jdbc:postgresql://"+host+":"+port+"/"+dbname+"?user="+user+"&password="+pass;
static {
try {
DriverManager.registerDriver(new org.postgresql.Driver());
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
try {
return DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Can not connect to the database:\n"+e.getMessage());
}
return null;
}
public static void closeConnection(Connection connection) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}`
授权-dto:
public class Auth {
public static class RegisterReq {
public String name;
public String lastname;
public String login;
public String pass;
public int age;
public String gender;
public RegisterReq(String name, String lastname, String login, String pass, int age, String gender) {
this.name = name;
this.lastname = lastname;
this.login = login;
this.pass = pass;
this.age = age;
this.gender = gender;
}
}
public static class RegisterResp {
public boolean status;
public RegisterResp(boolean status) {
this.status = status;
}
}
public static class LoginReq {
public String login;
public String pass;
public LoginReq(String login, String pass) {
this.login = login;
this.pass = pass;
}
}
public static class LoginResp {
public boolean status;
public LoginResp(boolean status) {
this.status = status;
}
}
}
Auth-class 注册方法:
`
import static dto.Auth.*;
@Path("/auth")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class Auth {
@POST
@Path("/register")
public RegisterResp register(RegisterReq req) {
boolean result = false;
//sql
Connection connection = null;
try {
connection = DatabaseManager.getConnection();
Statement stmt = connection.createStatement();
String checkSql = "select e_mail from users";
ResultSet resultSet=stmt.executeQuery(checkSql);
while (resultSet.next()) {
if(req.login.equals(resultSet.getString(1))) return new RegisterResp(result);
}
//unsafe query
String sql = "INSERT INTO users" +
" (u_name, u_lastname, e_mail, password, age, gender, reg_date)" +
" VALUES (" +
req.name + ","+
req.lastname + ","+
req.login + ","+
req.pass + "," +
req.age + ","+
req.gender + ","+
new java.sql.Timestamp(new java.util.Date().getTime()) + ")";
result = stmt.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) DatabaseManager.closeConnection(connection);
}
return new RegisterResp(result);
}`
主页HTML文件:
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>Market start page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="./resources/css/app.css">
</head>
<body ng-controller="UserController">
<div style="background: #8fb9ee" class="jumbotron">
<h1>Market homepage</h1>
<h2>Welcome!</h2>
<p align="center">
<a href="#/register" style="background: sandybrown" class="btn btn-primary btn-lg" role="button">Register</a>
<a href="#/login" style="background: #606cf4" class="btn btn-primary btn-lg" role="button">Log in</a>
</p>
</div>
<hr>
<div >
<ul>
<p style="font-size: xx-large" >Total user count: {{users.length}} </p>
<table class="TableStyle">
<tr class="RowHeaderStyle">
<th >Firstname</th>
<th >Lastname</th>
<th >E-mail</th>
<th >Age</th>
<th >Gender</th>
</tr>
<tr ng-repeat="user in users" class="RowStyle">
<td >{{user.name}}</td>
<td >{{user.lastname}}</td>
<td >{{user.e_mail}}</td>
<td >{{user.age}}</td>
<td >{{user.gender}}</td>
</tr>
</table>
</ul>
</div>
<input type="checkbox" ng-model="value"> admin ?
<div ng-if="value">Admin</div>
<div ng-if="!value">User</div>
<div ng-view></div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-resource.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-route.js"></script>
<script src="./resources/js/app.js"></script>
</body>
</html>
注册HTML-文件:
<h2>Register</h2>
<div ng-controller="RegisterController" align="center" class="container-fluid">
<table >
<tr>
<td>First name</td>
<td><input type="text" ng-model="fname"></td>
</tr>
<tr>
<td>Last name</td>
<td><input type="text" ng-model="lname"></td>
</tr>
<tr>
<td>E-mail</td>
<td><input type="text" ng-model="uemail"></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="text" ng-model="upass"></td>
</tr>
<tr>
<td>Gender</td>
<td>
<select ng-model="ugend" >
<option>male</option>
<option>female</option>
</select>
</td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" ng-model="uage"></td>
</tr>
</table>
<button role="button" ng-click="AddUser()"> Confirm </button>
</div>
我愚蠢地尝试做一些事情的应用程序 JS 文件:
`angular.module('app', ['ngResource', 'ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: './resources/partials/login.html',
controller: 'RegisterController'
}).
when('/register', {
templateUrl: './resources/partials/register.html',
controller: 'LoginController'
}).
otherwise({
redirectTo: '/'
});
}])
.controller('UserController', ['$scope', '$resource', function($scope, $resource) {
var User = $resource('/r/users');
var users = User.query(function() {
$scope.users = users;
});
}])
.controller('LoginController', ['$scope', '$resource', function($scope, $resource) {
}])
.controller('RegisterController', ['$scope', '$resource',"$http", function($scope,$http, $resource) {
//here should be something smart
$scope.AddUser = function() {
};
}]);`
我在 Intellij 工作,这是我第一次尝试做某事,所以不要打我=)。
如果我理解你的问题正确。解决此问题的一种方法是创建一个 angular 服务来执行 ajax post 粘贴来自当前 spring-boot angular 应用程序即时消息的示例发展中。我使用的是 es6 但概念是一样的
这里是服务的一个片段
class UserService
{
constructor($http)
{
HTTP.set(this, $http);
}
// getGroups(groupId){
// return HTTP.get(this).get(`/api/v1/group/group/?id=${groupId}`).then(result => result.data.objects );
// }
//
// createUserInGroup(groupId,user){
// return HTTP.get(this).post(`/api/v1/group/user/${groupId}`,user);
// }
updateUser(userId,user){
return HTTP.get(this).put(`/api/v1/user/${userId}`, user);
}
你可以告诉我注入 $http angular 对象来执行请求,如果你决定做一个服务,你将不得不做同样的事情
在控制器中,我正在注入服务
class NewGroupController{
constructor($timeout,$modalInstance, groupSvc,currentGroup){
GROUP_SERVICE.set(this, groupSvc);
MODAL_INSTANCE.set(this,$modalInstance);
TIMEOUT.set(this, $timeout);
CURRENT_GROUP.set(this,currentGroup);
借助组服务,我可以调用该方法,仅此而已。
希望对您有所帮助
大致上,您的 RegisterController 应该如下所示:
.controller('RegisterController', ['$scope', '$resource', function($scope, $resource) {
var auth = $resource('/auth/:action', null, {
login: {
method: 'POST',
params: {
action: 'login'
},
},
register: {
method: 'POST',
params: {
action: 'register'
}
}
});
$scope.AddUser = function() {
// your data consumed from UI
var data = {
name: $scope.name
lastname: $scope.lastname,
login: $scope.login,
pass: $scope.pass,
age: $scope.age,
gender: $scope.gender
};
auth.register(null, data, function(resp) {
// your callback when response is received
// resp variable contains response data sent from server
if (resp.status) {
// registered successfully
} else {
// some error occurred
}
});
};
}]);
我正在尝试创建简单的市场 Web 应用程序。我想添加一个登录功能以在我的数据库中添加用户,但我不明白,我如何在 js 脚本中 "call" 我的注册方法(来自 java)。目前,我的网络应用程序实际做的唯一一件事是显示来自用户的记录(我手动添加的)-table.
这是我的数据库管理器:
`public class DatabaseManager {
public static String host = "localhost";
public static String port = "5432";
public static String dbname = "market";
public static String user = "postgres";
public static String pass = "123456";
public static String url = "jdbc:postgresql://"+host+":"+port+"/"+dbname+"?user="+user+"&password="+pass;
static {
try {
DriverManager.registerDriver(new org.postgresql.Driver());
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
try {
return DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Can not connect to the database:\n"+e.getMessage());
}
return null;
}
public static void closeConnection(Connection connection) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}`
授权-dto:
public class Auth {
public static class RegisterReq {
public String name;
public String lastname;
public String login;
public String pass;
public int age;
public String gender;
public RegisterReq(String name, String lastname, String login, String pass, int age, String gender) {
this.name = name;
this.lastname = lastname;
this.login = login;
this.pass = pass;
this.age = age;
this.gender = gender;
}
}
public static class RegisterResp {
public boolean status;
public RegisterResp(boolean status) {
this.status = status;
}
}
public static class LoginReq {
public String login;
public String pass;
public LoginReq(String login, String pass) {
this.login = login;
this.pass = pass;
}
}
public static class LoginResp {
public boolean status;
public LoginResp(boolean status) {
this.status = status;
}
}
}
Auth-class 注册方法: `
import static dto.Auth.*;
@Path("/auth")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class Auth {
@POST
@Path("/register")
public RegisterResp register(RegisterReq req) {
boolean result = false;
//sql
Connection connection = null;
try {
connection = DatabaseManager.getConnection();
Statement stmt = connection.createStatement();
String checkSql = "select e_mail from users";
ResultSet resultSet=stmt.executeQuery(checkSql);
while (resultSet.next()) {
if(req.login.equals(resultSet.getString(1))) return new RegisterResp(result);
}
//unsafe query
String sql = "INSERT INTO users" +
" (u_name, u_lastname, e_mail, password, age, gender, reg_date)" +
" VALUES (" +
req.name + ","+
req.lastname + ","+
req.login + ","+
req.pass + "," +
req.age + ","+
req.gender + ","+
new java.sql.Timestamp(new java.util.Date().getTime()) + ")";
result = stmt.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) DatabaseManager.closeConnection(connection);
}
return new RegisterResp(result);
}`
主页HTML文件:
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>Market start page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="./resources/css/app.css">
</head>
<body ng-controller="UserController">
<div style="background: #8fb9ee" class="jumbotron">
<h1>Market homepage</h1>
<h2>Welcome!</h2>
<p align="center">
<a href="#/register" style="background: sandybrown" class="btn btn-primary btn-lg" role="button">Register</a>
<a href="#/login" style="background: #606cf4" class="btn btn-primary btn-lg" role="button">Log in</a>
</p>
</div>
<hr>
<div >
<ul>
<p style="font-size: xx-large" >Total user count: {{users.length}} </p>
<table class="TableStyle">
<tr class="RowHeaderStyle">
<th >Firstname</th>
<th >Lastname</th>
<th >E-mail</th>
<th >Age</th>
<th >Gender</th>
</tr>
<tr ng-repeat="user in users" class="RowStyle">
<td >{{user.name}}</td>
<td >{{user.lastname}}</td>
<td >{{user.e_mail}}</td>
<td >{{user.age}}</td>
<td >{{user.gender}}</td>
</tr>
</table>
</ul>
</div>
<input type="checkbox" ng-model="value"> admin ?
<div ng-if="value">Admin</div>
<div ng-if="!value">User</div>
<div ng-view></div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-resource.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-route.js"></script>
<script src="./resources/js/app.js"></script>
</body>
</html>
注册HTML-文件:
<h2>Register</h2>
<div ng-controller="RegisterController" align="center" class="container-fluid">
<table >
<tr>
<td>First name</td>
<td><input type="text" ng-model="fname"></td>
</tr>
<tr>
<td>Last name</td>
<td><input type="text" ng-model="lname"></td>
</tr>
<tr>
<td>E-mail</td>
<td><input type="text" ng-model="uemail"></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="text" ng-model="upass"></td>
</tr>
<tr>
<td>Gender</td>
<td>
<select ng-model="ugend" >
<option>male</option>
<option>female</option>
</select>
</td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" ng-model="uage"></td>
</tr>
</table>
<button role="button" ng-click="AddUser()"> Confirm </button>
</div>
我愚蠢地尝试做一些事情的应用程序 JS 文件:
`angular.module('app', ['ngResource', 'ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: './resources/partials/login.html',
controller: 'RegisterController'
}).
when('/register', {
templateUrl: './resources/partials/register.html',
controller: 'LoginController'
}).
otherwise({
redirectTo: '/'
});
}])
.controller('UserController', ['$scope', '$resource', function($scope, $resource) {
var User = $resource('/r/users');
var users = User.query(function() {
$scope.users = users;
});
}])
.controller('LoginController', ['$scope', '$resource', function($scope, $resource) {
}])
.controller('RegisterController', ['$scope', '$resource',"$http", function($scope,$http, $resource) {
//here should be something smart
$scope.AddUser = function() {
};
}]);`
我在 Intellij 工作,这是我第一次尝试做某事,所以不要打我=)。
如果我理解你的问题正确。解决此问题的一种方法是创建一个 angular 服务来执行 ajax post 粘贴来自当前 spring-boot angular 应用程序即时消息的示例发展中。我使用的是 es6 但概念是一样的
这里是服务的一个片段
class UserService
{
constructor($http)
{
HTTP.set(this, $http);
}
// getGroups(groupId){
// return HTTP.get(this).get(`/api/v1/group/group/?id=${groupId}`).then(result => result.data.objects );
// }
//
// createUserInGroup(groupId,user){
// return HTTP.get(this).post(`/api/v1/group/user/${groupId}`,user);
// }
updateUser(userId,user){
return HTTP.get(this).put(`/api/v1/user/${userId}`, user);
}
你可以告诉我注入 $http angular 对象来执行请求,如果你决定做一个服务,你将不得不做同样的事情
在控制器中,我正在注入服务
class NewGroupController{
constructor($timeout,$modalInstance, groupSvc,currentGroup){
GROUP_SERVICE.set(this, groupSvc);
MODAL_INSTANCE.set(this,$modalInstance);
TIMEOUT.set(this, $timeout);
CURRENT_GROUP.set(this,currentGroup);
借助组服务,我可以调用该方法,仅此而已。
希望对您有所帮助
大致上,您的 RegisterController 应该如下所示:
.controller('RegisterController', ['$scope', '$resource', function($scope, $resource) {
var auth = $resource('/auth/:action', null, {
login: {
method: 'POST',
params: {
action: 'login'
},
},
register: {
method: 'POST',
params: {
action: 'register'
}
}
});
$scope.AddUser = function() {
// your data consumed from UI
var data = {
name: $scope.name
lastname: $scope.lastname,
login: $scope.login,
pass: $scope.pass,
age: $scope.age,
gender: $scope.gender
};
auth.register(null, data, function(resp) {
// your callback when response is received
// resp variable contains response data sent from server
if (resp.status) {
// registered successfully
} else {
// some error occurred
}
});
};
}]);