LoginSignup
0
0

More than 3 years have passed since last update.

Servletの勉強で学んだことまとめ

Posted at

フォームの使い方

jsp
<form action ="/servlet/FormSampleServlet" method="post">
名前:<input type="text" name="name"><br>
<input type="submit" value="登録">
</form>
servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");//文字コードのセット
        String name = request.getParameter("name");//"name"という名前のパラメータの値を取得する
}

フォワード

・フォワード先には同じWebアプリケーションのJSPファイルやServletクラスを指定する。
・アドレスバーに表示されるURLはリクエスト時のまま変わらない

forward
RequestDispatcher dispatcher = request.getRequestDispatcher("フォワード先");
dispatcher.forward(request,response);

リダイレクト

・リダイレクト先にはブラウザがリクエストできる先であればどこでも指定できる。
・アドレスバーに表示されるURLはリダイレクト先のものに代わる

redirect
response.sendRedirect("リダイレクト先のURL");

リクエストスコープの使い方

requestScope
// リクエストスコープに保存するインスタンス
Cat cat = new Cat();

// リクエストスコープにインスタンスを保存
request.setAttribute("cat",cat); // 第一引数:属性名(String),第二引数:インスタンス(Object)

// リクエストスコープからインスタンスを取得
Cat neko = (Cat) request.getAttribute("cat"); //第一引数:属性名(String) 
// ↑ ※戻り値はObject型なのでキャストが必要

セッションスコープの使い方

sessionScope
// セッションスコープの取得
HttpSession session = request.getSession();

// セッションスコープに保存する
session.setAttribute("cat",cat); // 第一引数:属性名(String),第二引数:インスタンス(Object)

// セッションスコープからインスタンスを取得する
Cat neko = (Cat) session.getAttribute("cat"); //第一引数:属性名(String) 
// ↑ ※戻り値はObject型なのでキャストが必要

// セッションスコープからインスタンスを削除する
sessin.removeAttribute("cat"); //第一引数:属性名(String) 

// セッションを破棄する
session.invalidate();

アプリケーションスコープの使い方

applicationScope
// アプリケーションスコープの取得
ServletContext application = this.getServletContext();

// アプリケーションスコープに保存する
application.setAttribute("cat",cat); // 第一引数:属性名(String),第二引数:インスタンス(Object)

// アプリケーションスコープからインスタンスを取得する
Cat neko = (Cat) application.getAttribute("cat"); //第一引数:属性名(String) 

// セッションスコープからインスタンスを削除する
application.removeAttribute("cat"); //第一引数:属性名(String) 

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0