Spring Boot + Thymeleaf + AngularJS 使用

IDEA创建Spring Boot项目
创建Spring Boot
创建Spring Boot
添加需要的依赖
添加依赖
maven依赖

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <!--thymeleaf layout插件-->
    <dependency>
        <groupId>nz.net.ultraq.thymeleaf</groupId>
        <artifactId>thymeleaf-layout-dialect</artifactId>
        <version>2.3.0</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.8</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

修改 application.yml

server:
  servlet:
    context-path: /angularjs
  port: 8123

spring:
  thymeleaf:
    cache: false
    encoding: UTF-8

项目目录结构

默认Spring boot的html在templates文件夹下,静态文件在static文件夹下,也可以修改Spring Boot 静态资源处理
项目结构
BasicAngularSpringBootController

@Controller
public class BasicAngularSpringBootController {
    @RequestMapping("/")
    public ModelAndView basicAngularSpringBootTemplate(){
        return new ModelAndView("basic_angular_springboot");
    }
}

Print类,测试用

@Data
public class Print {
    private String print;
}

BasicAngularSpringBootRest

@RestController
@RequestMapping("/api/basic")
public class BasicAngularSpringBootRest {
    @GetMapping("/get")
    public void getPrint(@RequestParam("print")String print){
        System.out.println("get : " + print);
    }
	
	@PostMapping("/postparam")
    public void postPrint(@RequestParam("print") String print){
        System.out.println("post param : " + print);
    }    

    @PostMapping("/postbody")
    public void postPrint(@RequestBody Print print){
        System.out.println("post body : " + print.getPrint());
    }
}

模板 default.html

<!DOCTYPE html>
<html ng-app="angularjsApp" lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="utf-8" />
    <title>默认模板</title>

    <link th:href="@{/lib/bootstrap/3.3.7/css/bootstrap.css}" rel="stylesheet" type="text/css">

    <script th:src="@{/lib/jquery/2.1.4/jquery.js}" type="text/javascript"></script>

    <script th:src="@{/lib/bootstrap/3.3.7/js/bootstrap.js}" type="text/javascript"></script>

    <script th:src="@{/lib/angular/angular-1.6.1/angular.js}" type="text/javascript"></script>

	<script th:src="@{/lib/layer/layer.js}" type="text/javascript"></script>

    <script th:src="@{/js/app.js}" type="text/javascript"></script>
    <script th:src="@{/js/service/httpService.js}" type="text/javascript"></script>

</head>

<body layout:fragment="content">
</body>

</html>

basic_angular_springboot.html

layout:fragment,定义模板片段,可以在子页面用同名片段覆盖

layout:decorator,引用Thymeleaf页面作为模板

<!DOCTYPE html>
<html ng-app="angularjsApp" lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.w3.org/1999/xhtml" layout:decorate="layout/default">
<head>
    <meta charset="utf-8">
    <title>basic angularjs springboot</title>
    
    <script th:src="@{/js/controller/basicAngularSpringBootCtrl.js}"></script>
</head>

<body layout:fragment="content">

<div ng-controller="basicAngularSpringBootCtrl" ng-cloak>
   	<h1>{{title}}</h1>
   	
    <input type="text" ng-model="inputText" ng-change="changeInputText()">
    <p>{{inputText}}</p>
</div>

</body>
</html>

angularJS的 app.js

var Config = {
    contextPath:"/angularjs/",
    apiRemoteUrl: "http://localhost:8123/angularjs/api/",
    getContextPath: function() {
        return this.contextPath;
    },
    getApiRemoteUrl: function() {
        return this.apiRemoteUrl;
    }
};

var app = angular.module('angularjsApp',[]);

angularJS 的 控制类 basicAngularSpringBootCtrl.js

app.controller('basicAngularSpringBootCtrl',function($scope,$http,httpService){

    $scope.title = "basicAngularSpringBootCtrl";

    $scope.changeInputText = function () {
        //get 字符串
        var getUrl = 'basic/get';
        var getParams = {
            'print': $scope.inputText
        };
        httpService.getOrPostParam('GET',getUrl,getParams,function (response) {
            layer.msg("get success");
        });

		//post 字符串
        var postparamUrl = 'basic/postparam';
        var postparamParams = {
            'print': $scope.inputText
        };
        httpService.getOrPostParam('POST',postparamUrl,postparamParams,function (response) {
            layer.msg("post param success");
        });

        //post 对象
        var postbodyUrl = 'basic/postbody';
        var postbodyParams = {
            'print': $scope.inputText
        };
        httpService.postData(postbodyUrl,postbodyParams,function (response) {
            layer.msg("post body success");
        }); 
    };
});

抽出ajax httpSerivce.js

/**
 * http service
 */
app.factory('httpService', function($http) {
    var factory = {};

    factory.getOrPostParam = function (method,url,param,callback) {
        $http({
            method: method,
            url: Config.getApiRemoteUrl() + url,
            params: param
        }).then(function successCallback(response) {
            callback(response);
        }, function errorCallback(response) {
            layer.alert("error");
        });
    };

    factory.postData = function (url,data,callback) {
        $http({
            method: 'POST',
            url: Config.getApiRemoteUrl() + url,
            data: data
        }).then(function successCallback(response) {
            callback(response);
        }, function errorCallback(response) {
            layer.alert("error");
        });
    };

    return factory;
});

访问 http://localhost:8123/angularjs/
访问
打印

参考:
Thymeleaf使用技巧:使用片段(fragment)实现母版页(Layout)功能
AngularJS 教程 | 菜鸟教程

发布了57 篇原创文章 · 获赞 11 · 访问量 9876

猜你喜欢

转载自blog.csdn.net/qq_36160730/article/details/97646922
今日推荐