简体   繁体   中英

Springboot submit not finding controller

When I click submit on my HTML form it is not hitting the /greeting endpoint

@org.springframework.stereotype.Controller
@EnableAutoConfiguration

public class Controller {
    @Autowired
    assessment.PdfGeneratorUtil pdfGenaratorUtil;

    @GetMapping ("/")
    String home() {
    return "static/assessment.html";
    }

    @PostMapping("/greeting")
    public String greetingSubmit() {

        Map<String,String> data = new HashMap<String,String>();
        data.put("name","James");

Thymeleaf config

 @Configuration
public class TheymeLeafConfiguration {
    @Bean
    public ClassLoaderTemplateResolver emailTemplateResolver(){
        ClassLoaderTemplateResolver emailTemplateResolver=new  ClassLoaderTemplateResolver();
            emailTemplateResolver.setPrefix("templates/");
            emailTemplateResolver.setTemplateMode("HTML5");
            emailTemplateResolver.setSuffix(".html");
            emailTemplateResolver.setTemplateMode("XHTML");
            emailTemplateResolver.setCharacterEncoding("UTF-8");
            emailTemplateResolver.setOrder(1);
            return emailTemplateResolver;
        }
    }

And a snippet of the html:

<form action="#" th:action="@{/greeting}" method="post">

Which when I submit the form doesn't hit the breakpoint on the POST controller (the same line as the Map) and I get a 405 in the browser:

There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'POST' not supported

The URL in the browser after submit is:

http://localhost:8080/assessment.html#

Project structure:

在此处输入图片说明

UPDATE

It is working with this code, in so far as it hits the Get controller method, and also the Post controller method on submission. I am not quite sure what changed.

Note I am not using @ModelAttribute at this point in time since I was testing that the controller methods are getting called at the correct times.

    @GetMapping("/greeting")
String greetingForm() {
    return "assessment";
}

@PostMapping("/greeting")
public String greetingSubmit() {

    System.out.println(" HELLLOO HELLOOOO ");
    Map<String,String> data = new HashMap<String,String>();
    data.put("name","James");
    try {
        pdfGenaratorUtil.createPdf("greeting",data);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "finished";
}

With the minimal details that you have given in your code, I will try to answer your question.

  1. The first problem that I see in your code is you are not passing any value to the method with postmapping, which I see at odd as post are used to create resource in rest.

So if you want to map the values received from input to some model data you need to do it using @ModelAttribute annotation.

@PostMapping("/greeting")
public String greetingSubmit(@ModelAttribute Greeting greeting) {

    return "greeting";
}

See Spring boot form handling

  1. Check whether your template webpages are found. I dont see any page mapping to show the result of this submission. So you need to return some page name where your browser will forward the response of your form submission. So if you dont add that, spring find the method, executes the code, but dont know where to redirect. In this case as well it shows the 415 HttpStatus code .

So add something like below:

    return "greeting";

So this above code will look for /templates/greeting.html as per your resolver configuration.

  1. I assume you are also using spring security in your project ( assumption from screenshot. [class SecurityConfig.] )

If you use spring security, the CSRF filter is enabled by default in spring-boot. So either you need to disable it or add csrf param in your login form post request. (recommended). For the remaining forms, CSRF token will be automatically added to forms with hidden input.

To Disable CSRF:

In your spring securityConfig disable the csrf protection on HttpSecurity object something like below:

@Override
protected void configure(HttpSecurity http) throws Exception {
   http        
      .formLogin()
                .loginProcessingUrl("/authentication")
                .usernameParameter("j_username")
                .passwordParameter("j_password").permitAll()
                .and()
      .csrf().disable()

}

Or To add csrf in your login form as below:

input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM