PostMapping Spring загрузочная аннотация не работает - PullRequest
0 голосов
/ 09 апреля 2020

Я новичок в весенней загрузке и не знаю, почему мой @PostMapping не работает и приводит к ошибке белой метки. Все остальное работает нормально, и я могу добавлять клиентов в базу данных h2. Однако, как только я добавляю клиентов и go к URL localhost: 8084 / getdetails и вводу 1, возникает ошибка белого ярлыка. Однако форма в файле ViewCustomers. jsp по-прежнему отображается, но не может принимать никаких входных данных. Форма должна вызывать toString () объекта customer и его полей.

Контроллер

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class FormController {
  @Autowired
  CustomerRepo repo;

  @RequestMapping("/")
  public String details() {
    return "edureka";
  }

  @RequestMapping("/details")
  public String details(Customers customers) {
    repo.save(customers);
    return "edureka";
  }

  @RequestMapping("/getdetails")
  public String getdetails() {
    return "ViewCustomers";
  }

  @PostMapping("/getdetails")
  public ModelAndView getdetails(@RequestParam int cid) {
    System.out.println("here");
    ModelAndView mv = new ModelAndView("Retrieve");
    Customers customers = repo.findById(cid).orElse(null);
    mv.addObject(customers);
    return mv;
  }
}

edureka. jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Edureka Customers</title>
</head>
<body>
    <form method="post" action="details">
        Enter Customer ID: <input type="text" name="cid"><br><br>
        Enter Customer Name: <input type="text" name="cname"><br><br>    
        Enter Customer Email Address: <input type="email" name="cemail"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

ViewCustomer. jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>View Customer Details</h1>
    <h2>Details as submitted as follows</h2>
    <form method="getdetails" action="post">
        <input type="number" name="cid"><br> 
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Получить. jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>Retrieve Customer Details</h1>
    <h2>Details as submitted as follows:</h2>
    <h5>${customers}</h5>
</body>
</html>

Клиенты. java

package com.example.demo;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Customers {
  @Id
  private int cid;
  private String cname;
  private String cemail;

  public int getCid() {
    return cid;
  }

  public void setCid(int cid) {
    this.cid = cid;
  }

  public String getCname() {
    return cname;
  }

  public void setCname(String cname) {
    this.cname = cname;
  }

  public String getCemail() {
    return cemail;
  }

  public void setCemail(String cemail) {
    this.cemail = cemail;
  }

  @Override
  public String toString() {
    return "Customers [cid=" + cid + ", cname=" + cname + ", cemail=" + cemail + "]";
  }
}

Пакет интерфейса CustomerRepo com.example.demo;

import org.springframework.data.repository.CrudRepository;

public interface CustomerRepo extends CrudRepository<Customers,Integer>{

}

SubmissionFormApplication. java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import com.example.demo.SubmissionFormApplication;

@ComponentScan
@SpringBootApplication
public class SubmissionFormApplication extends SpringBootServletInitializer{
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
      return application.sources(SubmissionFormApplication.class);
    }
    public static void main(String[] args) {
        SpringApplication.run(SubmissionFormApplication.class, args);
    }

}

пом. xml

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.13.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>SubmissionForm</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SubmissionForm</name>
    <description>First Spring Boot Web app</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jersey</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jasper</artifactId>
            <version>9.0.31</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Ответы [ 3 ]

1 голос
/ 09 апреля 2020

Метод формы ViewCustomer.jsp должен иметь метод как post и действие как get details. Проблема в html а не в пружине.

0 голосов
/ 09 апреля 2020

Несколько вещей:

  1. Ваш контроллер может быть аннотирован как @RestController вместо просто @Controller.

  2. Ваши отображения для POST - это @PostMapping - Для согласованности я бы порекомендовал, чтобы ваше сопоставление для GET было @GetMapping - Поэтому я бы заменил все @RequestMapping на @GetMapping (это устраняет неоднозначность и улучшает читаемость)

  3. Форма в eureka.jsp должна изменить URL-адрес, на который отправляется сообщение. Вместо action=details он должен указывать на action=getdetails

  4. Форма, на ваш взгляд, viewcustomer.jsp имеет действие и сообщение переключено (метод должен быть POST действие должно быть getdetails)

0 голосов
/ 09 апреля 2020

@PostMapping("/getdetails") отображается на путь "/getdetails". Такое отображение уже существует. Попробуйте сопоставить с другим путем, чтобы разрешить этот конфликт.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...