SAStruts/cookie操作

SAStruts/cookie操作

cookie操作っす。

オブジェクトをつかむ

S2Containerを眺めると、cookieも暗黙でDIコンテナが管理してくれているようだ。

なのでこいつをゴニョっとすればいいようだ

Actionメソッドのpropertyに加える

@Resource
protected Map<String, Cookie> cookie;

多分名前はこれじゃないとだめなんだろう。

そんで

Cookie c = this.cookie.get("hogehoge");

とやれば掴める。あとはJavaのcookie操作

なので以下の実装は全部 Action の親クラスに実装してしまったほうが何かと楽だろう。

cookieを打ち込む

requestとresponseを予めDI管理にしておく

@Resource
protected HttpServletRequest request;
@Resource
protected HttpServletResponse response;    
Cookie c = new Cookie("hogehoge", "123");
c.setMaxAge(1000);  // cookieの生存期間 単位秒
c.setPath(this.request.getContextPath());
this.response.addCookie(c);

cookieの値を取る

Cookie c = this.cookie.get("hogehoge");
String hogehoge = c.getValue();

キーに対応するcookieが存在しない場合はnullが返ってくる。

cookieを削除する

削除は何かをセットして、即死指定しておけばよい。今回はnull突っ込んでおいた。

Cookie c = new Cookie("hogehoge", null);
c.setMaxAge(0);  // 即死にする
c.setPath(this.request.getContextPath());
this.response.addCookie(c);

Tag

java/sastruts/cookie.txt · 最終更新: 2017-09-26 18:34 by ore