重要なお知らせ

「教えて! goo」は2025年9月17日(水)をもちまして、サービスを終了いたします。詳細はこちら>

【GOLF me!】初月無料お試し

どなたか助けていただけないでしょうか。。。
tomcat、サーブレット、jspを用いて
足し算アプリを作っています。

現在のコードは以下です。

*サーブレット
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class AdditionReceiptServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String strNum1 = request.getParameter("num1"); //入力パラメータの取得
String strNum2 = request.getParameter("num2"); //入力パラメータの取得
String message = null; //エラーメッセージ用変数
int answer = 0; //計算結果用変数

//入力チェック
if (strNum1 == null || strNum2 == null) {
//ダイレクトアクセス時のエラー設定
message = "フォーム画面から入力してください";
}
else if (strNum1.equals("") || strNum2.equals("")) {
//空白の場合のエラー設定
message = "何も入力されていません";
}
else {
try {
int num1 = Integer.parseInt(strNum1);
int num2 = Integer.parseInt(strNum2);
answer = num1 + num2;
}
catch (NumberFormatException e) {
//文字が入力された場合のエラー設定
message = "数字を入力してください";
}
}
//JSPに渡す情報をキーと値で設定
request.setAttribute("answer", String.valueOf(answer));
getServletContext().getRequestDispatcher("/forward.jsp").forward(request, response);

}
}

*jsp
<%@ page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8"%>
<html>
<head>
<title>同じ画面に表示する</title>
</head>
<body>
1<input type = "text" name = "num1"><br>
2<input type = "text" name = "num2"><br>
<input type = "submit" value = "Plus">
<% String answer = (String)request.getAttribute("answer"); %>
answer:<%= answer %><br>
</body>
</html>

*xml
<servlet>
<servlet-name>AdditionReceiptServletMapping</servlet-name>
<servlet-class>AdditionReceiptServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AdditionReceiptServletMapping</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>

こちら現在の表示画面が
1(入力ボックス)
2(入力ボックス)
(Plus) answer:null

のようになっているのですが、
・結果を同じ画面に表示する
・結果表示のときに入力値が入力ボックスに入った状態にする
の二つの条件ができていません。
(そもそもplusが押せない)

初心者のため、どこをどう修正したらいいのか分からず、
修正例をご教示いただけないでしょうか?

どうぞよろしくお願いいたします。

A 回答 (3件)

No.2です。

訂正(^-^;
>web.config→web.xml
    • good
    • 0

① inputはformタグで囲まないと submitできない


②入力値はinputのvalue属性に埋め込んでサーバから返すように
すれば、ページを越えて保持される
③messageも画面に送るべきでは?
④入力はなくともanswerは適切にセットしよう。nullはまずい。

蛇足だけど、サーブレットのURLはweb.configに書くのは
だいぶ前に廃れたと思う。

今はサーブレットのソースにアノテーション書くのが普通。
    • good
    • 0

<input> を囲む <form> を作る


https://developer.mozilla.org/ja/docs/Web/HTML/E …

<form> の属性を正しく指定する
* action = おそらくは "/add"
* method = "GET" ← doGet で処理するため

変数 message に内容がある場合は answer の代わりに表示させる
    • good
    • 1

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!