Getmapping Spring Boot là gì

RequestMapping được sử dụng để ánh xạ yêu cầu với phương thức xử lý request.

Anotation @RequestMapping có thể sử dụng để đánh dấu cho một controller và cho từng action riêng lẻ.

  • Khi đánh dấu cho một controller thì các thiết lập của nó được áp dụng cho tất cả các action trong controller đó.
  • Khi đánh dấu cho từng action riêng thì chỉ áp dụng các thiết lập cho action đó.

Cú pháp: @RequestMapping [value, method, params]

  • value: chỉ ra action được ánh xạ với phương thức xử lý
  • method: chỉ ra phương thức truyền dữ liệu của trình duyệt web [POST, GET, PUT, DELETE.v.v.]
  • params: chỉ ra tham số bắt buộc phải có để thực hiện action.

Mặc định khi sử dụng annotation @RequestMapping, nếu bạn không định nghĩa thuộc tính method thì request method sẽ là GET. Nếu bạn sử dụng với các request method khác thì sẽ bị lỗi 405 [Lỗi 405: Xuất hiện là do người dùng đã gửi yêu cầu về một phương thức sai hoặc phương thức đó không còn tồn tại trên website.]

VD1: RequestMapping với method là GET

@Controller public class GreetingController{     @RequestMapping[value = "greeting", method = RequestMethod.GET]     public String greeting[] {         return "index";     } }       Greeting        

Hello Spring MVC

 

URL: //localhost:8080/greeting

Tags Java Spring Framework Web Development

Updated on 14 Tháng Mười, 2021

Để đơn giản quá trình lập trình ứng dụng với Spring framework, Spring Boot đã được giới thiệu. Các bạn có thể tham khảo bài viết này để hình dung Spring Boot là gì nhé!

Trong bài viết này, mình tổng hợp tất cả những bài viết của Hướng Dẫn Java về Spring Boot để mọi người tiện tham khảo.

Cài đặt

  • Cài đặt Spring Boot Command Line Interface trên Window

Để có thể tạo mới một project Spring Boot dễ dàng sử dụng command line trên Window, các bạn nên tham khảo bài viết này để cài đặt Spring Boot CLI.

  • Cài đặt Spring Boot Command Line Interface trên Ubuntu.

Tương tự như trên Window, các bạn cũng có thể cài đặt Spring Boot CLI trên Ubuntu.

  • Cài đặt Spring Boot Command Line Interface trên macOS

Trong bài viết này, mình hướng dẫn các bạn cách cài đặt Spring Boot CLI trên môi trường macOS.

Tạo mới Spring Boot project

  • Tạo mới Spring Boot project sử dụng Spring Initializr Web

Các bạn có thể tạo mới Spring Boot project sử dụng Spring Initializr Web ở địa chỉ //start.spring.io/.

  • Tạo mới Spring Boot project sử dụng Spring Tool Suite

Các bạn cũng có thể sử dụng Spring Tool Suite để tạo mới Spring Boot project.

Làm việc với database

  • Cấu hình database trong Spring Boot project với JPA Starter dependency

Trong bài viết này, mình hướng dẫn các bạn cấu hình database trong Spring Boot với JPA Starter dependency.

  • Sử dụng EclipseLink thay thế Hibernate trong Spring Data JPA Starter

Trong bài viết này, mình hướng dẫn các bạn cách sử dụng EclipseLink thay thế Hibernate trong Spring Data JPA Starter.

  • Sử dụng Liquibase trong Spring Boot

Trong bài viết này, mình hướng dẫn các bạn cách sử dụng Liquibase trong Spring Boot.

Bài viết hướng dẫn

  • Nói về cách hoạt động của Spring Boot

Để hiểu cách hoạt động của Spring Boot, các bạn có thể tham khảo bài viết này.

  • Ứng dụng Java console với Spring Boot

Trong bài viết này, mình hướng dẫn các bạn làm thế nào để tạo ứng dụng Java console với Spring Boot.

Trong bài viết này, mình hướng dẫn các bạn cách binding properties trong Spring Boot với annotation @ConfigurationProperties.

  • Sử dụng Apache Tiles trong Spring Boot

Các bạn sẽ biết cách cài đặt và sử dụng Apache Title trong Spring Boot nếu đọc bài viết này.

  • InternalResourceViewResolver trong Spring Boot

Trong bài viết này, mình sẽ hướng dẫn các bạn cách sử dụng InternalResourceViewResolver trong Spring Boot.

Trong bài viết này, mình sẽ hướng dẫn các bạn cách cấu hình JSP views trong InternalResourceViewResolver với Spring Boot JAR file.

  • Tạo RESTful API document sử dụng Springfox cho Swagger trong Spring Boot

Trong bài viết này, mình hướng dẫn các bạn cách sử dụng Springfox cho Swagger để tạo RESTful API document trong Spring Boot.

  • Sử dụng Thymeleaf trong Spring Boot

Trong bài viết này, mình hướng dẫn các bạn cách sử dụng Thymeleaf trong Spring Boot.

  • Giới thiệu về công cụ DevTools trong Spring Boot

Trong bài viết này, mình giới thiệu với các bạn về công cụ DevTools trong Spring Boot.

  • Giới thiệu về Spring Boot Actuator

Trong bài viết này, mình giới thiệu với các bạn về Spring Boot Actuator.

  • Viết Unit Test cho Spring Boot application

Trong bài viết này, mình sẽ hướng dẫn cho các bạn cách viết Unit Test cho Spring Boot application.

  • Sử dụng Spring Security trong Spring Boot

Sử dụng Spring Security với Spring Boot, chúng ta sẽ giảm thiểu các bước cấu hình cho Spring Security đi rất nhiều!

Deployment

Mình sẽ hướng dẫn các bạn làm thế nào để deploy một ứng dụng Spring Boot lên Cloud Foundry sử dụng Spring Boot Dashboard trong Spring Tool Suite.

  • Deploy ứng dụng Spring Boot sử dụng Docker

Trong bài viết này, mình hướng dẫn các bạn cách đơn giản để deploy ứng dụng Spring Boot trong Docker container.

Annotation @RequestMapping ngoài cho phép chúng ta định nghĩa request URL, nó còn cho phép chúng ta định nghĩa HTTP request method cho controller trong Spring MVC bằng cách sử dụng thuộc tính method của nó. Trong bài viết này, chúng ta sẽ cùng tìm hiểu thêm về thuộc tính method này các bạn nhé!

Trong project mà mình đã tạo ở bài viết trước, phương thức home[] đã định nghĩa một annotation @RequestMapping với giá trị của thuộc tính method là RequestMethod.GET.

package com.huongdanjava.springmvc; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Handles requests for the application home page. */ @Controller public class HomeController { private static final Logger logger = LoggerFactory.getLogger[HomeController.class]; /** * Simply selects the home view to render by returning its name. */ @RequestMapping[value = "home", method = RequestMethod.GET] public String home[Locale locale, Model model] { logger.info["Welcome home! The client locale is {}.", locale]; Date date = new Date[]; DateFormat dateFormat = DateFormat.getDateTimeInstance[DateFormat.LONG, DateFormat.LONG, locale]; String formattedDate = dateFormat.format[date]; model.addAttribute["serverTime", formattedDate]; return "home"; } }

package com.huongdanjava.springmvc;

import java.text.DateFormat;

import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

* Handles requests for the application home page.

public class HomeController {

    private static final Logger logger = LoggerFactory.getLogger[HomeController.class];

     * Simply selects the home view to render by returning its name.

    @RequestMapping[value = "home", method = RequestMethod.GET]

    public String home[Locale locale, Model model] {

        logger.info["Welcome home! The client locale is {}.", locale];

        DateFormat dateFormat = DateFormat.getDateTimeInstance[DateFormat.LONG, DateFormat.LONG, locale];

        String formattedDate = dateFormat.format[date];

        model.addAttribute["serverTime", formattedDate];

Điều này có nghĩa người dùng truy cập request URL này với phương thức GET.

Enum org.springframework.web.bind.annotation.RequestMethod chính là đối tượng định nghĩa các request method cho Spring MVC.

Các method mà annotation @RequestMapping hỗ trợ được định nghĩa trong enum org.springframework.web.bind.annotation.RequestMethod như sau:

  • GET
  • HEAD
  • POST
  • PUT
  • PATCH
  • DELETE
  • OPTIONS
  • TRACE

Hãy xem thêm một ví dụ nữa nhé các bạn.

@RequestMapping[value = "doLogin", method = RequestMethod.POST] public String doLogin[HttpServletRequest request] { return "home"; }

@RequestMapping[value = "doLogin", method = RequestMethod.POST]

public String doLogin[HttpServletRequest request] {

Như các bạn thấy, ở đây mình đã định nghĩa 1 request với POST method.

Mặc định khi sử dụng annotation @RequestMapping, nếu bạn không định nghĩa thuộc tính method thì request method sẽ là GET, POST hoặc HEAD. Ngoài những request method này, nếu các bạn request với các request method khác thì sẽ bị lỗi 405 ngay.

Ví dụ:

package com.huongdanjava.springmvc; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * Handles requests for the application home page. */ @Controller public class HomeController { private static final Logger logger = LoggerFactory.getLogger[HomeController.class]; /** * Simply selects the home view to render by returning its name. */ @RequestMapping[value = "home"] public String home[Locale locale, Model model] { logger.info["Welcome home! The client locale is {}.", locale]; Date date = new Date[]; DateFormat dateFormat = DateFormat.getDateTimeInstance[DateFormat.LONG, DateFormat.LONG, locale]; String formattedDate = dateFormat.format[date]; model.addAttribute["serverTime", formattedDate]; return "home"; } }

package com.huongdanjava.springmvc;

import java.text.DateFormat;

import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

* Handles requests for the application home page.

public class HomeController {

    private static final Logger logger = LoggerFactory.getLogger[HomeController.class];

     * Simply selects the home view to render by returning its name.

    @RequestMapping[value = "home"]

    public String home[Locale locale, Model model] {

        logger.info["Welcome home! The client locale is {}.", locale];

        DateFormat dateFormat = DateFormat.getDateTimeInstance[DateFormat.LONG, DateFormat.LONG, locale];

        String formattedDate = dateFormat.format[date];

        model.addAttribute["serverTime", formattedDate];

Kết quả:

Hoặc

Từ phiên bản 4.3 trở đi, Spring giới thiệu một số annotation để chúng ta dễ dàng khai báo request method hơn. Đó là các annotation sau:

  • Annotation @GetMapping cho method GET.
  • Annotation @PostMapping cho method POST.
  • Annotation @PutMapping cho method PUT.
  • Annotation @DeleteMapping cho method DELETE.
  • Annotation @PatchMapping cho method PATCH.

Bây giờ thì chúng ta không cần phải khai báo:

@RequestMapping[value = "/", method = RequestMethod.GET]

@RequestMapping[value = "/", method = RequestMethod.GET]

mà chỉ cần khai báo:

Nếu các bạn xem code của annotation @GetMapping thì các bạn sẽ hiểu tại sao chúng ta chỉ cần sử dụng annotation @GetMapping mà không cần sử dụng annotation @RequestMapping nữa.

/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 [the "License"]; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * //www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.bind.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; /** * Annotation for mapping HTTP {@code GET} requests onto specific handler * methods. * *

Specifically, {@code @GetMapping} is a composed annotation that * acts as a shortcut for {@code @RequestMapping[method = RequestMethod.GET]}. * * * @author Sam Brannen * @since 4.3 * @see PostMapping * @see PutMapping * @see DeleteMapping * @see PatchMapping * @see RequestMapping */ @Target[ElementType.METHOD] @Retention[RetentionPolicy.RUNTIME] @Documented @RequestMapping[method = RequestMethod.GET] public @interface GetMapping { /** * Alias for {@link RequestMapping#name}. */ @AliasFor[annotation = RequestMapping.class] String name[] default ""; /** * Alias for {@link RequestMapping#value}. */ @AliasFor[annotation = RequestMapping.class] String[] value[] default {}; /** * Alias for {@link RequestMapping#path}. */ @AliasFor[annotation = RequestMapping.class] String[] path[] default {}; /** * Alias for {@link RequestMapping#params}. */ @AliasFor[annotation = RequestMapping.class] String[] params[] default {}; /** * Alias for {@link RequestMapping#headers}. */ @AliasFor[annotation = RequestMapping.class] String[] headers[] default {}; /** * Alias for {@link RequestMapping#consumes}. * @since 4.3.5 */ @AliasFor[annotation = RequestMapping.class] String[] consumes[] default {}; /** * Alias for {@link RequestMapping#produces}. */ @AliasFor[annotation = RequestMapping.class] String[] produces[] default {}; }

* Copyright 2002-2016 the original author or authors.

* Licensed under the Apache License, Version 2.0 [the "License"];

* you may not use this file except in compliance with the License.

* You may obtain a copy of the License at

*      //www.apache.org/licenses/LICENSE-2.0

* Unless required by applicable law or agreed to in writing, software

* distributed under the License is distributed on an "AS IS" BASIS,

* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

* See the License for the specific language governing permissions and

* limitations under the License.

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

import org.springframework.core.annotation.AliasFor;

* Annotation for mapping HTTP {@code GET} requests onto specific handler

*

Specifically, {@code @GetMapping} is a composed annotation that

* acts as a shortcut for {@code @RequestMapping[method = RequestMethod.GET]}.

@Target[ElementType.METHOD]

@Retention[RetentionPolicy.RUNTIME]

@RequestMapping[method = RequestMethod.GET]

public @interface GetMapping {

* Alias for {@link RequestMapping#name}.

@AliasFor[annotation = RequestMapping.class]

String name[] default "";

* Alias for {@link RequestMapping#value}.

@AliasFor[annotation = RequestMapping.class]

String[] value[] default {};

* Alias for {@link RequestMapping#path}.

@AliasFor[annotation = RequestMapping.class]

String[] path[] default {};

* Alias for {@link RequestMapping#params}.

@AliasFor[annotation = RequestMapping.class]

String[] params[] default {};

* Alias for {@link RequestMapping#headers}.

@AliasFor[annotation = RequestMapping.class]

String[] headers[] default {};

* Alias for {@link RequestMapping#consumes}.

@AliasFor[annotation = RequestMapping.class]

String[] consumes[] default {};

* Alias for {@link RequestMapping#produces}.

@AliasFor[annotation = RequestMapping.class]

String[] produces[] default {};

Video liên quan

Chủ Đề