gpt4 book ai didi

java - 调试 AngularJS + Spring MVC + Tomcat Web 应用程序

转载 作者:行者123 更新时间:2023-11-28 22:27:09 25 4
gpt4 key购买 nike

我从事 Java Web 开发的日子已经过去了大约 6 年,尽管我作为一名非技术顾问开始了忙碌的新生活,但我还是想回到技术领域并为自己配备一些基本的 Web 开发技能。

为了让我开始,我使用本教程安装了一个 vagrant box: https://dzone.com/articles/vagrant

... 效果很好,让我的 Ubuntu 盒子在我的 Windows 主机上立即启动并运行。它还附带了 Java 7 和 Tomcat 应用程序服务器,我在过去的日子里仍然非常熟悉。尽管可能有更好的服务器可供练习,但这台服务器仍然有效,我现在将使用它进行修补。本教程附带的示例 Web 应用程序也可以运行,因此我确信我的 Tomcat 正在客户机上的端口 8080 上运行。

下一步是找到一个好的 AngularJS 和 Spring MVC 教程。再一次,虽然我知道 AngularJS 是 Web 开发中的最新热潮,但 Spring MVC 可能有点过时(?)但是因为我是一个 Java 男孩,因为我是从 Uni-egg 孵化出来的,所以我不介意使用它现在。

我找到的教程是这个: http://websystique.com/springmvc/spring-mvc-4-angularjs-example/

我从 git 下载项目并将其部署到我的 tomcat webapps 文件夹中。在 user_service.js 文件中,我将 REST_SERVICE_URI 保留为 http://localhost:8080/Spring4MVCAngularJSExample/user/鉴于 Tomcat 在主机 Ubuntu 机器上的端口 8080 上运行,我可以在浏览器中访问客户机上的应用程序 http://192.168.33.10:8080/Spring4MVCAngularJSExample

问题是应用程序(当它显示在浏览器中时)不会加载 UserServiceImpl 类中填充的模拟用户,并且应该在加载应用程序时显示。当我在 JavaScript 选项卡下检查我的 Firefox 控制台时,我从 user_controller.js 脚本中的 fetchAllUsers 函数收到“获取用户时出错”错误消息。

我怀疑这里的问题是前端(AngularJS $http服务)联系不上后端(Spring服务)。如果后端没有用户并返回 0,我就不会得到错误而是一个空集,因此我怀疑其他问题。

我的问题是如何从这里调试这个网络应用程序?我尝试使用 FF Developer 工具(调试器)查看前端控制台日志,我必须承认我没有编写任何 JUnit 测试来实际运行针对 Spring 服务实现类的测试。

感谢您的建议,如果我需要提供更多详细信息,请告诉我。

干杯阿尔法

Spring Controller :

    package com.websystique.springmvc.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.websystique.springmvc.model.User;
import com.websystique.springmvc.service.UserService;

@RestController
public class HelloWorldRestController {

@Autowired
UserService userService; //Service which will do all data retrieval/manipulation work


//-------------------Retrieve All Users--------------------------------------------------------

@RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> listAllUsers() {
List<User> users = userService.findAllUsers();
if(users.isEmpty()){
return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}



//-------------------Retrieve Single User--------------------------------------------------------

@RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> getUser(@PathVariable("id") long id) {
System.out.println("Fetching User with id " + id);
User user = userService.findById(id);
if (user == null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}



//-------------------Create a User--------------------------------------------------------

@RequestMapping(value = "/user/", method = RequestMethod.POST)
public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder) {
System.out.println("Creating User " + user.getUsername());

if (userService.isUserExist(user)) {
System.out.println("A User with name " + user.getUsername() + " already exist");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}

userService.saveUser(user);

HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}



//------------------- Update a User --------------------------------------------------------

@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
public ResponseEntity<User> updateUser(@PathVariable("id") long id, @RequestBody User user) {
System.out.println("Updating User " + id);

User currentUser = userService.findById(id);

if (currentUser==null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}

currentUser.setUsername(user.getUsername());
currentUser.setAddress(user.getAddress());
currentUser.setEmail(user.getEmail());

userService.updateUser(currentUser);
return new ResponseEntity<User>(currentUser, HttpStatus.OK);
}



//------------------- Delete a User --------------------------------------------------------

@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public ResponseEntity<User> deleteUser(@PathVariable("id") long id) {
System.out.println("Fetching & Deleting User with id " + id);

User user = userService.findById(id);
if (user == null) {
System.out.println("Unable to delete. User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}

userService.deleteUserById(id);
return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
}



//------------------- Delete All Users --------------------------------------------------------

@RequestMapping(value = "/user/", method = RequestMethod.DELETE)
public ResponseEntity<User> deleteAllUsers() {
System.out.println("Deleting All Users");

userService.deleteAllUsers();
return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
}

}

索引 Controller .java:

package com.websystique.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/")
public class IndexController {

@RequestMapping(method = RequestMethod.GET)
public String getIndexPage() {
return "UserManagement";
}

}

Javascript user_controller.js:

    'use strict';

angular.module('myApp').controller('UserController', ['$scope', 'UserService', function($scope, UserService) {
var self = this;
self.user={id:null,username:'',address:'',email:''};
self.users=[];

self.submit = submit;
self.edit = edit;
self.remove = remove;
self.reset = reset;


fetchAllUsers();

function fetchAllUsers(){
UserService.fetchAllUsers()
.then(
function(d) {
self.users = d;
},
function(errResponse){
console.error('Error while fetching Users');
}
);
}

function createUser(user){
UserService.createUser(user)
.then(
fetchAllUsers,
function(errResponse){
console.error('Error while creating User');
}
);
}

function updateUser(user, id){
UserService.updateUser(user, id)
.then(
fetchAllUsers,
function(errResponse){
console.error('Error while updating User');
}
);
}

function deleteUser(id){
UserService.deleteUser(id)
.then(
fetchAllUsers,
function(errResponse){
console.error('Error while deleting User');
}
);
}

function submit() {
if(self.user.id===null){
console.log('Saving New User', self.user);
createUser(self.user);
}else{
updateUser(self.user, self.user.id);
console.log('User updated with id ', self.user.id);
}
reset();
}

function edit(id){
console.log('id to be edited', id);
for(var i = 0; i < self.users.length; i++){
if(self.users[i].id === id) {
self.user = angular.copy(self.users[i]);
break;
}
}
}

function remove(id){
console.log('id to be deleted', id);
if(self.user.id === id) {//clean form if the user to be deleted is shown there.
reset();
}
deleteUser(id);
}


function reset(){
self.user={id:null,username:'',address:'',email:''};
$scope.myForm.$setPristine(); //reset Form
}

}]);

Javascript user_service.js:

    'use strict';

angular.module('myApp').factory('UserService', ['$http', '$q', function($http, $q){

var REST_SERVICE_URI = 'http://localhost:8080/Spring4MVCAngularJSExample/user/';

var factory = {
fetchAllUsers: fetchAllUsers,
createUser: createUser,
updateUser:updateUser,
deleteUser:deleteUser
};

return factory;

function fetchAllUsers() {
var deferred = $q.defer();
$http.get(REST_SERVICE_URI)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while fetching Users');
deferred.reject(errResponse);
}
);
return deferred.promise;
}

function createUser(user) {
var deferred = $q.defer();
$http.post(REST_SERVICE_URI, user)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while creating User');
deferred.reject(errResponse);
}
);
return deferred.promise;
}


function updateUser(user, id) {
var deferred = $q.defer();
$http.put(REST_SERVICE_URI+id, user)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while updating User');
deferred.reject(errResponse);
}
);
return deferred.promise;
}

function deleteUser(id) {
var deferred = $q.defer();
$http.delete(REST_SERVICE_URI+id)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while deleting User');
deferred.reject(errResponse);
}
);
return deferred.promise;
}

}]);

在服务器(vagrant 主机)上,我可以 wget URL 并从 Spring 服务器取回我的数据:

    vagrant@precise32:~$ wget http://localhost:8080/Spring4MVCAngularJSExample/user/--2016-08-26 11:08:24--  http://localhost:8080/Spring4MVCAngularJSExample/user/
Resolving localhost (localhost)... 127.0.0.1
Connecting to localhost (localhost)|127.0.0.1|:8080... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [application/json]
Saving to: `index.html'

[ <=> ] 206 --.-K/s in 0s

2016-08-26 11:08:24 (9.77 MB/s) - `index.html' saved [206]

vagrant@precise32:~$ less index.html

这给了我预期的结果集:

[{"id":1,"username":"Sam","address":"NY","email":"sam@abc.com"},{"id":2,"username":"Tomy","address":"ALBAMA","email":"tomy@abc.com"},{"id":3,"username":"Kelly","address":"NEBRASKA","email":"kelly@abc.com"}]

最佳答案

从您的 spring Controller 代码中,您所有的请求映射都需要 url 中的用户,因此如果您没有这个,则不会调用 spring Controller 。您是否将调度程序 servlet 设置为排除所有 http 请求,例如/

关于java - 调试 AngularJS + Spring MVC + Tomcat Web 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39155932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com