Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
J
javab_20230617
Overview
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Patryk Czarnik
javab_20230617
Commits
db7f1d60
Commit
db7f1d60
authored
Jul 30, 2023
by
Patryk Czarnik
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
PUT, POST, DELETE
parent
dacdd0c2
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
65 additions
and
0 deletions
+65
-0
ProductEndpoint.java
...SklepSpring/src/main/java/sklep/rest/ProductEndpoint.java
+63
-0
SecurityConfig.java
...epSpring/src/main/java/sklep/security/SecurityConfig.java
+2
-0
No files found.
PC27-SklepSpring/src/main/java/sklep/rest/ProductEndpoint.java
View file @
db7f1d60
...
...
@@ -4,10 +4,15 @@ import java.math.BigDecimal;
import
java.util.List
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.dao.EmptyResultDataAccessException
;
import
org.springframework.data.domain.Sort
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.web.bind.annotation.DeleteMapping
;
import
org.springframework.web.bind.annotation.GetMapping
;
import
org.springframework.web.bind.annotation.PathVariable
;
import
org.springframework.web.bind.annotation.PostMapping
;
import
org.springframework.web.bind.annotation.PutMapping
;
import
org.springframework.web.bind.annotation.RequestBody
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.RestController
;
import
org.springframework.web.server.ResponseStatusException
;
...
...
@@ -42,6 +47,64 @@ public class ProductEndpoint {
return
readOne
(
id
).
getPrice
();
}
/*
* Operacja PUT służy do zapisania danych POD PODANYM ADRESEM.
* Na przykład PUT products/2/price z wartością 100 powinno ustawić w produkcie nr 2 cenę 100.
* Jeśli PUT zadziała, to następnie GET wysłany pod ten sam adres powinien odczytać te same dane,
* które PUT zapisał (być może w innym formacie - to inny temat)
*
* PUT najczęściej jest używany do aktualizacji istniejących danych
* (pojedynczych wartości albo całych rekordów), ale może być też użyty do
* zapisania nowych danych. To, co najważniejsze, to fakt, że PUT zapisuje dane
* pod konkretnym adresem, do którego jest wysyłany.
*
* Aby odczytać dane, które przysłał klient, metoda ma jeden parametr oznaczony @RequestBody.
* To do tego parametru Spring przekaże dane odczytane z "body" zapytania.
*/
@PutMapping
(
"/{id}/price"
)
public
void
setPrice
(
@PathVariable
Integer
id
,
@RequestBody
BigDecimal
newPrice
)
{
Product
product
=
productRepository
.
findById
(
id
).
orElseThrow
(()
->
new
ResponseStatusException
(
HttpStatus
.
NOT_FOUND
));
product
.
setPrice
(
newPrice
);
productRepository
.
save
(
product
);
}
/*
* POST jest najbardziej ogólną metodą HTTP; oznacza, że klient
* "wysyła jakieś dane na serwer", a serwer odsyła jakąś odpowiedź.
* W zasadzie POST może służyć do wszystkiego.
*
* W praktyce POST bardzo często służy do dodawania nowych rekordów, ponieważ
* gdy tworzymy nowy rekord, to nie znamy z góry jego ID i nie wiemy pod jakim
* URL-em zostanie zapisany (nie da się więc użyć PUT). Stąd wzięła REST-owa
* konwencja, że aby dodać nowy rekord do katalogu, wysyła się POST z danymi
* tego rekordu pod ogólny adres całego katalogu.
*/
@PostMapping
public
Product
insert
(
@RequestBody
Product
product
)
{
/* Operacja save (a wewnętrznie persist z Hibernate) spowoduje ustawienie nowego ID w obiekcie.
* Warto taką informację przekazać klientowi. Można:
* 1) odesłać uzupełniony rekord (i tak zrobimy tutaj),
* 2) odesłać "małego JSON-a" z informacją o tym ID
* (i innymi informacjami, które serwer chce przekazać klientowi)
* 3) tylko nagłówek Location z URL-em nowego rekordu (to zobaczymy w wersji JAX-RS).
*/
productRepository
.
save
(
product
);
return
product
;
}
@DeleteMapping
(
"/{id}"
)
public
void
delete
(
@PathVariable
(
"id"
)
Integer
productId
)
{
try
{
productRepository
.
deleteById
(
productId
);
}
catch
(
EmptyResultDataAccessException
e
)
{
throw
new
ResponseStatusException
(
HttpStatus
.
NOT_FOUND
,
"Brak produktu nr "
+
productId
);
}
}
/* Większość komunikacji w usługach REST odbywa się w formacie JSON,
* ale czasami używany jest też format XML,
* a dla niektórych danych stosujemy bezpośrednio jakiś format specjalny, np. PNG, JPG dla obrazów, PDF dla wydruków itp.
*/
@GetMapping
(
path
=
"/{id}/photo"
,
produces
=
"image/jpeg"
)
public
byte
[]
getPhoto
(
@PathVariable
Integer
id
)
{
return
photoUtil
.
readBytes
(
id
);
...
...
PC27-SklepSpring/src/main/java/sklep/security/SecurityConfig.java
View file @
db7f1d60
...
...
@@ -8,6 +8,7 @@ import org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.Customizer
;
import
org.springframework.security.config.annotation.web.builders.HttpSecurity
;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
;
import
org.springframework.security.config.annotation.web.configurers.CsrfConfigurer
;
import
org.springframework.security.provisioning.JdbcUserDetailsManager
;
import
org.springframework.security.web.SecurityFilterChain
;
...
...
@@ -46,6 +47,7 @@ public class SecurityConfig {
.
requestMatchers
(
"/rest/**"
).
permitAll
()
.
anyRequest
().
denyAll
()
// dobra praktyka - odrzucanie pozostałych zapytań; Spring domyślnie wymagałby "authenticated"
).
formLogin
(
Customizer
.
withDefaults
())
.
csrf
(
c
->
c
.
ignoringRequestMatchers
(
"/rest/**"
))
;
return
httpSecurity
.
build
();
}
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment