質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
JSP

JSP(Java Server Pages)とは、ウェブアプリケーションの表示レイヤーに使われるサーバーサイドの技術のことです。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Q&A

解決済

1回答

3623閲覧

整数以外を入力した際のエラーメッセージの出し方

icecleam

総合スコア46

JSP

JSP(Java Server Pages)とは、ウェブアプリケーションの表示レイヤーに使われるサーバーサイドの技術のことです。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

0グッド

1クリップ

投稿2020/08/30 04:24

以下のadd.jspで1以上の整数で点数を入力し、[明細追加]ボタンを押すと、「明細に追加しました。」というメッセージが画面に表示されつつ、リストにデータが追加されていきます。
そこで、整数以外の文字(aなど)を入力した際に、「1以上の数字を入力してください。」とメッセージを出すように実装をしたいのですが、以下のエラーが出てしまいますので、正しくエラーメッセージを出す方法を教えていただきたいです。
(「0」を入力した際には正しくエラーメッセージが出ます。)
よろしくお願いします。

エラー画面

説明 The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).


add.jsp

<%@ page session="false" language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.time.LocalDate"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="/sales/resources/css/common.css" /> <title>売上システム(初期画面)</title> </head> <body> <form:form modelAttribute="salesForm" action="/sales/system" var="list"> <div class="header"> <span class="titleName">オンラインショップ</span> <div class="date"><%=LocalDate.now()%></div> </div> <div class="main"></div> <div>明細追加画面</div> 商品: <form:select path="goodsName" items="${nameList}" /> <div> 点数: <form:input path="quantity" items="${allList}"/> </div> <div> <input type="submit" name="add" value="明細追加" /> </div> <table> <tr> <th>削除</th> <th>商品ID</th> <th>商品名</th> <th>単価</th> <th>点数</th> <th>小計</th> </tr> <c:forEach items="${allList}" var="item" varStatus="status"> <tr class="even"> <form:hidden path="quantity" /> <td><input type="radio" name="remove"/></td> <td><c:out value="${item.id}" /></td> <td><c:out value="${item.name}" /></td> <td><c:out value="${item.price}" /></td> <td><c:out value="${item.quantity}" /></td> <td><c:out value="${item.subtotal}" /></td> </tr> </c:forEach> </table>           合計: <c:out value="${salesForm.total}" /> <input type="submit" name="firm" value="確定" /> <input type="submit" name="remove" value="削除" /> </form:form> </body> </html>

SalesSystemController.java

java

1package jp.practice.sales; 2 3import org.springframework.stereotype.Controller; 4import org.springframework.ui.Model; 5import org.springframework.web.bind.annotation.RequestMapping; 6import org.springframework.web.bind.annotation.SessionAttributes; 7 8/** 9 * Handles requests for the application home page. 10 */ 11@Controller 12@RequestMapping(value = "/system") 13@SessionAttributes 14public class SalesSystemController { 15 16 private static final String ERRMSG = "1以上の数字を入力してください。"; 17 private static final String ADDMSG = "明細に追加しました。"; 18 19 20 /** 21 * 22 * @param form フォームオブジェクト 23 * @param model モデルオブジェクト 24 * @return Viewとしてadd.jspを指定 25 */ 26 @RequestMapping(params = "add") 27 public String add(SalesForm form, Model model) { 28 Item item = RecordManager.findItem(form.getGoodsName()); 29 RecordManager.setNewItem(new Item(item.getId(), form.getGoodsName(), item.getPrice(), form.getQuantity(), item.getSubtotal())); 30 31 Item newItem = RecordManager.getNewItem(); 32 int sb = newItem.getPrice() * newItem.getQuantity(); 33 newItem.setSubtotal(sb); 34 model.addAttribute("nameList", RecordManager.makeNameList()); 35 model.addAttribute("allList", RecordManager.getallList()); 36 37 if (1 <= form.getQuantity()) { 38 RecordManager.addToAllList(newItem); 39 model.addAttribute("total", RecordManager.calTotal(RecordManager.getallList())); 40 model.addAttribute("message2", ADDMSG); 41 return "add"; 42 } else { 43 model.addAttribute("message", ERRMSG); 44 return "add"; 45 } 46 } 47 48 /** 49 * 確認画面で登録を押した時に呼ばれる。データを登録して初期画面表示へ遷移する。 50 * @param form フォームオブジェクト 51 * @param model モデルオブジェクト 52 * @return initメソッドへのリンクを指定 53 */ 54 @RequestMapping(params = "toInit") 55 public String toInit(SalesForm form, Model model) { 56 //RecordManager.findItem(name); 57 return init(form, model); 58 } 59} 60 61

SalesForm.java

java

1package jp.practice.sales; 2 3import java.util.ArrayList; 4import java.util.List; 5 6public class SalesForm { 7 8 /** 商品ID */ 9 private String id; 10 /** 商品名 */ 11 private String goodsName; 12 /** 単価 */ 13 private int price; 14 /** 売上点数 */ 15 private int quantity; 16 /** 小景 */ 17 private int subtotal; 18 /** 商品点数 */ 19 private int point; 20 /** 削除番号 */ 21 private int delNumber; 22 /** 合計 */ 23 private int total; 24 25 26 27 List<Item> allList = new ArrayList<>(); 28 29 public SalesForm() { 30 31 } 32 /** 33 * @return id 34 */ 35 public String getId() { 36 return id; 37 } 38 39 /** 40 * @param id セットする id 41 */ 42 public void setId(String id) { 43 this.id = id; 44 } 45 /** 46 * @return price 47 */ 48 public int getPrice() { 49 return price; 50 } 51 52 /** 53 * @param price セットする price 54 */ 55 public void setPrice(int price) { 56 this.price = price; 57 } 58 59 /** 60 * @return quantity 61 */ 62 public int getQuantity() { 63 return quantity; 64 } 65 66 /** 67 * @param quantity セットする quantity 68 */ 69 public void setQuantity(int quantity) { 70 this.quantity = quantity; 71 } 72 73 /** 74 * @return subtotal 75 */ 76 public int getSubtotal() { 77 return subtotal; 78 } 79 80 public void setSubtotal(int subtotal) { 81 82 this.subtotal = subtotal; 83 } 84 85 /** 86 * @return goodsName 87 */ 88 public String getGoodsName() { 89 return goodsName; 90 } 91 92 /** 93 * @param goodsName セットする goodsName 94 */ 95 public void setGoodsName(String goodsName) { 96 this.goodsName = goodsName; 97 } 98 99 /** 100 * @return point 101 */ 102 public int getPoint() { 103 return point; 104 } 105 106 /** 107 * @param point セットする point 108 */ 109 public void setPoint(int point) { 110 this.point = point; 111 } 112 113 114 public int getDelNumber() { 115 return delNumber; 116 } 117 118 public void setDelNumber(int delNumber) { 119 this.delNumber = delNumber; 120 } 121 122 123 public int getTotal() { 124 return total; 125 } 126 127 public void setTotal(int total) { 128 this.total = total; 129 } 130 131 /** 132 * @return allList 133 */ 134 public List<Item> getAllList() { 135 return allList; 136 } 137 138}

RecordManager.java

java

1package jp.practice.sales; 2 3import java.util.ArrayList; 4import java.util.List; 5 6/** 7 * 商品データ全体を保持するクラス 8 */ 9public final class RecordManager { 10 11 /** 明細データ */ 12 static List<Item> allList = new ArrayList<>(); 13 14 /** 商品データ */ 15 private static final List<Item> list = new ArrayList<Item>(); 16 static { 17 list.add(new Item("A00101", "油性ボールペン", 60, 0, 0)); 18 list.add(new Item("A00201", "極細ボールペン", 120, 0, 0)); 19 list.add(new Item("A00301", "蛍光ペン6色セット", 420, 0, 0)); 20 21 22 } 23 24 /** 25 * 更新した商品データ 26 * 確認ボタンを押すとlistに書き込む。 27 */ 28 private static Item newItem; 29 30 /** 31 * 引数で指定された商品名に一致する商品データを返却 32 * @param name 検索キーとなる商品名 33 * @return 検索結果の商品データ 34 */ 35 public static Item findItem(String goodsName) { 36 int index = list.indexOf(new Item("", goodsName, 0,0,0)); 37 return list.get(index); 38 } 39 40 /** 41 * 商品データを返す。 42 * @return 商品データ 43 */ 44 public static List<Item> getNameist() { 45 return list; 46 } 47 48 /** 49 * 明細データを返す。 50 * @return 明細データ 51 */ 52 public static List<Item> getallList() { 53 return allList; 54 } 55 56 /** 57 * リストに商品情報を 1 件追加する 58 */ 59 public static void addToAllList(Item newItem) { 60 Item item = new Item(newItem.getId(), newItem.getName(), newItem.getPrice(),newItem.getQuantity(),newItem.getSubtotal()); 61 allList.add(item); 62 } 63 64 public static void removeToAllList(Item newItem) { 65 Item item = new Item(newItem.getId(), newItem.getName(), newItem.getPrice(),newItem.getQuantity(),newItem.getSubtotal()); 66 allList.remove(item); 67 } 68 69 /** 70 * newItemを商品データlistに書き込む。 71 */ 72 public static void updateItem() { 73 list.set(list.indexOf(newItem), newItem); 74 } 75 76 /** 77 * newItemにデータを書き込む 78 * @param ni セットする item 79 */ 80 public static void setNewItem(Item ni) { 81 newItem = ni; 82 } 83 84 public static Item getNewItem() { 85 return newItem; 86 } 87 public static String[] makeNameList() { 88 String[] nameList = new String[list.size()]; 89 for (int i = 0; i < list.size(); i++) { 90 nameList[i] = (list.get(i)).getName(); 91 } 92 return nameList; 93 } 94 95 public static Item selectItem(String name) { 96 97 for(Item item:list) { 98 if (item.getName().equals(name)) { 99 return item; 100 } 101 } 102 return null; 103 } 104 105 public static int calTotal(List<Item> list) { 106 int total = 0; 107 for(Item item: list) { 108 total += item.getSubtotal(); 109 } 110 return total; 111 } 112} 113

Item.java

java

1package jp.practice.sales; 2 3public class Item { 4 5 /** 商品ID */ 6 private String id; 7 /** 商品名 */ 8 private String name; 9 /** 単価 */ 10 private int price; 11 /** 売上点数 */ 12 private int quantity; 13 /** 小景 */ 14 private int subtotal; 15 16 public Item(String id, String name, int price, int quantity, int subtotal) { 17 this.id = id; 18 this.name = name; 19 this.price = price; 20 this.quantity = quantity; 21 this.subtotal = subtotal; 22 } 23 24 public String getId() { 25 return id; 26 } 27 28 public void setId(String id) { 29 this.id = id; 30 } 31 32 public String getName() { 33 return name; 34 } 35 36 public void setName(String name) { 37 this.name = name; 38 } 39 40 public int getPrice() { 41 return price; 42 } 43 44 public void setPrice(int price) { 45 this.price = price; 46 } 47 48 public int getQuantity() { 49 return quantity; 50 } 51 52 public void setQuantity(int quantity) { 53 this.quantity = quantity; 54 } 55 56 public int getSubtotal() { 57 return subtotal; 58 } 59 60 /** 61 * @param subtotal セットする subtotal 62 */ 63 public void setSubtotal(int subtotal) { 64 this.subtotal = subtotal; 65 } 66}

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

quantityはint型なので、数値以外の文字列が入った場合に変換エラーが起きます。

SpringMVCでは、パラメータの型変換で最も簡単な方法は、リクエストを受け取るControllerのメソッドにてValidationの定義を行った上、BindingResultを引数に追加してエラー制御を行います。

java

1public String add(SalesForm form, BindingResult result, Model model) { 2 if (bindingResult.hasErrors()) { 3 // エラー時の実装 4 } 5}

メッセージ定義の方法は、springの設定である spring.messages.basename でファイル名(拡張子なし)を設定します。basenameをmessagesにした場合は、messages.propertiesがメッセージ定義ファイルになります。

エラーメッセージの設定は、例えば formクラスのageが型変換エラーならば

properties

1typeMismatch.form.age={0}は整数で入力してください。

などで定義できます。

エラーメッセージのキー設定については他にも詳細な設定が可能です。

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/DefaultMessageCodesResolver.html

余談ですが、add.jspの以下の実装は誤りで動作しません。

html

1<form:input path="quantity" items="${allList}"/>

items属性はありません。

投稿2020/08/30 08:04

A-pZ

総合スコア12011

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問