angularjs與springmvc的整合(restful)

REST 指的是一組架構約束條件和原則。知足這些約束條件和原則的應用程序或設計就是RESTful。javascript

最近嘗試了一下springmvc框架和google的angularjs進行整合,發現了不少的問題,而且有不少問題沒法在網絡上找到。幸運的是最後成功把問題都調通了。那麼下面我來把本身遇到的問題總結一下。css

首先咱們要搭建咱們的springmvc框架,最初遇到的這個框架感受很高端,但其實項目的搭建是很是簡單的。多的不說先來看一下,最先加載的web.xml吧!html


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>springmvc</display-name>
    <!--配置springmvc並加載spring的xml配置文件 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml,classpath:spring/**/spring-*.xml</param-value>
            <!--<param-value>classpath:spring/spring-mvc.xml</param-value> -->
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!--配置springmvc的url訪問路徑 -->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--默認的訪問文件類型,配置後這些拓展名結尾的不被收錄爲訪問請求 -->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</url-pattern>
    </servlet-mapping>
    <!--本身寫的過濾器,可使用spring自帶的,詳細的狀況你們本身查閱一下 -->
    <!-- <filter> <filter-name>encodingFilter</filter-name> <filter-class>com.ice.springmvc.filter.MyFilter</filter-class>
        </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern>
        </filter-mapping> -->
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>



上面已經有比較詳細的註釋,我就不在這裏贅述了。不過有一點須要簡單說明一下,contextConfigLocation配置的使用了通配符的形式,這樣就咱們可使用以spring-開頭來命名spring配置文件,而且放到指定的目錄下,這樣就能夠一勞永逸了。java

下面來看一下,spring-mvc.xml的配置,這個文件的配置更加簡單,不過我在這個配置文件的研究上花費了很是多的時間。好了先看一下這個配置文件的內容吧!mysql



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--該配置爲自動掃描配置的包下全部使用@Controller註解的類 -->
    <context:component-scan base-package="com.ice.personnel.controller" />
    <!--註解驅動,使spring的controller所有生效 -->
    <mvc:annotation-driven />
    <!--跳轉頁面使用,若是不配置的話,那麼咱們springmvc返回頁面的時候,會被認爲是請求url處理,因此就沒法到達想要跳轉的頁面。這是由於web.xml裏面配置的訪問路徑爲'/'也就是全部訪問路徑都被認爲是請求url -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>




以上是這個文件的配置,基本的功能我都寫到註釋中了,若是有不明白的你們能夠在回覆中提出來。jquery

都搞定了以後咱們來看看Controller類是怎麼實現的。angularjs



package com.ice.personnel.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import org.springframework.web.util.WebUtils;
import com.ice.personnel.bean.User;
import com.ice.personnel.service.IUserService;
@Controller
@RequestMapping(value = "/user")
public class UserController {
    /**
     * 添加用戶(該方法用來測試ajax正常調用)
     *
     * @return
     */
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addUser(HttpServletRequest request,
            HttpServletResponse response) {
        User user = new User();
        user.setUsername("ice");
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            userService.saveOrUpdateUser(user);
            map.put("flag", true);
        } catch (Exception e) {
            map.put("flag", false);
        }
        return map;
    }
    /**
     * 獲取用戶列表()
     *
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/getUserList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getUserList(HttpServletRequest request,
            HttpServletResponse response) {
        String sPage = WebUtils.findParameterValue(request, "page");
        String sPageSize = request.getParameter("pageSize");
        int page = Integer.parseInt(sPage);
        int pageSize = Integer.parseInt(sPageSize);
        Map<String, Object> map = new HashMap<String, Object>();
        List<User> userList = userService.getUserList(page, pageSize);
        map.put("userList", userList);
        return map;
    }
    /**
     * 獲取用戶列表
     *
     * @return
     */
    @RequestMapping(value = "/userList", method = RequestMethod.GET)
    @ResponseBody
    public List<User> getUserList(HttpServletRequest request) {
        String sPage = WebUtils.findParameterValue(request, "page");
        String sPageSize = request.getParameter("pageSize");
        int page = Integer.parseInt(sPage);
        int pageSize = Integer.parseInt(sPageSize);
        List<User> userList = userService.getUserList(page, pageSize);
        return userList;
    }
    /**
     * 添加用戶
     *
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.PUT)
    @ResponseBody
    public List<User> addUser(@RequestBody User user, HttpServletRequest request) {
        String sPage = WebUtils.findParameterValue(request, "page");
        String sPageSize = request.getParameter("pageSize");
        int page = Integer.parseInt(sPage);
        int pageSize = Integer.parseInt(sPageSize);
        userService.saveOrUpdateUser(user);
        List<User> userList = userService.getUserList(page, pageSize);
        return userList;
    }
    /**
     * 更新用戶
     *
     * @param user
     *            前臺獲取用戶對象
     * @param request
     *            請求對象
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public List<User> updateUser(@RequestBody User user,
            HttpServletRequest request) {
        String sPage = WebUtils.findParameterValue(request, "page");
        String sPageSize = request.getParameter("pageSize");
        int page = Integer.parseInt(sPage);
        int pageSize = Integer.parseInt(sPageSize);
        userService.saveOrUpdateUser(user);
        List<User> list = userService.getUserList(page, pageSize);
        return list;
    }
    /**
     * 刪除用戶
     *
     * @param request
     *            請求對象
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    @ResponseBody
    public List<User> deleteUser(HttpServletRequest request) {
        String userId = request.getParameter("id");
        String sPage = WebUtils.findParameterValue(request, "page");
        String sPageSize = request.getParameter("pageSize");
        int page = Integer.parseInt(sPage);
        int pageSize = Integer.parseInt(sPageSize);
        User user = new User(userId);
        userService.deleteUser(user);
        List<User> list = userService.getUserList(page, pageSize);
        return list;
    }
    /**
     * 用戶業務接口
     */
    @Autowired
    private IUserService userService;
}



我這裏寫的類比較亂,由於我把全部的異常都拿到Controller這裏處理了。你們可能注意到了@ResponseBody這個能夠保證該方法的返回值爲json格式,由於我是爲了作單頁面程序才這樣作的,只作數據的交換不作頁面的跳轉,springmvc的頁面跳轉網上的教程有不少我就不介紹了。web

還有一點須要說明的是@RequestBody這個標註是爲了將前臺傳遞進來js的Object自動封裝成相應的對象。前提是屬性要一致。後臺的基本配置已經基本準備好了。ajax

還有restful我我的理解是一種思想,具體瞭解該方面的知識能夠參考百度、google等搜索引擎spring

我把User這個類也貼一下:


package com.ice.personnel.bean;
/**
 * @author ice
 *
 */
public class User {
    public User() {
    }
    public User(String id) {
        this.id = id;
    }
    /**
     * @return the id
     */
    public String getId() {
        return id;
    }
    /**
     * @param id
     *            the id to set
     */
    public void setId(String id) {
        this.id = id;
    }
    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }
    /**
     * @param username
     *            the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }
    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }
    /**
     * @param password
     *            the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }
    /**
     * @return the realname
     */
    public String getRealname() {
        return realname;
    }
    /**
     * @param realname
     *            the realname to set
     */
    public void setRealname(String realname) {
        this.realname = realname;
    }
    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }
    /**
     * @param email
     *            the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }
    /**
     * @return the address
     */
    public String getAddress() {
        return address;
    }
    /**
     * @param address
     *            the address to set
     */
    public void setAddress(String address) {
        this.address = address;
    }
    /**
     * @return the zip
     */
    public int getZip() {
        return zip;
    }
    /**
     * @param zip
     *            the zip to set
     */
    public void setZip(int zip) {
        this.zip = zip;
    }
    /**
     * @return the identityCard
     */
    public String getIdentityCard() {
        return identityCard;
    }
    /**
     * @param identityCard
     *            the identityCard to set
     */
    public void setIdentityCard(String identityCard) {
        this.identityCard = identityCard;
    }
    /**
     * id
     */
    private String id;
    /**
     * 用戶名
     */
    private String username;
    /**
     * 密碼
     */
    private String password;
    /**
     * 真實姓名
     */
    private String realname;
    /**
     * 電子郵箱
     */
    private String email;
    /**
     * 地址
     */
    private String address;
    /**
     * 郵編
     */
    private int zip;
    /**
     * ×××
     */
    private String identityCard;
}


這樣就能夠準備咱們的前臺程序了。

前臺程序也很簡單,只須要兩個東東。一個是angular.js,一個是angular-resource.js。由於我前臺請求使用了angularjs中的resource模塊。具體內容請看這裏:http://docs.angularjs.org/api/ngResource.$resource




而後咱們來關注一下去前臺吧!廢話很少說,先直接上代碼


<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app="userService">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
<script type="text/javascript" src="js/angular.js"></script>
<script type="text/javascript" src="js/angular-resource.js"></script>
<script type="text/javascript" src="js/angular-my.js"></script>
<style type="text/css">
</style>
</script>
</head>
<body ng-controller="userController">
 <div id="save"
  style="display: block; margin-left: auto; margin-right: auto;">
  <table>
   <tr style="display: none">
    <td>用戶id</td>
    <td><input type="text" name="user.id" ng-model="saveUser.id" /></td>
   </tr>
   <tr>
    <td>用戶名</td>
    <td><input type="text" name="user.username"
     ng-model="saveUser.username" /></td>
   </tr>
   <tr>
    <td>密碼</td>
    <td><input type="password" name="user.password"
     ng-model="saveUser.password" /></td>
   </tr>
   <tr>
    <td>用戶姓名</td>
    <td><input type="text" name="user.cs"
     ng-model="saveUser.realname" /></td>
   </tr>
   <tr>
    <td colspan="2"><input type="button" value="添加"
     ng-click="addUserClick()" /></td>
   </tr>
  </table>
 </div>
 <div id="userList" style="margin-left: auto; margin-right: auto;">
  <table border="1" style="margin-left: auto; margin-right: auto;">
   <tr>
    <th>序號</th>
    <th>用戶id</th>
    <th>用戶名稱</th>
    <th>用戶密碼</th>
    <th>用戶姓名</th>
    <th>用戶操做</th>
   </tr>
   <tr ng-repeat="user in mydata" ng-class-even="'even'"
    ng-class-odd="'odd'">
    <td>{{$index + 1}}</td>
    <td>`user`.`id`</td>
    <td>`user`.`username`</td>
    <td>`user`.`password`</td>
    <td>`user`.`realname`</td>
    <td><a href="" ng-click="updateUser(user)">修改</a> &nbsp; <a
     href="" ng-click="deleteUser(user)">刪除</a></td>
   </tr>
  </table>
 </div>
 <div id="update"
  style="display: block; margin-left: auto; margin-right: auto;">
  <table>
   <tr style="display: none">
    <td>用戶id</td>
    <td><input type="text" id="id" name="user.id"
     ng-model="modifyUser.id" /></td>
   </tr>
   <tr>
    <td>用戶名</td>
    <td><input type="text" id="username" name="user.username"
     ng-model="modifyUser.username" /></td>
   </tr>
   <tr>
    <td>密碼</td>
    <td><input type="password" id="password" name="user.password"
     ng-model="modifyUser.password" /></td>
   </tr>
   <tr>
    <td>用戶姓名</td>
    <td><input type="text" id="cs" name="user.cs"
     ng-model="modifyUser.realname" /></td>
   </tr>
   <tr>
    <td colspan="2"><input type="button" value="更新"
     ng-click="updateUserClick()" /></td>
   </tr>
  </table>
 </div>
</body>
</html>


var projectName = '/' + window.location.pathname.split('/')[1];
var userUrl = {
    'addUrl' : projectName + '/user/add',
    'deleteUrl' : projectName + '/user/delete',
    'updateUrl' : projectName + '/user/update',
    'queryUrl' : projectName + '/user/userList'
};
var user = angular.module('userService', [ 'ngResource' ], angular.noop);
user.controller('userController', function($scope, $resource) {
    var actions = {
        'add' : {
            method : 'PUT',
            isArray : true,
            headers : {
                'Content-Type' : 'application/json'
            }
        },
        'delete' : {
            method : 'DELETE',
            isArray : true
        },
        'query' : {
            method : 'GET',
            isArray : true
        },
        'update' : {
            method : 'POST',
            isArray : true,
            headers : {
                'Content-Type' : 'application/json'
            }
        }
    };
    var getUserList = $resource(userUrl.queryUrl, {
        page : 1,
        pageSize : 20
    }, actions);
    getUserList.query({}, function(data) {
        subobj = data;
        $scope.mydata = data;
    });
    var userAdd = $resource(userUrl.addUrl, {
        page : 1,
        pageSize : 20
    }, actions);
    $scope.addUserClick = function() {
        userAdd.add($scope.saveUser, function(data) {
            subobj = data;
            $scope.mydata = data;
        });
    };
    var userUpdate = $resource(userUrl.updateUrl, {
        page : 1,
        pageSize : 20
    }, actions);
    $scope.updateUserClick = function() {
        userUpdate.update($scope.modifyUser, function(data) {
            subobj = data;
            $scope.mydata = data;
        });
    };
    var userDelete = $resource(userUrl.deleteUrl, {
        page : 1,
        pageSize : 20,
        id : ':id'
    }, actions);
    $scope.deleteUser = function(user) {
        userDelete['delete']({
            id : user.id
        }, {}, function(data) {
            subobj = data;
            $scope.mydata = data;
        });
    };
    $scope.updateUser = function(user) {
        $scope.modifyUser = user;
    };
});




如今這裏已經把代碼基本都已經貼出來了,能夠根據這個代碼寫一個本身的單頁面程序了。前臺後臺交互都用json來完成,值得注意一點咱們若是獲取的返回值爲list或者數組形式的數組,那麼咱們應該在定義resource模塊的時候,須要指定isArray: true(不然會瀏覽器報has no method 'push'的異常)。大體的流程是這樣的,因爲第一次寫這麼長的博客,寫的不是很好。若是你們有什麼問題能夠給我留言。

我是經過這幾個教程學習的,你們有興趣能夠參考一下他們的博文,對你們會頗有幫助。

springmvc restful:http://badqiu.iteye.com/blog/473301

angularjs:http://zouyesheng.com/angular.html (推薦)   、   http://www.angularjs.cn/

可能你們有疑問,搭建這樣一個項目須要哪些jar包呢?我是由maven來管理jar包的,pom的簡單配置以下:



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>springmvc</groupId>
    <artifactId>springmvc</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <spring.version>4.0.0.RELEASE</spring.version>
    </properties>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <warSourceDirectory>web</warSourceDirectory>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <!--spring framework start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring framework end -->
        <!--commons start -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.1</version>
        </dependency>
        <!--commons end -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
        <!--jstl start -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!--jstl end -->
        <!-- hibernate start -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.0.Final</version>
        </dependency>
        <!-- hibernate end -->
        <!-- jackson start -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-lgpl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <!-- jackson end -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.28</version>
        </dependency>
    </dependencies>
</project>



有些是否是必須的jar包,因此能夠根據本身的需求來導入。若是不是使用maven來管理的話,能夠根據artifactId來到maven資料庫上面手動下載一下就能夠了。

好了就說到這吧!

有問題留言探討!


我把代碼共享到51CTO的下載區了。稍後給出連接  共享連接:http://pan.baidu.com/s/1sjFC22x

相關文章
相關標籤/搜索