サーブレットとセッション②

public class Confirm extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2521469471955740120L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		CreateHtml ch = new CreateHtml();
		try {
			ch.printHtml(res, "aaa");
		} catch (TwitterException e) {
			e.printStackTrace();
		}
		// outputErrorPage(res, "Method:GETではアクセスできません",
		// "http://localhost:8080/SimpleTweet/top/");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		// セッションを取得
		HttpSession session = req.getSession(false);

		if (session != null) {
			String userId = session.getAttribute("uid").toString();
			String password = session.getAttribute("pwd").toString();
			String subject = session.getAttribute("sub").toString();

			if (!userId.equals("") && !password.equals("")
					&& !subject.equals("")) {
				SimpleTweet st = new SimpleTweet();
				try {
					st.postSubject(userId, password, subject);
					CreateHtml ch = new CreateHtml();
					ch
							.printHtml(
									res,
									"投稿が完了しました<br /><br /><a href=\"http://localhost:8080/SimpleTweet/top/\">最初の画面に戻る</a>");
				} catch (TwitterException e) {
					e.printStackTrace();
					outputErrorPage(res, "投稿に失敗しました",
							"http://localhost:8080/SimpleTweet/top/");
				}
			}
		} else {
			outputErrorPage(res, "セッションエラーです",
					"http://localhost:8080/SimpleTweet/top/");
		}
	}

	// エラーページでerrorMsgを表示し、3秒後指定したURLにリダイレクト
	public void outputErrorPage(HttpServletResponse res, String errorMsg,
			String url) {
		try {
			CreateHtml ch = new CreateHtml();
			ch.printHtml(res, errorMsg + "<br />3秒後に最初の画面に戻ります");
			Thread.sleep(3000);
			res.sendRedirect(url);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (TwitterException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}