简体   繁体   English

我怎样才能使我的表格需要某些字段

[英]How can I make it so that my form requires certain fields

I am trying to make a Spring Boot project that works like an e-commerce website.我正在尝试制作一个像电子商务网站一样工作的 Spring Boot 项目。

In the forms for creating and editing a product, I want to make it so that all fields are required, because if I do not input a price, then I get the "Whitelabel Error Page: This application has no explicit mapping for /error, so you are seeing this as a fallback."在用于创建和编辑产品的 forms 中,我想让所有字段都为必填项,因为如果我不输入价格,则会收到“Whitelabel 错误页面:此应用程序没有针对 /error 的显式映射,所以你将其视为后备方案。” error.错误。

Main class主 class

@SpringBootApplication
public class EcommerceWebsiteApplication {

    public static void main(String[] args) {
        SpringApplication.run(EcommerceWebsiteApplication.class, args);
    }

}

ProductController产品控制器

/**This is the product controller class. It has different mappings as well as the methods that allow 
 * the user to perform the different CRUD operations with regard to the products. */
@Controller
public class ProductController {

    @Autowired
    ProductRepository productRepository;

    @RequestMapping("/product")
    public String product(Model model) {
        model.addAttribute("products", productRepository.findAll());

        return "product";
    }

    @RequestMapping("/create")
    public String create(Model model) {
        return "create";
    }
 
    @RequestMapping("/save")
    public String save(@RequestParam String prodName, @RequestParam String prodDesc, @RequestParam Double prodPrice, @RequestParam String prodImage) {
        Product product = new Product();
        product.setProdName(prodName);
        product.setProdDesc(prodDesc);
        product.setProdPrice(prodPrice);
        product.setProdImage(prodImage);
        
        productRepository.save(product);
        
        return "redirect:/show/" + product.getId();
    }
    
    @RequestMapping("/show/{id}")
    public String show(@PathVariable String id, Model model) {
        model.addAttribute("product", productRepository.findById(id).get());
       
        return "show";
    }
    
    @RequestMapping("/delete")
    public String delete(@RequestParam String id) {
        Optional<Product> product = productRepository.findById(id);
        productRepository.delete(product.get());

        return "redirect:/product";
    }
    
    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable String id, Model model) {
        model.addAttribute("product", productRepository.findById(id).get());
        
        return "edit";
    }
    
    @RequestMapping("/update")
    public String update(@RequestParam String id, @RequestParam String prodName, @RequestParam String prodDesc, @RequestParam Double prodPrice, @RequestParam String prodImage) {
        Optional<Product> product = productRepository.findById(id);
        
        product.get().setProdName(prodName);
        product.get().setProdDesc(prodDesc);
        product.get().setProdPrice(prodPrice);
        product.get().setProdImage(prodImage);
        
        productRepository.save(product.get());

        return "redirect:/show/" + product.get().getId();
    }
}

Product POJO产品POJO


@Document(collection = "products")
public class Product {
    
    @Id
    String id;
    
    String prodName;
    String prodDesc;
    Double prodPrice;
    String prodImage;

    public Product() {
    }

    public Product(String prodName, String prodDesc, Double prodPrice, String prodImage) {
        this.prodName = prodName;
        this.prodDesc = prodDesc;
        this.prodPrice = prodPrice;
        this.prodImage = prodImage;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getProdName() {
        return prodName;
    }

    public void setProdName(String prodName) {
        this.prodName = prodName;
    }

    public String getProdDesc() {
        return prodDesc;
    }

    public void setProdDesc(String prodDesc) {
        this.prodDesc = prodDesc;
    }

    public Double getProdPrice() {
        return prodPrice;
    }

    public void setProdPrice(Double prodPrice) {
        this.prodPrice = prodPrice;
    }

    public String getProdImage() {
        return prodImage;
    }

    public void setProdImage(String prodImage) {
        this.prodImage = prodImage;
    }
}

create.html form page创建.html 表单页面

<!DOCTYPE HTML>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator="default">
    <head>
        <title>Create Product</title>
    </head>
    <body>
        <div layout:fragment="content" class="row">
            <div class="col-xs-8 col-md-8">
            
                <h3>
                    <a href="/product" class="btn btn-lg btn-primary"><span class="glyphicon glyphicon-list"></span>Product List</a>
                </h3>
                
                <h2>Create Product</h2>
                
                <form action="/save">
                
                    <div class="form-group">
                        <label for="email">Product Name:</label>
                        <input type="text" class="form-control" name="prodName" />
                    </div>
                    <div class="form-group">
                        <label for="email">Product Description</label>
                        <textarea class="form-control" name="prodDesc" cols="60" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="email">Product Price</label>
                        <input type="number" class="form-control" name="prodPrice" />
                    </div>
                    <div class="form-group">
                        <label for="email">Product Image URL:</label>
                        <input type="url" class="form-control" name="prodImage" />
                    </div>
                    
                    <button type="submit" class="btn btn-success">Save</button>
                </form>
            </div>
        </div>
    </body>
</html>

edit.html form page edit.html表单页面

<!DOCTYPE HTML>
<html lang="en"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="default">
    <head>
        <title>Edit Product</title>
    </head>
    <body>
        <div layout:fragment="content" class="row">
            <div class="col-xs-8 col-md-8">
            
                <h3>
                    <a href="/product" class="btn btn-lg btn-primary"><span class="glyphicon glyphicon-list"></span>Product List</a>
                </h3>
                
                <h2>Edit Product</h2>
                
                <form action="/update">
                
                    <div class="form-group">
                        <label for="email">Product Name:</label>
                        <input type="text" class="form-control" name="prodName" th:value="${product.prodName}" />
                    </div>
                    <div class="form-group">
                        <label for="email">Product Description</label>
                        <textarea class="form-control" name="prodDesc" cols="60" rows="3" th:text="${product.prodDesc}"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="email">Product Price</label>
                        <input type="number" class="form-control" name="prodPrice" th:value="${product.prodPrice}" />
                    </div>
                    <div class="form-group">
                        <label for="email">Product Image URL:</label>
                        <input type="url" class="form-control" name="prodImage" th:value="${product.prodImage}" />
                    </div>
                    
                    <input type="hidden" name="id" th:value="${product.id}" />
                    
                    <button type="submit" class="btn btn-success">Save</button>
                </form>
            </div>
        </div>
    </body>
</html>

pom.xml pom.xml

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ecommerce</groupId>
    <artifactId>ecommerce-website</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>ecommerce-website</name>
    <description>Ecommerce website using Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</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-test</artifactId>
            <scope>test</scope>
        </dependency>
        
    </dependencies>

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

</project>

I tried looking on different forms, and I saw answers that involved using annotations like @NotNull or creating a configuration class, but neither of those have worked for me.我尝试查看不同的 forms,我看到了涉及使用 @NotNull 之类的注释或创建配置 class 的答案,但这些都不适合我。

Add spring-boot-starter-validation as a dependency.添加spring-boot-starter-validation作为依赖项。 Add the annotations to your Product and use Product as a model object instead of requst parameters.将注释添加到您的Product并将Product用作 model object 而不是请求参数。

@RequestMapping("/save")
public String save(@Valid @ModelAttribute Product product) {
    productRepository.save(product);
    return "redirect:/show/" + product.getId();
}
@Document(collection = "products")
public class Product {
    
    @Id
    String id;
    
    @NotBlank
    String prodName;
    @NotBlank
    String prodDesc;
    @Min(0.01d)
    Double prodPrice;
    String prodImage;

Some of that for validation (ofcourse you would need to determine which to use based on your requirements.其中一些用于验证(当然,您需要根据您的要求确定使用哪个。

Additionally use proper types and required keyword in your HTML templates.此外,在您的 HTML 模板中使用正确的类型和required的关键字。

<div class="form-group">
    <label for="email">Product Name:</label>
    <input type="text" class="form-control" name="prodName" required />
</div>
<div class="form-group">
    <label for="prodDesc">Product Description</label>
    <textarea class="form-control" name="prodDesc" cols="60" rows="3" required></textarea>
</div>
<div class="form-group">
    <label for="prodPrice">Product Price</label>
    <input type="number" class="form-control" name="prodPrice" />
</div>
<div class="form-group">
    <label for="prodImage">Product Image URL:</label>
    <input type="url" class="form-control" name="prodImage" />
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何做到这一点,所以我的编码/解码器仅使用某些ASCII字符 - How can I make it so my encode/decoder only using certain ASCII characters 如何使HTML和Java表单重定向到自身,以便用户可以输入其他项? - How do I make my HTML and java form redirect to itself so that the user can input another item? 如何使我的MousePressed侦听器仅在单击特定区域时才响应? - How do I make it so that my MousePressed listener only respons when I click in a certain area? 如何使我的类可迭代,以便我可以使用 foreach 语法? - How can I make my class iterable so I can use foreach syntax? 如何隐藏我的API密钥,以便任何人反编译我的应用程序都看不到它? - How can I make my API key hidden so that anyone decompling my app wouldn't see it? 如何使自己的mouseListener处理当前表单? - How can I make my own mouseListener dispose of the current form? 我如何在Java中实现Flowlayout来实现它,以便GridLayout可以具有不同大小的按钮? - How can I implement Flowlayout in java to make it so that my GridLayout can have a different sized button? 如何使用 GridPane 和 HBox 使我的 javafx 表单中的所有字段均可点击? - How do I make all the fields in my javafx form clickable using GridPane and HBox? 如何做到这一点,以便Eclipse在编辑时自动在窗口中更新代码? - How can I make it so Eclipse automatically updates my code in a window as I edit it? (javafx)我当前正在制作一个需要人们创建帐户的应用程序,如何确保文本字段不为空? - (javafx) I'm currently making an app which requires people to create an account, how can i make sure the texts fields aren't null?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM