• [Java Spring MVC] @PathVariable, @Vallidated, @PostMapping & @ResponseStatus


    Controller:

    package com.example.ec.web;
    
    import com.example.ec.domain.Tour;
    import com.example.ec.domain.TourRating;
    import com.example.ec.domain.TourRatingPk;
    import com.example.ec.repo.TourRatingRepository;
    import com.example.ec.repo.TourRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.NoSuchElementException;
    
    @RestController
    @RequestMapping(path = "/tours/{tourId}/ratings")
    public class TourRatingController {
        TourRatingRepository tourRatingRepository;
        TourRepository tourRepository;
    
        @Autowired
        public TourRatingController(TourRatingRepository tourRatingRepository, TourRepository tourRepository) {
            this.tourRatingRepository = tourRatingRepository;
            this.tourRepository = tourRepository;
        }
    
        protected TourRatingController() {}
    
        @PostMapping
        @ResponseStatus(HttpStatus.CREATED)
        public void createTourRating(@PathVariable(value = "tourId") int tourId, @RequestBody @Validated RatingDto ratingDto) {
            Tour tour = verifyTour(tourId);
            tourRatingRepository.save(new TourRating( new TourRatingPk(tour, ratingDto.getCustomerId()), ratingDto.getScore(), ratingDto.getComment()));
        }
    
        /**
         * Verify and return the Tour given a tourId.
         *
         * @param tourId tour identifier
         * @return the found Tour
         * @throws NoSuchElementException if no Tour found.
         */
        private Tour verifyTour(int tourId) throws NoSuchElementException {
            return tourRepository.findById(tourId).orElseThrow(() ->
                    new NoSuchElementException("Tour does not exist " + tourId));
        }
    
        /**
         * Exception handler if NoSuchElementException is thrown in this Controller
         *
         * @param ex exception
         * @return Error message String.
         */
        @ResponseStatus(HttpStatus.NOT_FOUND)
        @ExceptionHandler(NoSuchElementException.class)
        public String return400(NoSuchElementException ex) {
            return ex.getMessage();
    
        }
    }

    DTO:

    package com.example.ec.web;
    import com.example.ec.domain.TourRating;
    import javax.validation.constraints.Max;
    import javax.validation.constraints.Min;
    import javax.validation.constraints.NotNull;
    import javax.validation.constraints.Size;
    /**
     * Data Transfer Object for Rating a Tour
     * */
    
    public class RatingDto {
    
        @Min(0)
        @Max(5)
        private Integer score;
    
        @Size(max = 255)
        private String comment;
    
        @NotNull
        private Integer customerId;
    
        /**
         * Construct a RatingDto from a fully instantiated TourRating.
         *
         * @param tourRating Tour Rating Object
         */
        public RatingDto(TourRating tourRating) {
            this(tourRating.getScore(), tourRating.getComment(), tourRating.getPk().getCustomerId());
        }
        /**
         * Constructor to fully initialize the RatingDto
         *
         * @param score score 1-5
         * @param comment comment
         * @param customerId customer identifier
         */
        private RatingDto(Integer score, String comment, Integer customerId) {
            this.score = score;
            this.comment = comment;
            this.customerId = customerId;
        }
    
        protected RatingDto() {}
    
        public Integer getScore() {
            return score;
        }
    
        public void setScore(Integer score) {
            this.score = score;
        }
    
        public String getComment() {
            return comment;
        }
    
        public void setComment(String comment) {
            this.comment = comment;
        }
    
        public Integer getCustomerId() {
            return customerId;
        }
    
        public void setCustomerId(Integer customerId) {
            this.customerId = customerId;
        }
    }
            <dependency>
                <groupId>javax.validation</groupId>
                <artifactId>validation-api</artifactId>
                <version>2.0.1.Final</version>
            </dependency>
  • 相关阅读:
    java基于redis事务的秒杀实现
    redis事务
    java 根据经纬度坐标计算两点的距离算法
    Spring ElasticsearchTemplate 经纬度按距离排序
    springboot springmvc拦截器 拦截POST、PUT、DELETE请求参数和响应数据,并记录操作日志
    jpa Auditor 自动赋值与自定义 @CreatedBy @LastModifiedBy @CreatedDate @LastModifiedDate
    docker安装elasticsearch
    win10中使用 Windows照片查看器
    Springboot 项目启动后执行某些自定义代码
    SimpleDateFormat 线程不安全及解决方案
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14136605.html
Copyright © 2020-2023  润新知