Spring Boot 中結(jié)合Angular

引言

一直想要前后端結(jié)合一下,今天專(zhuān)門(mén)搜羅材料整理一篇博客。其實(shí)前端框架沒(méi)怎么太多使用過(guò),尤其是Angular或者是JQuery。困難是如何將Angular和Java后端體系相結(jié)合。

Angular(包括2和4)是從AngularJs1.x升級(jí)而來(lái),但是不提供向下兼容。

  • Anuglar2(或者4)和AngularJs1.x的一個(gè)很大不同,便是Angular使用了TypeScript,而1.x則使用了JavaScript,也是兩者不能兼容的一個(gè)很重要的原因。目前現(xiàn)代瀏覽器均不直接支持TypeScript,因此,我不能像AngularJs 1.x那樣,直接將Angular引入到JSP中。

解決方案

雖然通過(guò)查找資料沒(méi)有解決我的問(wèn)題,但是我還是獲得很大收獲。TypeScript畢竟是JavaScript的一個(gè)超集,本質(zhì)上還是JavaScript。Angular雖然是用TypeScript寫(xiě)的,但是在編譯之后本質(zhì)上和html、css、js文件沒(méi)有什么兩樣,因此我沒(méi)有必要將Angular的代碼放進(jìn)JavaWeb里面,而是將Angular編譯之后的靜態(tài)文件放入JavaWeb項(xiàng)目中就可以了。

在這個(gè)項(xiàng)目中我使用Spring Boot作為后端的框架,maven作為構(gòu)建工具,那么在main目錄下使用@angular/cli工具新建一個(gè)angular項(xiàng)目,名字就叫做angular吧。Spring Boot項(xiàng)目中一般將靜態(tài)資源放在resources目錄下的static文件夾中,為了方便編譯,可以把Angular中的.angular-cli.json文件中apps下的outDir設(shè)置為“../resources/static”。

Angular頁(yè)面使用WebStorm開(kāi)發(fā),Spring Boot則使用IDEA。當(dāng)我們啟動(dòng)項(xiàng)目或打包的時(shí)候需要使用ng build去編譯angular代碼,由于我修改.angular-cli.json的配置,編譯后的代碼將不會(huì)放在默認(rèn)的dist目錄下,而是在spring boot中的resources的static文件夾中了。

源代碼

這是源代碼

實(shí)戰(zhàn)

一、項(xiàng)目準(zhǔn)備

在建立mysql數(shù)據(jù)庫(kù)后新建表“t_order”

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `t_order`
-- ----------------------------
DROP TABLE IF EXISTS `t_order`;
CREATE TABLE `t_order` (
  `order_id` varchar(36) NOT NULL,
  `order_no` varchar(50) DEFAULT NULL,
  `order_date` datetime DEFAULT NULL,
  `quantity` int(11) DEFAULT NULL,
  PRIMARY KEY (`order_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_order
-- ----------------------------

修改pom.xml

<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>com.github.carter659</groupId>
    <artifactId>spring04</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring04</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

二、編寫(xiě)類(lèi)文件:

修改App.java

package com.github.carter659.spring04;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * 博客出處:http://www.cnblogs.com/GoodHelper/
 * 
 * @author 劉冬
 *
 */
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

新建數(shù)據(jù)載體類(lèi)文件“Order.java”

package com.github.carter659.spring04;

import java.util.Date;

/**
 * 博客出處:http://www.cnblogs.com/GoodHelper/
 * @author 劉冬
 *
 */
public class Order {

    public String id;

    public String no;

    public Date date;

    public int quantity;

    /**
     * 省略 get set
     */
}

新建數(shù)據(jù)持久層類(lèi)“OrderDao.java”

package com.github.carter659.spring04;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;

/**
 * 博客出處:http://www.cnblogs.com/GoodHelper/
 * @author 劉冬
 *
 */
@Repository
public class OrderDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Order> findAll() {
        List<Order> list = new ArrayList<>();
        String sql = " select * from t_order ";
        SqlRowSet rows = jdbcTemplate.queryForRowSet(sql, new Object[] {});
        while (rows.next()) {
            Order order = new Order();
            list.add(order);
            order.id = rows.getString("order_id");
            order.no = rows.getString("order_no");
            order.date = rows.getDate("order_date");
            order.quantity = rows.getInt("quantity");
        }
        return list;
    }

    public Order get(String id) {
        Order order = null;
        String sql = " select * from t_order where order_id = ? ";
        SqlRowSet rows = jdbcTemplate.queryForRowSet(sql, new Object[] { id });
        while (rows.next()) {
            order = new Order();
            order.id = rows.getString("order_id");
            order.no = rows.getString("order_no");
            order.date = rows.getDate("order_date");
            order.quantity = rows.getInt("quantity");
        }
        return order;
    }

    public String insert(Order order) {
        String id = UUID.randomUUID().toString();
        String sql = " insert into t_order ( order_id , order_no , order_date , quantity ) values (?,?,?,?) ";
        jdbcTemplate.update(sql,
                new Object[] { id, order.no, new java.sql.Date(order.date.getTime()), order.quantity });
        return id;
    }

    public void update(Order order) {
        String sql = " update t_order set order_no = ? , order_date = ? , quantity = ? where order_id = ? ";
        jdbcTemplate.update(sql,
                new Object[] { order.no, new java.sql.Date(order.date.getTime()), order.quantity, order.id });
    }

    public void delete(String id) {
        String sql = " delete from t_order where order_id = ? ";
        jdbcTemplate.update(sql, new Object[] { id });
    }
}

其中對(duì)數(shù)據(jù)庫(kù)的操作,顧名思義:

findAll-->查詢(xún)所有數(shù)據(jù)

get-->通過(guò)id獲取數(shù)據(jù)

insert-->插入數(shù)據(jù)

update-->修改數(shù)據(jù)

delete-->刪除數(shù)據(jù)

新建控制器“MainController.java”

package com.github.carter659.spring04;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mysql.jdbc.StringUtils;

@Controller
public class MainController {

    @Autowired
    private OrderDao orderDao;

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @PostMapping("/save")
    public @ResponseBody Map<String, Object> save(@RequestBody Order order) {
        Map<String, Object> result = new HashMap<>();
        if (StringUtils.isNullOrEmpty(order.id))
            order.id = orderDao.insert(order);
        else {
            orderDao.update(order);
        }
        result.put("id", order.id);
        return result;
    }

    @PostMapping("/get")
    public @ResponseBody Object get(String id) {
        return orderDao.get(id);
    }

    @PostMapping("/findAll")
    public @ResponseBody Object findAll() {
        return orderDao.findAll();
    }

    @PostMapping("/delete")
    public @ResponseBody Map<String, Object> delete(String id) {
        Map<String, Object> result = new HashMap<>();
        orderDao.delete(id);
        result.put("id", id);
        return result;
    }
}

三、新建thymeleaf模板

新建文件“src/main/resources/templates/index.html”

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>玩轉(zhuǎn)spring boot——結(jié)合JDBC</title>
<script src="http://cdn.bootcss.com/angular.js/1.5.6/angular.min.js"></script>
<script type="text/javascript">
    /*<![CDATA[*/
    var app = angular.module('app', []);
    app.controller('MainController', function($rootScope, $scope, $http) {

        $scope.data = {};
        $scope.rows = [];

        //添加
        $scope.add = function() {
            $scope.data = {
                no : 'No.1234567890',
                quantity : 100,
                'date' : '2016-12-30'
            };
        }

        //編輯
        $scope.edit = function(id) {
            for ( var i in $scope.rows) {
                var row = $scope.rows[i];
                if (id == row.id) {
                    $scope.data = row;
                    return;
                }
            }
        }

        //移除
        $scope.remove = function(id) {
            for ( var i in $scope.rows) {
                var row = $scope.rows[i];
                if (id == row.id) {
                    $scope.rows.splice(i, 1);
                    return;
                }
            }
        }

        //保存
        $scope.save = function() {
            $http({
                url : '/save',
                method : 'POST',
                data : $scope.data
            }).success(function(r) {
                //保存成功后更新數(shù)據(jù)
                $scope.get(r.id);
            });
        }

        //刪除
        $scope.del = function(id) {
            $http({
                url : '/delete?id=' + id,
                method : 'POST',
            }).success(function(r) {
                //刪除成功后移除數(shù)據(jù)
                $scope.remove(r.id);
            });
        }

        //獲取數(shù)據(jù)
        $scope.get = function(id) {
            $http({
                url : '/get?id=' + id,
                method : 'POST',
            }).success(function(data) {
                for ( var i in $scope.rows) {
                    var row = $scope.rows[i];
                    if (data.id == row.id) {
                        row.no = data.no;
                        row.date = data.date;
                        row.quantity = data.quantity;
                        return;
                    }
                }
                $scope.rows.push(data);
            });
        }

        //初始化載入數(shù)據(jù)
        $http({
            url : '/findAll',
            method : 'POST'
        }).success(function(rows) {
            for ( var i in rows) {
                var row = rows[i];
                $scope.rows.push(row);
            }
        });
    });
    /*]]>*/
</script>
</head>
<body ng-app="app" ng-controller="MainController">
    <h1>玩轉(zhuǎn)spring boot——結(jié)合JDBC</h1>
    <h4>
        <a >from 劉冬的博客</a>
    </h4>
    <input type="button" value="添加" ng-click="add()" />
    <input type="button" value="保存" ng-click="save()" />
    <br />
    <br />
    <h3>清單信息:</h3>
    <input id="id" type="hidden" ng-model="data.id" />
    <table cellspacing="1" style="background-color: #a0c6e5">
        <tr>
            <td>編號(hào):</td>
            <td><input id="no" ng-model="data.no" /></td>
            <td>日期:</td>
            <td><input id="date" ng-model="data.date" /></td>
            <td>數(shù)量:</td>
            <td><input id="quantity" ng-model="data.quantity" /></td>
        </tr>
    </table>

    <br />
    <h3>清單列表:</h3>
    <table cellspacing="1" style="background-color: #a0c6e5">
        <tr
            style="text-align: center; COLOR: #0076C8; BACKGROUND-COLOR: #F4FAFF; font-weight: bold">
            <td>操作</td>
            <td>編號(hào)</td>
            <td>日期</td>
            <td>數(shù)量</td>
        </tr>
        <tr ng-repeat="row in rows" bgcolor='#F4FAFF'>
            <td><input ng-click="edit(row.id)" value="編輯" type="button" /><input
                ng-click="del(row.id)" value="刪除" type="button" /></td>
            <td>{{row.no}}</td>
            <td>{{row.date}}</td>
            <td>{{row.quantity}}</td>
        </tr>
    </table>

    <br />
    <a >點(diǎn)擊訪(fǎng)問(wèn)原版博客</a>
</body>
</html>

使用angularjs的ajax調(diào)用spring boot mv的后臺(tái)方法。

四、數(shù)據(jù)庫(kù)連接

新建“src/main/resources/application.properties”文件

spring.datasource.initialize=false
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

完整的結(jié)構(gòu)為:

五、運(yùn)行效果

在瀏覽器輸入“http://localhost:8080/


添加數(shù)據(jù):



保存新數(shù)據(jù):


編輯數(shù)據(jù):


刪除數(shù)據(jù):


刪除完成的效果:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容