我正在學習Java EE,我必須用四小時定時cookie來記住登錄用戶。在登錄頁面上使用Cookie使用Struts 2
我要實現這種方式,因爲cookie的部分是強制性的我的學校。 我知道我的cookie是很好創建的(在LoginAction.java
),因爲我在自定義操作中對其進行了測試。 (在我的login.jsp
我把一個Struts標籤<action ... executeResults="true"/>
。
我創建了一個名爲LoginInterceptor
攔截每一個試圖訪問一個網頁的攔截。
它攔截完全正確的請求(是的!),但是我不能檢查餅乾,因爲我HTTPServletRequest
是null
。
我怎麼測試? 我去我登錄指數(localhost.../myProject/
) 記住我。
你有什麼想法嗎?
Index.jsp
:
<% response.sendRedirect("AccueilAction.action"); %>
struts.xml
:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false"/>
<constant name="struts.devMode" value="true"/>
<package name="default" extends="struts-default">
<global-results>
<result name="login">/WEB-INF/content/login.jsp</result>
</global-results>
</package>
<package name="com.yaka.yakaaerien.actions" namespace ="/" extends ="struts-default">
<interceptors>
<interceptor name="loginInterceptor"
class="com.yaka.yakaaerien.interceptor.LoginInterceptor" />
<interceptor-stack name="globalStack">
<interceptor-ref name="loginInterceptor"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<action name="ActionsListAction" class="com.yaka.yakaaerien.actions.ActionsListAction">
<interceptor-ref name="globalStack"/>
<result>/index.jsp</result>
</action>
<action name="AccueilAction" class="com.yaka.yakaaerien.actions.AccueilAction">
<interceptor-ref name="globalStack"/>
<result>/WEB-INF/content/login.jsp</result>
</action>
<action name="LoginAction" class="com.yaka.yakaaerien.actions.LoginAction">
<result name="success">/WEB-INF/content/Accueil.jsp</result>
<result name="error">/WEB-INF/content/login.jsp</result>
<result name="input">/WEB-INF/content/login.jsp</result>
</action>
<action name="GenerePasswordAction" class="com.yaka.yakaaerien.actions.GenerePasswordAction">
<result>/WEB-INF/content/GenerePassword.jsp</result>
<result name="success">/WEB-INF/content/result.jsp</result>
<result name="error">/WEB-INF/content/GenerePassword.jsp</result>
<result name="input">/WEB-INF/content/GenerePassword.jsp</result>
</action>
</package>
</struts>
LoginAction.java
(getter和setter工作,我不告訴他們,自動生成它們):
//imports....
public class LoginAction extends ActionSupport implements ServletRequestAware, ServletResponseAware {
private boolean isAdmin = false;
private String message;
private String login;
private String password;
private String userID;
private String remember;
private UsersDAO usersDAO = new UsersDAO();
public ArrayList<Users> list_users = new ArrayList<Users>();
protected HttpServletRequest servletRequest;
protected HttpServletResponse servletResponse;
@Override
public String execute() throws Exception {
UsersDAO actions = new UsersDAO();
List list_users = actions.get_users(login, password);
Iterator i = list_users.iterator();
Users user;
if (list_users != null && !list_users.isEmpty()) {
while(i.hasNext()){
user = (Users)i.next();
if (user.getUserIsAdm() != null && user.getUserIsAdm()) {
isAdmin = true;
}
// Permits to save the current logged Session
//ActionContext.getContext().getSession().put("logged", user.getUserFirstName());
System.out.println("success");
if (remember.equals("true")) {
System.out.println("Registering new cookie");
Cookie userCookie = new Cookie("userID", user.getUserFirstName() + "," + user.getUserPassword());
userCookie.setMaxAge(60 * 60 * 4);
servletResponse.addCookie(userCookie);
}
return SUCCESS;
}
}else {
System.out.println("Adding actionError");
addActionError("Erreur : Nom d'utilisateur ou mot de passe érroné.");
}
return ERROR;
}
@Override
public void validate() {
System.out.println("Form validation");
System.out.println(remember);
Map<String, List<String>> fields = getFieldErrors();
fields = new HashMap<String, List<String>>();
if (login == null || login.length() == 0) {
addFieldError("coucou", "coucou");
}
if (password == null || password.length() == 0) {
addFieldError("bad password", "bad password");
}
}
@Override
public void setServletRequest(HttpServletRequest hsr) {
this.servletRequest = hsr;
}
@Override
public void setServletResponse(HttpServletResponse hsr) {
this.servletResponse = hsr;
}
}
LoginInterceptor.java
:
public class LoginInterceptor implements Interceptor {
private HttpServletRequest servletRequest;
private String cookied = "false";
public void destroy() {
System.out.println("destroy");
}
public void init() {
System.out.println("init");
}
@Override
public String intercept(ActionInvocation ai) throws Exception {
if(ai.getAction() instanceof ServletRequestAware)
{
System.out.println("omg");
this.servletRequest = (HttpServletRequest)ai.getInvocationContext().
get(StrutsStatics.HTTP_REQUEST);
}
UsersDAO actions = new UsersDAO();
System.out.println("Entering LoginInterceptor");
if (getCookie("userID") != null) {
System.out.println("Looking for cookie userID");
String cookieValue = getCookie("userID").getValue();
String login = cookieValue.substring(0, cookieValue.lastIndexOf(","));
String password = cookieValue.substring(cookieValue.lastIndexOf(",") + 1);
List list_users = actions.get_users(login, password);
System.out.println("Checking cookie for user :" + login);
Iterator i = list_users.iterator();
Users currentUser;
while (i.hasNext()) {
currentUser = (Users) i.next();
System.out.println(currentUser.getUserFirstName());
System.out.println(getCookie("userID").getValue());
if (currentUser.getUserFirstName().equals(login)) {
System.out.println("Cookie found !");
cookied = "true";
return ai.invoke();
}
}
}
return "login";
}
public Cookie getCookie(String name) {
if (servletRequest != null) {
if (servletRequest.getCookies() != null) {
Cookie cookies[] = servletRequest.getCookies();
Cookie requestedCookie = null;
if (cookies != null) {
for (Cookie current : cookies) {
if (current.getName().equals(name)) {
requestedCookie = current;
break;
}
}
}
return requestedCookie;
}
}
return null;
}
public void setServletRequest(HttpServletRequest hsr) {
this.servletRequest = hsr;
}
public String getCookied() {
return cookied;
}
public void setCookied(String cookied) {
this.cookied = cookied;
}
}
好的!它現在運作良好:D! 我認爲這很難理解這一點..我看不到這些intereceptors捕獲動作請求...但操作返回一個JSP。 所以,如果我直接輸入我的網頁瀏覽器到另一個頁面的鏈接,它會被攔截嗎? 無論如何,非常感謝:) – ogdabou
攔截器與動作一起使用,如果您需要使用頁面調用過濾器使用過濾器。 –
因此,如果我明白,如果有人輸入directyl url到我的頁面之一,在登錄頁面上強制重定向,我必須實現一個過濾器呢? – ogdabou