「Java開発」セッションの設定、クリアとcookieを削除するサンプルコード
1.sessionクリア
protected void clearSession() {
SessionMap sessionMap = (SessionMap) ActionContext.getContext()
.getSession();
try {
sessionMap.clear();
} catch (Exception e) {
//
}
HttpSession httpSession = this.getServletRequest().getSession();
try {
httpSession.invalidate();
} catch (Exception e) {
//
}
}
2.session設定(ログイン)
public String ctnLoginFunc() {
clearSession();
String cftUsername = this.getLoginUsername();
String cftPassword = this.getLoginPassword();
if (StringUtils.isBlank(cftUsername)) {
setMessage(“ユーザIDが必須");
return INPUT;
} else if (StringUtils.isBlank(cftPassword)) {
setMessage(“パスワードが必須");
return INPUT;
}
try {
setSessionAttribute(SESSION_ATTRIBUTE_KEY_USER,user);
setCookiesAttribute(COOKIES_ATTRIBUTE_KEY_EMPLOYEE_NO, cftUsername);
return “home";
} catch (WebApplicationRuntimeException e) {
this.setMessage(e.getMessage());
}
return INPUT;
}
3.ログアウト
public String execute() {
try {
clearSession();
ReserverCookie reserverCookie = new ReserverCookie();
reserverCookie.removeCookie(this.getServletRequest(), getServletResponse());
} catch (Exception e) {
}
return “login";
}
4.cookieを削除
public void removeCookie(HttpServletRequest request,
HttpServletResponse response) {
Cookie cookie = getCookie(request);
if (cookie != null) {
cookie = new Cookie(COOKIE_NAME, “");
cookie.setMaxAge(0);
cookie.setValue(“");
cookie.setPath(“/");
cookie.setDomain(SAMPLE_COM);
response.addCookie(cookie);
}
}