Spring Boot - 不允许发布方法,但GET有效

时间:2018-06-08 08:52:26

标签: java spring spring-boot jpa

我的spring boot mysql项目出了问题, 控制器类只能找到METHOD GET(get all),但我似乎无法发布 并得到错误405:方法" POST"不允许

继承我的控制器类:

package com.example.demo.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.demo.Blog;

import java.util.List;

@Repository
public interface BlogRespository extends JpaRepository<Blog, Integer> {

    // custom query to search to blog post by title or content
    List<Blog> findByTitleContainingOrContentContaining(String text, String textAgain);

}

如果你需要的话,继承我的存储库类

Managed Jenkins > Global Tools configuration

我正在尝试使用SoapUI的POST请求,似乎无法找到解决方案,非常感谢

5 个答案:

答案 0 :(得分:1)

您可能希望考虑搜索方法的consumes属性,以告知spring您希望该方法使用哪个Content-Type。例如@PostMapping(value="/blog/search", consumes=org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE)

看一下org.springframework.http.converter.HttpMessageConverter的实现。 org.springframework.http.converter.FormHttpMessageConverter impl之类的内容会将请求正文转换为MultiValueMap<String,?>

您还可以使用以下示例:Spring MVC - How to get all request params in a map in Spring controller?使用@RequestParam注释而不是@RequestBody

您是否可以发布展示curl响应的示例HTTP 405请求 - 我认为您要发布到/blog/search端点?

答案 1 :(得分:0)

如果已配置或启用csrf,则不会允许方法发布 那么您需要在发布表单或数据时提供有效的csrf

检查您的弹簧安全配置 例如

    @Configuration
    @EnableWebSecurity
    @ComponentScan(basePackageClasses = CustomUserDetailsService.class)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    .....

RequestMatcher csrfRequestMatcher = new RequestMatcher() {
        // Enabled CSFR protection on the following urls:
        //@formatter:off
        private AntPathRequestMatcher[] requestMatchers = 
            {
                new AntPathRequestMatcher("/**/verify"),
                        new AntPathRequestMatcher("/**/login*")
            };
        //@formatter:off

        @Override
        public boolean matches(final HttpServletRequest request) {
            // If the request match one url the CSFR protection will be enabled
            for (final AntPathRequestMatcher rm : requestMatchers) {
                if (rm.matches(request)) {
                    System.out.println();
                    /* return true; */
                }
            }
            return false;
        } // method matches
    };
@Override
    protected void configure(final HttpSecurity http) throws Exception {
        //@formatter:off

        http.headers().frameOptions().sameOrigin()
        .and()
        .authorizeRequests()
        .antMatchers("/","/css/**", "/static/**", "/view/**", "**/error/**").permitAll()
        .anyRequest().authenticated()
        .and()
        .formLogin().loginPage("/mvc/login").permitAll() 
        .authenticationDetailsSource(authenticationDetailsSource())
        .successHandler(authenticationSuccessHandler)
        .usernameParameter("username").passwordParameter("password")
        .and()
        .logout().permitAll()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .addLogoutHandler(customLogoutHandler)
        .logoutSuccessHandler(customLogoutSuccessHandler)
        .logoutSuccessUrl("/login?logout")
        .and()
        .exceptionHandling()
        .accessDeniedPage("/403")
                .and()
                .csrf()/* .requireCsrfProtectionMatcher(csrfRequestMatcher) */
        .ignoringAntMatchers("/crud/**","/view/**")
    ;
        // @formatter:off


    }

由于

答案 2 :(得分:0)

我试着通过编写一个虚拟代码来重现这个问题,但它对我来说非常好。

请在下面找到我尝试的代码段 -

package com.pradeep.rest.controller;

import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RestRequestController {

    @GetMapping("/blog")
    public String show() {
        String result = "Hello from show";
        return result;
    }

    @PostMapping("/blog")
    public String create(@RequestBody Map<String, String> body) {
        String title = body.get("title");
        String content = body.get("content");
        String result = "title= " + title + " : content= " + content;
        return result;
    }
}

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.pradeep.rest</groupId>
    <artifactId>RestApi</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- to ease development environment -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>
</project>

输入和输出片段:

enter image description here

答案 3 :(得分:0)

我的审判非常顺利Postman

这是我的控制器。 我遵循了本教程Spring Boot Angular

package io.crzn.myNotes.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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 io.crzn.myNotes.exception.ResourceNotFoundException;
import io.crzn.myNotes.model.MyNotes;
import io.crzn.myNotes.repository.myNotesRepository;

@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/api/v1")
public class myNotesController {

    @Autowired
    private myNotesRepository mynotesRepository;

    @GetMapping("/mynotes")
    public List<MyNotes> getAllmyNotes(){
        return mynotesRepository.findAll();
    }

    @GetMapping("/mynotes/{id}")
    public ResponseEntity<MyNotes> getEmployeeById(@PathVariable(value = "id") Long mynotesId)
        throws ResourceNotFoundException{
        MyNotes mynotes = mynotesRepository.findById(mynotesId)
                .orElseThrow(() -> new ResourceNotFoundException("Note not found for this id : :" + mynotesId));
        return ResponseEntity.ok().body(mynotes);
    }

    @PostMapping("/mynotes")
    public MyNotes createMyNotes(@Valid @RequestBody MyNotes mynotes) {
        return mynotesRepository.save(mynotes);
    }

    @PutMapping("/mynotes/{id}")
    public ResponseEntity<MyNotes> updateMyNotes(@PathVariable(value = "id") Long mynotesId,
            @Valid @RequestBody MyNotes mynotesDetails)
                    throws ResourceNotFoundException{
        MyNotes mynotes = mynotesRepository.findById(mynotesId)
                .orElseThrow(() -> new ResourceNotFoundException("Not not found for this id : : " + mynotesId));

        mynotes.setstatus(mynotesDetails.getstatus());
        mynotes.setbody(mynotesDetails.getbody());
        mynotes.settitle(mynotesDetails.gettitle());
        final MyNotes updatedMyNotes = mynotesRepository.save(mynotes);
        return ResponseEntity.ok(updatedMyNotes);
    }

    @DeleteMapping("/mynotes/{id}")
    public Map<String, Boolean> deleteMyNotes(@PathVariable(value = "id") Long mynotesId)
            throws ResourceNotFoundException{
        MyNotes mynotes = mynotesRepository.findById(mynotesId)
                .orElseThrow(() -> new ResourceNotFoundException("Not not found for this id : : " + mynotesId));

        mynotesRepository.delete(mynotes);
        Map<String, Boolean> response = new HashMap<>();
        response.put("deleted", Boolean.TRUE);
        return response;

    }




}

答案 4 :(得分:0)

我遇到了同样的错误,我可以在不允许 POST 方法的情况下发出 GET 请求,后来我发现在登台服务器中启用了 SSL,因此刚刚更改 “http”到“https”并使其工作