最近想学习AngularJS的使用,网上搜了一圈后,折腾了半天解决bug后,成功使用AngularJS整合Springmvc、Spring、Mybatis搭建了一个开发环境。(这里Spring使用的版本是4.0.6,Mybatis版本是3.2.5,AngularJS的版本是1.0.3)
第一步:创建一Maven项目,在pom.xml下添加需要的包
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://.hin.service.UserService; @Controller @RequestMapping("/users") public class UserController { @Resource private UserService userService; @RequestMapping("/userlist.json") public @ResponseBody List<User> getUserList() { return userService.getAllUsers(); } @RequestMapping(value = "/addUser/{userName}", method = RequestMethod.POST) public @ResponseBody void addUser(@PathVariable("userName") String userName) { userService.addUser(userName); } @RequestMapping(value = "/removeUser/{userName}", method = RequestMethod.DELETE) public @ResponseBody void removeUser(@PathVariable("userName") String userName) { userService.deleteUser(userName); } @RequestMapping(value = "/removeAllUsers", method = RequestMethod.DELETE) public @ResponseBody void removeAllUsers() { userService.deleteAll(); } @RequestMapping("/layout") public String getUserPartialPage() { return "users/layout"; } }
第四步:引入angular的js文件,如下:
这里使用Angular来实现添加用户与删除用户功能主要是UserController.js,如下:
'use strict'; /** * UserController */ var UserController = function($scope, $http) { $scope.fetchUsersList = function() { $http.get('users/userlist.json').success(function(userList){ $scope.users = userList; }); }; $scope.addNewUser = function(newUser) { $http.post('users/addUser/' + newUser).success(function() { $scope.fetchUsersList(); }); $scope.userName = ''; }; $scope.removeUser = function(user) { $http.delete('users/removeUser/' + user).success(function() { $scope.fetchUsersList(); }); }; $scope.removeAllUsers = function() { $http.delete('users/removeAllUsers').success(function() { $scope.fetchUsersList(); }); }; $scope.fetchUsersList(); };
关于Angular的其他文件具体可看源码,最后再右键项目,Run as,Maven install,再发布到Tomcat下就可以看到效果了,如下:
AngularJS整合Springmvc、Spring、Mybatis搭建开发环境就完成了,希望对大家的学习有所帮助。