#06:具体例:フォームで、RPGの戦闘シーンを作ろう その1
ここでは、Javaによるフォームの具体例として、RPGの戦闘シーンを作ります。先ほど作ったフォームをベースにして、ドロップダウンメニューでプレイヤーを選択できるようにしましょう。
(tomcat/webapps/mybattle/ShowServlet.java)import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShowServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
setPlayerList(request);
request.setAttribute("message", "あらたなモンスターがあらわれた!");
forwardForm(request, response);
}
private void setPlayerList(HttpServletRequest request) {
String playerList = "勇者,戦士,魔法使い";
request.setAttribute("playerList", playerList);
}
private void forwardForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String view = "/WEB-INF/views/form.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(view);
dispatcher.forward(request, response);
}
}
(tomcat/webapps/mybattle/WEB-INF/views/form.jsp)<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Java - paiza</title>
</head>
<body>
<h1>RPGの戦闘フォーム</h1>
<p><%= (String)request.getAttribute("message") %></p>
<% String playerList = (String)request.getAttribute("playerList"); %>
<% String[] players = playerList.split(","); %>
<form action="show" method="post">
<label for="name">プレイヤー</label>
<select name="name">
<% for (String player : players) { %>
<option value="<%= player %>"><%= player %></option>
<% } %>
</select>
<p></p>
<button type="submit">たたかう</button>
</form>
</body>
</html>
$ javac -classpath "../../lib/servlet-api.jar" -d WEB-INF/classes ShowServlet.java
- Javaの道>Servlet・JSP
https://www.javaroad.jp/servletjsp/index.html
- Servletアプリ開発:目次 - Web系開発メモ
http://web-dev.hatenablog.com/entry/java/servlet/dev-restful-app/table-of-contents
- JSP(formデータ)とJava Servletプログラムの連携 - はしくれエンジニアもどきのメモ
http://cartman0.hatenablog.com/entry/2015/12/08/181657