Я новичок в Springboot. Перед использованием этой модели атрибута я пробовал с @RequestParams, он отлично работает без каких-либо ошибок. Но некоторые сайты предложили, что если мы хотим получить больше входных данных от пользователя, не рекомендуется использовать @RequestParams для всех входных данных в классе контроллера. Я не знаю, верно ли это или нет, но попытался в этом методе, в результате чего следующая ошибка.
мой pom. 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.2.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>bootjpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>bootjpa</name>
<description>Demo project for Spring Boot</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>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.6</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>1.9.1</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.27</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
мой контроллер это:
package com.example.demo.Controller;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.example.demo.Model.Todo;
import com.example.demo.Service.TodoService;
@Controller
@SessionAttributes("name")
public class TodoController
{
@Autowired
TodoService service;
@RequestMapping(value = "/todos", method = RequestMethod.GET)
public String todoview(ModelMap model)
{
String nam = (String)model.get("name");
model.put("returnVal", service.retrieveTodo(nam));
return "todos";
}
@RequestMapping(value = "/addTodo", method = RequestMethod.GET)
public String addTodo(ModelMap model)
{
model.addAttribute("todo",new Todo(0, (String)model.get("name"), "", new Date(), false));
return "addTodo";
}
@RequestMapping(value = "/addTodo", method = RequestMethod.POST)
public String addPostTodo(ModelMap model,Todo todo)
{
service.addTodo((String)model.get("name"), todo.getDesc(), new Date());
return "redirect:/todos";
}
@RequestMapping(value = "/delete", method = RequestMethod.GET)
public String deleteTodo(@RequestParam int id)
{
service.removeTodo(id);
return "redirect:/todos";
}
}
мой addTodo . jsp страница выглядит так:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link href = "webjars/bootstrap/3.3.6/css/bootstrap.min.css" rel = "stylesheet">
</head>
<body>
<center><div class = "page-header">
<h1>Add a new Todo</h1>
</div></center>
<div class = "container">
<form:form method = "post" modelAttribute = "todo" style="width:300px;">
<fieldset class = "form-group">
<form:label path = "desc" class = "control-label" >Description </form:label>
<form:input path = "desc" type = "text" class = "form-control" required = "required" />
</fieldset>
<button type = "submit" class = "button btn-success btn-lg">Add</button>
</form:form>
</div>
<script src = "webjars/jquery/1.9.1/jquery.min.js"></script>
<script src = "webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
Класс, который я пытался связать между моделью и контроллером:
package com.example.demo.Model;
import java.util.Date;
public class Todo
{
private int id;
private String user;
private String desc;
private Date targetDate;
private boolean isDone;
public Todo(int id, String user, String desc, Date targetDate, boolean isDone)
{
super();
this.id = id;
this.user = user;
this.desc = desc;
this.targetDate = targetDate;
this.isDone = isDone;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Date getTargetDate() {
return targetDate;
}
public void setTargetDate(Date targetDate) {
this.targetDate = targetDate;
}
public boolean isDone() {
return isDone;
}
public void setDone(boolean isDone) {
this.isDone = isDone;
}
@Override
public String toString()
{
return String.format(id+","+user+","+desc+","+targetDate+","+isDone);
}
}
Мой класс обслуживания:
package com.example.demo.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.springframework.stereotype.Service;
import com.example.demo.Model.Todo;
@Service
public class TodoService
{
private static List<Todo> todos = new ArrayList<Todo>();
private static int count= 3;
static
{
todos.add(new Todo(1, "atchuth", "Learn Spring boot", new Date(), false));
todos.add(new Todo(2, "atchuth", "Learn MongoDB", new Date(), false));
todos.add(new Todo(3, "atchuth", "Learn MVC", new Date(), false));
}
public void addTodo(String name, String desc, Date date)
{
todos.add(new Todo(++count,name,desc,date,false));
}
public void removeTodo(int id)
{
Iterator<Todo> iter = todos.iterator();
while(iter.hasNext())
{
{
Todo t = iter.next();
if(t.getId() == id)
iter.remove();
}
}
}
public List<Todo> retrieveTodo(String name)
{
List<Todo> retrieveList = new ArrayList<Todo>();
for(Todo t : todos)
{
if(t.getUser().equalsIgnoreCase(name))
{
retrieveList.add(t);
}
}
return retrieveList;
}
}
Но я получаю ошибку как:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Feb 26 15:48:45 IST 2020
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='todo'. Error count: 2
, где в качестве объяснения этой ошибки в наборе инструментов Spring отображается как:
Field error in object 'todo' on field 'id': rejected value [null]; codes
[typeMismatch.todo.id,typeMismatch.id,typeMismatch.int,typeMismatch]; arguments
[org.springframework.context.support.DefaultMessageSourceResolvable: codes [todo.id,id]; arguments
[]; default message [id]]; default message [Failed to convert value of type 'null' to required type
'int'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to
convert from type [null] to type [int] for value 'null'; nested exception is
java.lang.IllegalArgumentException: A null value cannot be assigned to a primitive type]
Field error in object 'todo' on field 'isDone': rejected value [null]; codes
[typeMismatch.todo.isDone,typeMismatch.isDone,typeMismatch.boolean,typeMismatch]; arguments
[org.springframework.context.support.DefaultMessageSourceResolvable: codes [todo.isDone,isDone];
arguments []; default message [isDone]]; default message [Failed to convert value of type 'null' to
required type 'boolean'; nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to convert from type [null] to
type [boolean] for value 'null'; nested exception is java.lang.IllegalArgumentException: A null value
cannot be assigned to a primitive type]]