p-nuts-sp
@p-nuts-sp (はらけん)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

Java CRUD アップデート部分

解決したいこと

ここに解決したい内容を記載してください。

Java Spring Bootで CRUDのUを作っているのですが
編集ボタンを押してもエラーでURLに飛べません

画面遷移して、情報を書き換えるようにするにはどうしたらいいでしょうか?

発生している問題・エラー

編集画面が表示されない

例)

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Feb 13 20:24:22 JST 2023
There was an unexpected error (type=Bad Request, status=400).
Failed to convert value of type 'java.lang.String' to required type 'long'; nested exception is java.lang.NumberFormatException: For input string: "edit"
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'long'; nested exception is java.lang.NumberFormatException: For input string: "edit"
	at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:133)
	at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
	at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.lang.NumberFormatException: For input string: "edit"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.base/java.lang.Long.parseLong(Long.java:692)
	at java.base/java.lang.Long.valueOf(Long.java:1144)
	at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:214)
	at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:115)
	at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:429)
	at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:402)
	at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:155)
	at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:73)
	at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:53)
	at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:693)
	at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:125)
	... 47 more

または、問題・エラーが起きている画像をここにドラッグアンドドロップ

該当するソースコード

Controller

package com.example.demo.controllers;


import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.demo.models.InquiryForm;
import com.example.demo.models.InquiryForm3;

//
import com.example.demo.models.Item;
import com.example.demo.repositries.InquiryRepository;
import com.example.demo.repositries.InquiryRepository3;
import com.example.demo.repositries.ItemRepository;






@Controller
@RequestMapping("/")
public class RootController {


	@Autowired
	InquiryRepository repository;
	@Autowired
	InquiryRepository3 repository3;
	@Autowired
	ItemRepository itemRepository;

	}

	@GetMapping("/item")
	public String item(Item item ) {
		return "itemIndex/item";
	}

	@PostMapping("/item")
	public String item(@Validated Item item, BindingResult bindingResult, Model model) {
		if (bindingResult.hasErrors()) {
			return "itemIndex/item";
			//			エラーがあればreturnで返される
		}
		itemRepository .saveAndFlush(item);
		item.clear();
		model.addAttribute("message", "お問い合わせを受け付けました。");
		return "itemIndex/item";
	}
	
	@GetMapping("/list")
	public String list(Model model) {
		List<Item> item =itemRepository.findAll();
		model.addAttribute("item",item);
		return "itemIndex/list";
	}
	
	@GetMapping("/edit")
	public String edit(@PathVariable Item item,Model model) {
		model.addAttribute("item",item);
		return "itemIndex/edit";
	}
	
	@PostMapping("/{id}")
	public String update(@PathVariable long id, @ModelAttribute Item item) {
		return "itemIndex/list";
	}
	

	
	
	

	}

}

edit.html

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org" lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ポートフォリオサイト</title>
<link rel="stylesheet" media="all" th:href="@{/css/ress.min.css}" />
<link rel="stylesheet" media="all" th:href="@{/css/style.css}" />
<script th:src="@{/js/jquery-2.1.4.min.js}"></script>
<script th:src="@{/js/style.js}"></script>

<!-- Favicon -->
<link rel="icon" type="image/png" th:href="@{/img/favicon.png}">

</head>
<body>
	<header>
		<div class="container">
			<div class="row">
				<div class="col span-12">
					<div class="head">
						<h1>
							<a th:href="@{/}">PORTFOLIO</a>
						</h1>
					</div>
				</div>
			</div>
			<div class="row">
				<div class="col span-12">
					<nav>
						<div id="open">
							<img th:src="@{/img/button.png}">
						</div>
						<div id="close">
							<img th:src="@{/img/button2.png}">
						</div>
						<div id="navi">
							<ul>
								<li><a th:href="@{/}">ホーム</a></li>
								<li><a th:href="@{/form}">お問い合わせ</a></li>
							</ul>
						</div>
					</nav>
				</div>
			</div>
		</div>
	</header>
	<div class="mainimg">
		<img th:src="@{/img/subimg.jpg}" alt="お問い合わせ画像">
	</div>
	<main>
		<article>
			<div class="container">
				<div class="row">
					<div class="col span-12">
						<div class="breadcrumb">
							<ul>
								<li><a th:href="@{/demo}">ホーム</a> > お問い合わせ</li>
							</ul>
						</div>

						<th:block th:if="message != null">
							<h2 th:class="msg" th:text="${message}"></h2>
						</th:block>

						<h2 class="underline">商品編集画面</h2>
						<form th:action="@{/form/{id}(id=*{id})}" th:method="post" th:object="${item}">
							<div class="form-group">
								<label class="control-label">商品名</label>
								<input class="form-control" type="text" th:field="*{name}" />
							</div>
							<div class="form-group">
								<label class="control-label">値段</label>
								<input class="form-control" type="number" th:field="*{price}" />
							</div>
							<div class="form-group">
								<label class="control-label">商品概要</label>
								<input class="form-control" type="text" th:field="*{content}" />
							</div>
							<button class="btn btn-default" type="submit">更新</button>
						</form>
						<div class="pull-right">
						<a class="btn btn-link" href="/players">一覧画面へ</a>
						</div>
					</div>
				</div>
			</div>
		</article>
	</main>
	<footer>
		<div class="container">
			<div class="row">
				<div class="col span-12">
					<h5>お知らせ</h5>
					<p>電話での問合せは承っておりません。</p>
					<p>回答にお時間頂くことがございます。予めご了承ください。</p>
				</div>
			</div>
		</div>
	</footer>
	<p id="pagetop">
		<a href="#">TOP</a>
	</p>
</body>
</html>
0

1Answer

いくつか問題点が重なっていそうです。

  1. 恐らくPOSTされている
    1. 後述の通り/edit/{id}にGETするように修正してください
    2. list画面のコードを見せてください
  2. editのパスで更新対象のレコードを特定するすべがない
    1. 以下を確認してください
      1. GetMappingの引数でidを受け取れるようにする
      2. editメソッドの引数でidを受け取れるようにする
      3. editメソッドで更新対象のitemを取得する
@GetMapping("/edit/{id}")
public String edit(@PathVariable long id,Model model) {
  Item item =itemRepository.findById(id);// findByIdのメソッドがあるかは知らないです。
  model.addAttribute("item",item);
  return "itemIndex/edit";
}
1Like

Your answer might help someone💌