первая лаба
This commit is contained in:
3
.idea/.gitignore
generated
vendored
Normal file
3
.idea/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
9
.idea/internetDev.iml
generated
Normal file
9
.idea/internetDev.iml
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
6
.idea/misc.xml
generated
Normal file
6
.idea/misc.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="21" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
||||
8
.idea/modules.xml
generated
Normal file
8
.idea/modules.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/internetDev.iml" filepath="$PROJECT_DIR$/.idea/internetDev.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
6
.idea/vcs.xml
generated
Normal file
6
.idea/vcs.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -10,17 +10,10 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
@CrossOrigin(origins = "*")
|
||||
public class ArtistController {
|
||||
|
||||
private final Map<String, ArtistDto> artists = new LinkedHashMap<>();
|
||||
private final Map<Integer, ArtistDto> artists = new LinkedHashMap<>();
|
||||
private final AtomicInteger idCounter = new AtomicInteger(1);
|
||||
|
||||
public ArtistController() {
|
||||
// Инициализация предопределенными данными
|
||||
artists.put("9daa", new ArtistDto("9daa", "testlabуцк", "sadууу", 2, 3));
|
||||
artists.put("98ad", new ArtistDto("98ad", "ыфвфы", "выфв", 1, 1));
|
||||
artists.put("dd28", new ArtistDto("dd28", "аааа", "ааа", 2, 3));
|
||||
artists.put("b499", new ArtistDto("b499", "бб", "уафв", 1, 3));
|
||||
artists.put("0f62", new ArtistDto("0f62", "Максим", "2", 2, 1));
|
||||
}
|
||||
public ArtistController() {}
|
||||
|
||||
@GetMapping("/artists")
|
||||
public List<ArtistDto> getAllArtists() {
|
||||
@@ -28,20 +21,20 @@ public class ArtistController {
|
||||
}
|
||||
|
||||
@GetMapping("/artists/{id}")
|
||||
public ArtistDto getArtistById(@PathVariable String id) {
|
||||
public ArtistDto getArtistById(@PathVariable Integer id) {
|
||||
return artists.get(id);
|
||||
}
|
||||
|
||||
@PostMapping("/artists")
|
||||
public ArtistDto createArtist(@RequestBody ArtistDto artist) {
|
||||
String newId = String.valueOf(idCounter.getAndIncrement());
|
||||
Integer newId = idCounter.getAndIncrement();
|
||||
artist.setId(newId);
|
||||
artists.put(newId, artist);
|
||||
return artist;
|
||||
}
|
||||
|
||||
@PutMapping("/artists/{id}")
|
||||
public ArtistDto updateArtist(@PathVariable String id, @RequestBody ArtistDto artist) {
|
||||
public ArtistDto updateArtist(@PathVariable Integer id, @RequestBody ArtistDto artist) {
|
||||
if (artists.containsKey(id)) {
|
||||
artist.setId(id);
|
||||
artists.put(id, artist);
|
||||
@@ -51,7 +44,7 @@ public class ArtistController {
|
||||
}
|
||||
|
||||
@PatchMapping("/artists/{id}")
|
||||
public ArtistDto patchArtist(@PathVariable String id, @RequestBody Map<String, Object> updates) {
|
||||
public ArtistDto patchArtist(@PathVariable Integer id, @RequestBody Map<String, Object> updates) {
|
||||
ArtistDto existingArtist = artists.get(id);
|
||||
if (existingArtist != null) {
|
||||
if (updates.containsKey("name")) {
|
||||
@@ -73,7 +66,7 @@ public class ArtistController {
|
||||
}
|
||||
|
||||
@DeleteMapping("/artists/{id}")
|
||||
public boolean deleteArtist(@PathVariable String id) {
|
||||
public boolean deleteArtist(@PathVariable Integer id) {
|
||||
return artists.remove(id) != null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ public class CountryController {
|
||||
private final AtomicInteger idCounter = new AtomicInteger(1);
|
||||
|
||||
public CountryController() {
|
||||
// Инициализация предопределенными данными
|
||||
|
||||
countries.put(1, new CountryDto(1, "Россия"));
|
||||
countries.put(2, new CountryDto(2, "США"));
|
||||
countries.put(3, new CountryDto(3, "Тайга"));
|
||||
|
||||
@@ -14,7 +14,6 @@ public class EpochController {
|
||||
private final AtomicInteger idCounter = new AtomicInteger(1);
|
||||
|
||||
public EpochController() {
|
||||
// Инициализация предопределенными данными
|
||||
epochs.put(1, new EpochDto(1, "1980-е"));
|
||||
epochs.put(2, new EpochDto(2, "1990-е"));
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class ArtistDto {
|
||||
private String id;
|
||||
private Integer id;
|
||||
private String name;
|
||||
private String description;
|
||||
private Integer epochId;
|
||||
@@ -9,7 +9,7 @@ public class ArtistDto {
|
||||
|
||||
public ArtistDto() {}
|
||||
|
||||
public ArtistDto(String id, String name, String description, Integer epochId, Integer countryId) {
|
||||
public ArtistDto(Integer id, String name, String description, Integer epochId, Integer countryId) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.description = description;
|
||||
@@ -17,11 +17,11 @@ public class ArtistDto {
|
||||
this.countryId = countryId;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@
|
||||
<div class="card-body">
|
||||
<h3 class="text-punk mb-4"><i class="bi bi-person-plus"></i> Добавить исполнителя</h3>
|
||||
|
||||
<form id="artistForm">
|
||||
<form id="artistForm" onsubmit="addArtist(); return false;">
|
||||
<!-- Название группы -->
|
||||
<div class="mb-3">
|
||||
<label class="form-label text-light">Название группы</label>
|
||||
@@ -153,12 +153,12 @@
|
||||
<label class="form-label text-light">Страна</label>
|
||||
<input type="text" class="form-control bg-dark text-light border-punk" id="editArtistCountry">
|
||||
</div>
|
||||
<input type="hidden" id="editArtistId">
|
||||
<input type="number" id="editArtistId" style="display: none;">
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer border-punk">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
|
||||
<button type="button" class="btn btn-punk" id="saveEditArtist"><i class="bi bi-save"></i> Сохранить</button>
|
||||
<button type="button" class="btn btn-punk" id="saveEditArtist" onclick="saveEditArtist()"><i class="bi bi-save"></i> Сохранить</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
208
punkrock-react/src/js/main.js
Normal file
208
punkrock-react/src/js/main.js
Normal file
@@ -0,0 +1,208 @@
|
||||
// Основной JavaScript код для работы с исполнителями
|
||||
const API_URL = 'http://localhost:8080/api';
|
||||
|
||||
// Загрузка данных при загрузке страницы
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
loadArtists();
|
||||
loadCountries();
|
||||
loadEpochs();
|
||||
});
|
||||
|
||||
// Загрузка исполнителей
|
||||
async function loadArtists() {
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/artists`);
|
||||
const artists = await response.json();
|
||||
displayArtists(artists);
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки исполнителей:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Загрузка стран
|
||||
async function loadCountries() {
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/countries`);
|
||||
const countries = await response.json();
|
||||
console.log('Загружены страны:', countries);
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки стран:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Загрузка эпох
|
||||
async function loadEpochs() {
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/epochs`);
|
||||
const epochs = await response.json();
|
||||
console.log('Загружены эпохи:', epochs);
|
||||
} catch (error) {
|
||||
console.error('Ошибка загрузки эпох:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Отображение исполнителей
|
||||
function displayArtists(artists) {
|
||||
const container = document.getElementById('artistsContainer');
|
||||
container.innerHTML = '';
|
||||
|
||||
artists.forEach(artist => {
|
||||
const artistCard = createArtistCard(artist);
|
||||
container.appendChild(artistCard);
|
||||
});
|
||||
}
|
||||
|
||||
// Создание карточки исполнителя
|
||||
function createArtistCard(artist) {
|
||||
const col = document.createElement('div');
|
||||
col.className = 'col-md-4 mb-4';
|
||||
|
||||
col.innerHTML = `
|
||||
<div class="card bg-dark border-punk">
|
||||
<div class="card-body">
|
||||
<h5 class="card-title text-punk">${artist.name}</h5>
|
||||
<p class="card-text text-light">${artist.description || 'Нет описания'}</p>
|
||||
<p class="card-text text-light"><small>Эпоха ID: ${artist.epochId || 'Не указана'}</small></p>
|
||||
<p class="card-text text-light"><small>Страна ID: ${artist.countryId || 'Не указана'}</small></p>
|
||||
<button class="btn btn-outline-primary edit-btn me-2" onclick="editArtist(${artist.id})">
|
||||
<i class="bi bi-pencil-square"></i> Изменить
|
||||
</button>
|
||||
<button class="btn btn-outline-danger delete-btn" onclick="deleteArtist(${artist.id})">
|
||||
<i class="bi bi-trash"></i> Удалить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
return col;
|
||||
}
|
||||
|
||||
// Редактирование исполнителя
|
||||
function editArtist(id) {
|
||||
// ID теперь числовой
|
||||
console.log('Редактирование исполнителя с ID:', id, 'тип:', typeof id);
|
||||
|
||||
// Заполняем форму данными исполнителя
|
||||
document.getElementById('editArtistId').value = id;
|
||||
|
||||
// Здесь можно загрузить данные исполнителя и заполнить форму
|
||||
// Пока что просто открываем модальное окно
|
||||
const modal = new bootstrap.Modal(document.getElementById('editArtistModal'));
|
||||
modal.show();
|
||||
}
|
||||
|
||||
// Удаление исполнителя
|
||||
async function deleteArtist(id) {
|
||||
// ID теперь числовой
|
||||
console.log('Удаление исполнителя с ID:', id, 'тип:', typeof id);
|
||||
|
||||
if (confirm('Удалить исполнителя?')) {
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/artists/${id}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
loadArtists(); // Перезагружаем список
|
||||
} else {
|
||||
alert('Ошибка удаления исполнителя');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка удаления:', error);
|
||||
alert('Ошибка удаления исполнителя');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Сохранение изменений исполнителя
|
||||
async function saveEditArtist() {
|
||||
const id = parseInt(document.getElementById('editArtistId').value);
|
||||
const name = document.getElementById('editArtistName').value;
|
||||
const description = document.getElementById('editDescription').value;
|
||||
const year = document.getElementById('editArtistYear').value;
|
||||
const country = document.getElementById('editArtistCountry').value;
|
||||
|
||||
console.log('Сохранение исполнителя с ID:', id, 'тип:', typeof id);
|
||||
|
||||
if (!name || !description) {
|
||||
alert('Все поля обязательны!');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/artists/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: name,
|
||||
description: description,
|
||||
epochId: 1, // Пока что статическое значение
|
||||
countryId: 1 // Пока что статическое значение
|
||||
})
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const modal = bootstrap.Modal.getInstance(document.getElementById('editArtistModal'));
|
||||
modal.hide();
|
||||
loadArtists(); // Перезагружаем список
|
||||
} else {
|
||||
alert('Ошибка сохранения исполнителя');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка сохранения:', error);
|
||||
alert('Ошибка сохранения исполнителя');
|
||||
}
|
||||
}
|
||||
|
||||
// Добавление нового исполнителя
|
||||
async function addArtist() {
|
||||
const name = document.getElementById('artistName').value;
|
||||
const description = document.getElementById('description').value;
|
||||
const year = document.getElementById('artistYear').value;
|
||||
const country = document.getElementById('artistCountry').value;
|
||||
|
||||
if (!name || !description) {
|
||||
alert('Все поля обязательны!');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/artists`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: name,
|
||||
description: description,
|
||||
epochId: 1, // Пока что статическое значение
|
||||
countryId: 1 // Пока что статическое значение
|
||||
})
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
document.getElementById('artistForm').reset();
|
||||
loadArtists(); // Перезагружаем список
|
||||
} else {
|
||||
alert('Ошибка добавления исполнителя');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Ошибка добавления:', error);
|
||||
alert('Ошибка добавления исполнителя');
|
||||
}
|
||||
}
|
||||
|
||||
// Привязка событий
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Кнопка сохранения редактирования
|
||||
document.getElementById('saveEditArtist').addEventListener('click', saveEditArtist);
|
||||
|
||||
// Кнопка добавления исполнителя
|
||||
document.getElementById('artistForm').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
addArtist();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user