1

我正在学习 Java EE,我必须记住使用四小时定时 cookie 登录的用户。

我必须以这种方式实现它,因为 cookie 部分对我的学校来说是强制性的。我知道我的 cookie 创建得很好(在 中LoginAction.java),因为我在自定义操作中对其进行了测试。(在我的login.jsp我放了一个 struts 标签<action ... executeResults="true"/>

我创建了一个名为拦截器的拦截器LoginInterceptor来拦截访问页面的每一次尝试。

它非常正确地拦截了请求(是的!)但是我无法检查 cookie,因为我HTTPServletRequest的 is 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;
    }
}
4

1 回答 1

0

In the interceptor you could get cookies like

Cookie[] cookies = ServletActionContext.getRequest().getCookies();

ServletRequestAware interface is used with actions. To get access to the servlet environment use the ServletActionContext.

于 2013-05-29T15:07:26.923 回答