Spring Boot REST method not allowed











up vote
0
down vote

favorite












I'm trying to implement a method that will allow users (including anonymous) to read reviews about certain items. I want to use two path variables so I don't repeat myself with the code. That's how the Controller method looks like:



@RestController("/reviews")
@AllArgsConstructor
public class ReviewController {


@Autowired
private ReviewService reviewService;

@GetMapping("/{type}/{id}")
public ReviewDTO readReview(@PathVariable String type, @PathVariable long id) {
return reviewService.readReview(type, id);
}


Each type has its own entity, so I want to use the type variable to determine, which repository should be used. Here's the implementation of the ReviewService.readReview method:



public ReviewDTO readReview(String type, long id) {
switch (type) {
case "rides":
return new RideReviewDTO(findRideReview(id));
case "beacons":
return new TransceiverReviewDTO(findTransceiverReview(id));
case "backpacks":
return null;
default:
return null;
}
}


When I'm running tests, the request looks exacly as it should:



MockHttpServletRequest:
HTTP Method = GET
Request URI = /reviews/rides/1
Parameters = {}
Headers = {}
Body = null


I'm getting an error though. This is the response I'm getting when trying to perform this request in Postman:



{
"timestamp": "2018-11-20T07:08:39.145+0000",
"status": 405,
"error": "Method Not Allowed",
"message": "Request method 'GET' not supported",
"path": "/api/reviews/rides/1"
}


And this is the full reponse I get from test MockMvc:



MockHttpServletResponse:
Status = 405
Error message = Request method 'GET' not supported
Headers = {Allow=[POST], X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies =


I'm not sure what's wrong, when trying to debug, the method in the controller isn't even reached. That's how I configured my security configuration:



@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private PowderizeUserDetailsService userDetailsService;

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.headers().and()
.authorizeRequests()
.antMatchers("/users", "/users/confirm/**", "/users/forgotPassword").anonymous()
.antMatchers(HttpMethod.GET, "/reviews/*").permitAll()
.anyRequest().authenticated().and()
.httpBasic().and()
.logout().permitAll().and()
.csrf().disable();
}


EDIT



The answer given by @Alien was correct one, but there was also one more issue - in the security configuration method, the pattern .antMatchers(HttpMethod.GET, "/reviews/*").permitAll() was also bad. there should be /reviews/**, otherwise the requests would not include the below directories.










share|improve this question




























    up vote
    0
    down vote

    favorite












    I'm trying to implement a method that will allow users (including anonymous) to read reviews about certain items. I want to use two path variables so I don't repeat myself with the code. That's how the Controller method looks like:



    @RestController("/reviews")
    @AllArgsConstructor
    public class ReviewController {


    @Autowired
    private ReviewService reviewService;

    @GetMapping("/{type}/{id}")
    public ReviewDTO readReview(@PathVariable String type, @PathVariable long id) {
    return reviewService.readReview(type, id);
    }


    Each type has its own entity, so I want to use the type variable to determine, which repository should be used. Here's the implementation of the ReviewService.readReview method:



    public ReviewDTO readReview(String type, long id) {
    switch (type) {
    case "rides":
    return new RideReviewDTO(findRideReview(id));
    case "beacons":
    return new TransceiverReviewDTO(findTransceiverReview(id));
    case "backpacks":
    return null;
    default:
    return null;
    }
    }


    When I'm running tests, the request looks exacly as it should:



    MockHttpServletRequest:
    HTTP Method = GET
    Request URI = /reviews/rides/1
    Parameters = {}
    Headers = {}
    Body = null


    I'm getting an error though. This is the response I'm getting when trying to perform this request in Postman:



    {
    "timestamp": "2018-11-20T07:08:39.145+0000",
    "status": 405,
    "error": "Method Not Allowed",
    "message": "Request method 'GET' not supported",
    "path": "/api/reviews/rides/1"
    }


    And this is the full reponse I get from test MockMvc:



    MockHttpServletResponse:
    Status = 405
    Error message = Request method 'GET' not supported
    Headers = {Allow=[POST], X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]}
    Content type = null
    Body =
    Forwarded URL = null
    Redirected URL = null
    Cookies =


    I'm not sure what's wrong, when trying to debug, the method in the controller isn't even reached. That's how I configured my security configuration:



    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(jsr250Enabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PowderizeUserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http
    .cors().and()
    .headers().and()
    .authorizeRequests()
    .antMatchers("/users", "/users/confirm/**", "/users/forgotPassword").anonymous()
    .antMatchers(HttpMethod.GET, "/reviews/*").permitAll()
    .anyRequest().authenticated().and()
    .httpBasic().and()
    .logout().permitAll().and()
    .csrf().disable();
    }


    EDIT



    The answer given by @Alien was correct one, but there was also one more issue - in the security configuration method, the pattern .antMatchers(HttpMethod.GET, "/reviews/*").permitAll() was also bad. there should be /reviews/**, otherwise the requests would not include the below directories.










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I'm trying to implement a method that will allow users (including anonymous) to read reviews about certain items. I want to use two path variables so I don't repeat myself with the code. That's how the Controller method looks like:



      @RestController("/reviews")
      @AllArgsConstructor
      public class ReviewController {


      @Autowired
      private ReviewService reviewService;

      @GetMapping("/{type}/{id}")
      public ReviewDTO readReview(@PathVariable String type, @PathVariable long id) {
      return reviewService.readReview(type, id);
      }


      Each type has its own entity, so I want to use the type variable to determine, which repository should be used. Here's the implementation of the ReviewService.readReview method:



      public ReviewDTO readReview(String type, long id) {
      switch (type) {
      case "rides":
      return new RideReviewDTO(findRideReview(id));
      case "beacons":
      return new TransceiverReviewDTO(findTransceiverReview(id));
      case "backpacks":
      return null;
      default:
      return null;
      }
      }


      When I'm running tests, the request looks exacly as it should:



      MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /reviews/rides/1
      Parameters = {}
      Headers = {}
      Body = null


      I'm getting an error though. This is the response I'm getting when trying to perform this request in Postman:



      {
      "timestamp": "2018-11-20T07:08:39.145+0000",
      "status": 405,
      "error": "Method Not Allowed",
      "message": "Request method 'GET' not supported",
      "path": "/api/reviews/rides/1"
      }


      And this is the full reponse I get from test MockMvc:



      MockHttpServletResponse:
      Status = 405
      Error message = Request method 'GET' not supported
      Headers = {Allow=[POST], X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]}
      Content type = null
      Body =
      Forwarded URL = null
      Redirected URL = null
      Cookies =


      I'm not sure what's wrong, when trying to debug, the method in the controller isn't even reached. That's how I configured my security configuration:



      @Configuration
      @EnableWebSecurity
      @EnableGlobalMethodSecurity(jsr250Enabled = true)
      public class SecurityConfig extends WebSecurityConfigurerAdapter {

      @Autowired
      private PowderizeUserDetailsService userDetailsService;

      @Override
      protected void configure(HttpSecurity http) throws Exception {
      http
      .cors().and()
      .headers().and()
      .authorizeRequests()
      .antMatchers("/users", "/users/confirm/**", "/users/forgotPassword").anonymous()
      .antMatchers(HttpMethod.GET, "/reviews/*").permitAll()
      .anyRequest().authenticated().and()
      .httpBasic().and()
      .logout().permitAll().and()
      .csrf().disable();
      }


      EDIT



      The answer given by @Alien was correct one, but there was also one more issue - in the security configuration method, the pattern .antMatchers(HttpMethod.GET, "/reviews/*").permitAll() was also bad. there should be /reviews/**, otherwise the requests would not include the below directories.










      share|improve this question















      I'm trying to implement a method that will allow users (including anonymous) to read reviews about certain items. I want to use two path variables so I don't repeat myself with the code. That's how the Controller method looks like:



      @RestController("/reviews")
      @AllArgsConstructor
      public class ReviewController {


      @Autowired
      private ReviewService reviewService;

      @GetMapping("/{type}/{id}")
      public ReviewDTO readReview(@PathVariable String type, @PathVariable long id) {
      return reviewService.readReview(type, id);
      }


      Each type has its own entity, so I want to use the type variable to determine, which repository should be used. Here's the implementation of the ReviewService.readReview method:



      public ReviewDTO readReview(String type, long id) {
      switch (type) {
      case "rides":
      return new RideReviewDTO(findRideReview(id));
      case "beacons":
      return new TransceiverReviewDTO(findTransceiverReview(id));
      case "backpacks":
      return null;
      default:
      return null;
      }
      }


      When I'm running tests, the request looks exacly as it should:



      MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /reviews/rides/1
      Parameters = {}
      Headers = {}
      Body = null


      I'm getting an error though. This is the response I'm getting when trying to perform this request in Postman:



      {
      "timestamp": "2018-11-20T07:08:39.145+0000",
      "status": 405,
      "error": "Method Not Allowed",
      "message": "Request method 'GET' not supported",
      "path": "/api/reviews/rides/1"
      }


      And this is the full reponse I get from test MockMvc:



      MockHttpServletResponse:
      Status = 405
      Error message = Request method 'GET' not supported
      Headers = {Allow=[POST], X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]}
      Content type = null
      Body =
      Forwarded URL = null
      Redirected URL = null
      Cookies =


      I'm not sure what's wrong, when trying to debug, the method in the controller isn't even reached. That's how I configured my security configuration:



      @Configuration
      @EnableWebSecurity
      @EnableGlobalMethodSecurity(jsr250Enabled = true)
      public class SecurityConfig extends WebSecurityConfigurerAdapter {

      @Autowired
      private PowderizeUserDetailsService userDetailsService;

      @Override
      protected void configure(HttpSecurity http) throws Exception {
      http
      .cors().and()
      .headers().and()
      .authorizeRequests()
      .antMatchers("/users", "/users/confirm/**", "/users/forgotPassword").anonymous()
      .antMatchers(HttpMethod.GET, "/reviews/*").permitAll()
      .anyRequest().authenticated().and()
      .httpBasic().and()
      .logout().permitAll().and()
      .csrf().disable();
      }


      EDIT



      The answer given by @Alien was correct one, but there was also one more issue - in the security configuration method, the pattern .antMatchers(HttpMethod.GET, "/reviews/*").permitAll() was also bad. there should be /reviews/**, otherwise the requests would not include the below directories.







      rest http spring-boot servlets






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 at 8:26

























      asked Nov 20 at 7:22









      Jack_Russell

      9411




      9411
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          Try to Change



          @RestController("/reviews")
          @AllArgsConstructor
          public class ReviewController


          to



          @RestController
          @RequestMapping("/reviews")
          @AllArgsConstructor
          public class ReviewController


          by specifying the base url in @RequestMapping instead of @RestController.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53388085%2fspring-boot-rest-method-not-allowed%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            Try to Change



            @RestController("/reviews")
            @AllArgsConstructor
            public class ReviewController


            to



            @RestController
            @RequestMapping("/reviews")
            @AllArgsConstructor
            public class ReviewController


            by specifying the base url in @RequestMapping instead of @RestController.






            share|improve this answer



























              up vote
              1
              down vote



              accepted










              Try to Change



              @RestController("/reviews")
              @AllArgsConstructor
              public class ReviewController


              to



              @RestController
              @RequestMapping("/reviews")
              @AllArgsConstructor
              public class ReviewController


              by specifying the base url in @RequestMapping instead of @RestController.






              share|improve this answer

























                up vote
                1
                down vote



                accepted







                up vote
                1
                down vote



                accepted






                Try to Change



                @RestController("/reviews")
                @AllArgsConstructor
                public class ReviewController


                to



                @RestController
                @RequestMapping("/reviews")
                @AllArgsConstructor
                public class ReviewController


                by specifying the base url in @RequestMapping instead of @RestController.






                share|improve this answer














                Try to Change



                @RestController("/reviews")
                @AllArgsConstructor
                public class ReviewController


                to



                @RestController
                @RequestMapping("/reviews")
                @AllArgsConstructor
                public class ReviewController


                by specifying the base url in @RequestMapping instead of @RestController.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 20 at 7:34

























                answered Nov 20 at 7:27









                Alien

                4,41521023




                4,41521023






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53388085%2fspring-boot-rest-method-not-allowed%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    404 Error Contact Form 7 ajax form submitting

                    How to know if a Active Directory user can login interactively

                    TypeError: fit_transform() missing 1 required positional argument: 'X'