Struts2的登錄驗證和session控制


 今天由於軟件工程大項目的需要,我學習了下Struts2的自定義攔截器的使用方法。

其實很簡單,攔截器的思想就是在執行某個需要權限的action之前先進攔截器Action看一下是否符合要求,比如說是否有合法的session保存。

下面是各種配置文件:

1. 某package中的interceptors配置,這里沒用 interceptor-stack,因為只需要一層過濾。

        <interceptors>
            <interceptor name="teacherInterceptor"
                         class="com.postgraduate.interceptors.TeacherLoginInterceptor" >
            </interceptor>
        </interceptors>

        <global-results>
            <result name="login">/login.jsp</result>
        </global-results>

2.同一個package下的action配置,只是增加了一句

        <action name="toTeacherIndex" class="com.postgraduate.action.TeacherAction" method="getIndex">
            <result name="success">/teacher/teacher_index.jsp</result>
            <result name="error">/teacher/error.jsp</result>
            <interceptor-ref name="teacherInterceptor" />
        </action>

3.同時還需要實現一個Interceptor類,用來處理驗證邏輯,其實就是個Action,只不過比普通的Action優先級高,而各Interceptor的優先級由stack決定。

public class TeacherLoginInterceptor extends AbstractInterceptor {

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        ActionContext ctx = invocation.getInvocationContext();
        Map<String,Object> session = ctx.getSession();
        Teacher teacher = (Teacher) session.get("teacher");
        if(teacher == null)
            return "login";
        else {
            return invocation.invoke();
        }
    }
}

4.登錄action(無權限執行)中設置session:

    public String login() {
        int userId;
        try {
            userId = Integer.parseInt(user.getUserId());
        } catch (Exception e) {
            return "login";
        }
        if (type.equals("teacher")) {
            Teacher teacher = userDAO.loginTeacher(userId, user.getPassword());
            ActionContext.getContext().getSession().put("teacher", teacher);
            return "teacher";
        } else if (type.equals("student")) {
            Student student = userDAO.loginStudent(userId,user.getPassword());
            ActionContext.getContext().getSession().put("student", student);
            return "student";
        } else
            return "login";
    }

這樣整套邏輯就通了,另外,如果不想讓其他人直接通過網站目錄訪問jsp,可以將有權限的jsp放到WEB-INF目錄下,只通過action控制。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM