《HttpServletRequest》.sendRedirect( リダイレクト先 );フォワードと比べ、とても単純ですね。リダイレクト先のアドレスを引数に指定するだけです。ただし! リダイレクトを使う場合、先の「HttpServletRequestのsetAttributeを使った値の受け渡し」は利用できなくなります。
HttpSession session = request.getSession();リクエストであるHttpServletRequestインスタンスの「getSession」を呼び出すことで、現在のセッションを管理するHttpSessionインスタンスが取得できます。そしてこのインスタンスの「setAttribute」を呼び出すことで、セッションに値を保管することができます。
session.setAttribute("input", param);後は、JSP側で値を取り出している部分をリクエストからセッションに変更すれば良いのです。以下のような具合ですね。JSPでは、HttpSessionは「session」という暗黙オブジェクトとして用意されています。
session.setAttribute("result", result);
<%=session.getAttribute("result") %>セッションは、リクエストが切れてもそのまま維持され続けますから、リダイレクト先のJSPでもちゃんと値をとり出すことができます。これで安心してページの移動が行えますね。
<%=session.getAttribute("input") %>
※リストが表示されない場合
AddBlockなどの広告ブロックツールがONになっているとリストなどが表示されない場合があります。これらのツールをOFFにしてみてください。
※helo.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>Sample jsp</title> <style> h1{ font-size: 16pt; background: #AAFFAA; padding: 5px; } </style> </head> <body> <h1>Hello App Engine!</h1> <p>Result: <%=session.getAttribute("result") %></p> <hr> <p id="msg">※整数を入力:</p> <form method="post" action="/mygaeapp"> <table> <tr> <td>入力</td> <td><input type="text" id="input" name="text1" value="<%=session.getAttribute("input") %>"></td> </tr> <tr> <td></td> <td> <input type="submit" value="送信する"> </td> </tr> </table> </form> </body> </html> ※MyGaeAppServlet.java package com.tuyano.libro.mygaeapp; import java.io.*; import java.net.URLDecoder; import javax.servlet.*; import javax.servlet.http.*; @SuppressWarnings("serial") public class MyGaeAppServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/plain"); request.setCharacterEncoding("utf8"); response.setCharacterEncoding("utf8"); PrintWriter out = response.getWriter(); out.println("Hello, world!"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); request.setCharacterEncoding("utf8"); response.setCharacterEncoding("utf8"); String param =request.getParameter("text1"); PrintWriter out = response.getWriter(); int result = 0; try { int n = Integer.parseInt(param); for(int i = 1;i <= n;i++){ result += i; } } catch (NumberFormatException e) { out.println(e); } HttpSession session = request.getSession(); session.setAttribute("input", param); session.setAttribute("result", result); response.sendRedirect("/helo.jsp"); } }
<< 前へ | 次へ >> |