Spring boot controller method memo

Spring MVC controller methods can receive various information as arguments in addition to the parameters entered on the screen.

@Secured By adding the @Secured annotation, you can specify the authority related to the URL.


@Controller
@RequestMapping("/sbadmin2/")
@Secured("IS_AUTHENTICATED_FULLY")
public class SbAdmin2Controller {

    @RequestMapping("/index.html")
    public ModelAndView index() {
        return new ModelAndView("SbAdmin2Controller/index");
    }

    @Secured("ROLE_STAFF")
    @RequestMapping("/forms.html")
    public ModelAndView forms() {
        return new ModelAndView("SbAdmin2Controller/forms");
    }
}
// /sbadmin2/index.html can be accessed if logged in
// /sbadmin2/forms.html log in and ROLE_Accessable if assigned STAFF privileges

@RequestParam By specifying the @RequestParam annotation, you can receive the query parameters included in the URL and the post parameters included in the message body.


@GetMapping("/hello")
public String hello(@RequestParam("name") String name) {}
// /hello?name=string

@RequestPart If you specify the @RequestParam annotation, you can receive image / video files and JSON.


@GetMapping("/hello")
public String hello(@RequestPart("data") String data) {}
const data = new FormData()
data.append('file', file)
data.append('jsonValue', new Blob([JSON.stringify(sampleObject)], {type : 'application/json'}))

axios.get('/hello', data)

@PathVariable If you specify the @PathVariable annotation, you can receive the dynamic parameters included in the URL.


@GetMapping("/hello/{userId}")
public String hello(@PathVariable("userId") Integer userId) {

@RequestHeader If you specify the @RequestHeader annotation, you can receive each item included in the request header.


@GetMapping("/hello")
public String hello(@RequestHeader("User-Agent") String userAgent) {

RequestHeader


GET /hello?userId=10 HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json
X-XSRF-TOKEN: 00000-000-0000-0000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin
Referer: http://localhost:8080/hello?userId=10
Accept-Encoding: gzip, deflate, br
Accept-Language: ja,en-US;q=0.9,en;q=0.8
Cookie: [email protected];
JSESSIONID=sfdgfhgjh;
XSRF-TOKEN=00000-000-0000-0000

@RequestBody If you specify the @RequestBody annotation, you can get the contents of the request body as it is.

@PostMapping("/hello")
public String hello(@RequestBody String body) {
POST /hello HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 22
Cache-Control: max-age=0
Origin: http://localhost:8080
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Referer: http://localhost:8080/hello
Accept-Encoding: gzip, deflate, br
Accept-Language: ja,en-US;q=0.8,en;q=0.6

user=scott&password=tiger

@DateTimeFormat Specify the @DateTimeFormat annotation to specify the format of the string representation of the received date and time.

@GetMapping("/hello/{date}")
public String hello(@PathVariable("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) java.util.Date date) {}

@Autowired It automatically injects beans that match the type of the given field. If there are multiple beans that meet the type, they can be uniquely identified by using the @Qualifier annotation.

Reference: Verification of the difference between @Autowired, @Inject, @Resource @Validated Specify the @Validated annotation to enable validation.

 @PostMapping("/hello")
    public String hello(@RequestBody @Validated String name)

@AuthenticationPrincipal Specify the @AuthenticationPrincipal annotation so that the authenticated user information is automatically passed to its argument.

@RequestMapping("/hello")
    public String hello(@AuthenticationPrincipal AppUserDetail userDetail) {
        log.info("debug: {}", userDetail);
 
        return "user";
    }

Recommended Posts

Spring boot controller method memo
Spring boot memo writing (1)
Spring boot memo writing (2)
Spring Boot + Thymeleaf BootStrap installation method memo
Spring Security Usage memo Method security
◆ Spring Boot + gradle environment construction memo
Spring Boot + PostgreSQL error resolution method
A memo that touched Spring Boot
Spring retrospective memo
Spring Boot environment construction memo on mac
Challenge Spring Boot
Use DynamoDB query method in Spring Boot
Spring Boot Form
Spring Boot Memorandum
Test controller with Mock MVC in Spring Boot
JJUG CCC Spring 2018 memo
SPRING BOOT learning record 01
Spring Boot + Heroku Postgres
Spring Shell usage memo
Java learning memo (method)
[Java ~ Method ~] Study memo (5)
First Spring Boot (DI)
SPRING BOOT learning record 02
Spring Boot2 cheat sheet
Spring Boot exception handling
Spring boot development-development environment-
Spring Boot learning procedure
Get the class name and method name of Controller executed by HandlerInterceptor of Spring Boot
Learning Spring Boot [Beginning]
Spring Boot 2.2 Document Summary
[Spring Boot] DataSourceProperties $ DataSourceBeanCreationException
Spring Boot 2.3 Application Availability
Spring boot tutorials Topics
Download with Spring Boot
Spring Security usage memo: Cooperation with Spring MVC and Boot
[Spring Boot] Environment construction (macOS)
[Personal memo] About Spring framework
Set context-param in Spring Boot
Spring + MyBatis connection setting method
Try Spring Boot from 0 to 100.
Generate barcode with Spring Boot
Hello World with Spring Boot
JJUG CCC 2018 Spring participation memo
Implement GraphQL with Spring Boot
[Spring] Controller exception output test
Spring Framework self-study memo series_1
Spring Boot tutorial task schedule
Spring 5 & Spring Boot 2 Hands-on preparation procedure
Get started with Spring boot
Spring Security usage memo Run-As
Java Silver Study Method Memo
Hello World with Spring Boot!
Create a java method [Memo] [java11]
Spring Boot 2 multi-project in Gradle
[Spring Boot] Web application creation
spring boot port duplication problem
Spring Boot Hot Swapping settings
Spring Model View Controller Flow
[Java] Thymeleaf Basic (Spring Boot)
Introduction to Spring Boot ① ~ DI ~
Spring Security usage memo Remember-Me