alphaのjava備忘録

alphaが勉強したことを書いていくブログ

フォームに入力されたデータを出力する

JSPで行うフォームの作成は入力フォームを作ることもできる。サーブレット側でフォームの値を取得する記述をするとJSP画面で入力された内容をプログラム上で使用できる。今回はJSP画面から入力した文字列を別のJSPの画面で出力してみる。処理の流れとしては、EclipseからServlet実行→doGet()でJSP1が呼び出される→フォーム入力後、送信ボタンを押す⇒ServletがdoPost()でJSP2を呼び出す、という形になる。


Servlet4.java

package servletTest;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Servlet4")
public class Servlet4 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String jsp1 = "/WEB-INF/jsp4-1.jsp";
		RequestDispatcher rd = request.getRequestDispatcher(jsp1);
		rd.forward(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String ret[] = request.getParameterValues("text1");
		String jsp2 = "/WEB-INF/jsp4-2.jsp?name="+ret[0];
		RequestDispatcher rd = request.getRequestDispatcher(jsp2);
		rd.forward(request,response);
	}
}


jsp4-1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jsp4-1.jsp</title>
</head>
<body>

<form method = post action="Servlet4" >
<input type = text  name= text1 >
<input type = submit value ="送信">

</form>

</body>
</html>

jsp4-2.jsp

<% String name = request.getParameter("name");%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jsp4-2.jsp</title>
</head>
<body>
<%= name%>
</body>
</html>


実行結果
f:id:dream_of_night:20180712224355p:plain
最初に1つ目のJSP画面(jsp4-1.jsp)が表示されて

f:id:dream_of_night:20180712224348p:plain
文字列を入れて「送信」ボタンを押すと

f:id:dream_of_night:20180712224814p:plain
文字列のデータを持った2つ目のJSP画面(jsp4-2.jsp)が表示される。