Thứ Bảy, 19 tháng 7, 2014

Develop Authorization using interceptor in Struts2

Ta sẽ áp dụng interceptor để làm chức năng login cho assignment.
Việc đầu tiên ta cần làm là tạo một trang index.jsp với form đăng nhập như code phía dưới.

<a href="#" id="color_lg">Đăng nhập</a>
                                    <ul id="ul_login">
                                        <form action="login" method="post">
                                            <li><input class="required" type="text" name="username" maxlength="100" placeholder="Tên đăng nhập. . . . "/></li>
                                            <li><input class="required" type="password" name="password" maxlength="50" placeholder="Mật khẩu. . . ."/></li>
                                            <li id="li_Login"><input type="submit" value="Đăng nhập" id="btnLogin" /></li>
                                            <span></span>
                                            <label class="passerror"></label>
                                        </form>
                                    </ul>

Như ta nhìn thấy chữ login được bôi đậm trong thuộc tính action của form. Điều tiếp theo cần làm là ta sẽ tạo một lớp java và implements ActionSupport với tên là Login.java để xử lý request và kiểm tra username và password.


package ass.ui;

import ass.bussiness.AccountManagement;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 *
 * @author Nguyen Minh An
 */
public class Login extends ActionSupport {

    private String username;
    private String password;

    @Override
    public String execute() throws Exception {
        String session = ActionContext.getContext().getSession().toString();
        if ("".equals(session)) {
            int result = new AccountManagement().checkUserRole(session);
            if (result == 1) {
                return "GUIDE";
            }
            if (result == 2) {
                return "TRAVELLER";
            } else {
                return LOGIN;
            }
        }
        int res = new AccountManagement().checkLogin(username, password);
        if (res == 2) {
            ActionContext.getContext().getSession().put("username", username);
            return "GUIDE";
        }
        if (res == 3) {
            ActionContext.getContext().getSession().put("username", username);
            return "TRAVELLER";
        } else {
            return LOGIN;
        }
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

Tiếp đó ta tạo một class java thường với tên AccountManagement để kiểm tra thông tin người dùng nhập vào có khớp với thông tin trong cơ sở dữ liệu hay không.

public int checkLogin(String username, String password) {
        boolean check = Validation.checkLoginValidation(username, password);
        if (check == false) {
            return 1;
        }
        if (check == false) {
            return 1;
        }
        if (check != false) {
        } else {
            return 1;
        }
        if (check == false) {
            return 1;
        }
        if (check == false) {
            return 1;
        } else {
            try {
                String password2 = Encrypt.Encode(password);
                Connection conn = DataAccess.getConnection();

                PreparedStatement ps = conn.prepareCall("SELECT * FROM ACCOUNT WHERE aUsername like '" + username + "' and aPassword like '" + password2 + "'");
                ResultSet res = ps.executeQuery();
                while (res.next()) {
                    conn.close();
                    Connection conn2 = DataAccess.getConnection();
                    PreparedStatement ps2 = conn2.prepareCall("SELECT * FROM ACCOUNT WHERE aUsername like '" + username + "' and aPassword like '" + password2 + "' and aRole=1");
                    ResultSet res2 = ps2.executeQuery();
                    if (res2.next()) {
                        return 2;
                    } else {
                        return 3;
                    }
                }
            } catch (Exception ex) {
                Logger.getLogger(AccountManagement.class.getName()).log(Level.SEVERE, null, ex);
            }
            return 1;
        }
    }


Tiếp đến ta sẽ khai báo trong file struts.xml cho action login ở trên.

<action name="login" class="ass.ui.Login" method="execute">
            <result name="TRAVELLER"  type="redirect">travellerhomepage</result>
            <result name="GUIDE"  type="redirect">guidehomepage</result>
        </action>

<action name="guidehomepage" class="ass.ui.GuideHomePage" method="execute">
            <result name="success">GuideHomePage.jsp</result>
        </action>
        
        <action name="travellerhomepage" class="ass.ui.TravellerHomePage" method="execute">
            <result name="success">TravellerHomePage.jsp</result>

        </action>

<interceptors>
            <interceptor name="authorization" class="ass.controller.Authorization" />
            <interceptor-stack name="myStack">
                <interceptor-ref name="servletConfig" />
                <interceptor-ref name="params" />
                <interceptor-ref name="authorization" />
                <interceptor-ref name="prepare" />
                <interceptor-ref name="modelDriven" />
                <interceptor-ref name="fileUpload" />
                <interceptor-ref name="staticParams" />
                <interceptor-ref name="conversionError" />
                <interceptor-ref name="validation" />
                <interceptor-ref name="workflow" />
            </interceptor-stack>
        </interceptors>
        
        <default-interceptor-ref name="myStack"/>
        
        <global-results>
            <result name="login">/</result>

        </global-results>

Cuối cùng ta tạo một lớp với tên Authorization.java để làm nhiệm vụ lọc request và đưa chúng đến nơi cần đến.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ass.controller;

import ass.ui.Login;
import ass.ui.PlaceSearching;
import ass.ui.SearchResult;
import ass.ui.SearchingError;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.Interceptor;


/**
 *
 * @author Nguyen Minh An
 */
public class Authorization implements Interceptor {

    @Override
    public void destroy() {

    }

    @Override
    public void init() {

    }

    @Override
    public String intercept(ActionInvocation ai) throws Exception {
        Object user = ActionContext.getContext().getSession().get("username");
        if (ai.getAction() instanceof Login || user != null) {
            return ai.invoke();
        }
        if (ai.getAction() instanceof PlaceSearching) {
            return ai.invoke();
        }
        if (ai.getAction() instanceof SearchResult) {
            return ai.invoke();
        }
        if (ai.getAction() instanceof SearchingError) {
            return ai.invoke();
        }
        return ActionSupport.LOGIN;
    }

}

Các bạn có thể tải source code ở đây 


Nhận xét: 

Ưu điểm.
- Intercepter đóng vai trò như filter trong javaservlet, thật vậy nó chính là một controller để nhằm lọc các request đến server và gửi request đến action để xử lý.
- Việc sử dụng interceptor khá tiết kiệm thời gian, và không cần viết nhiều code.

Nhược điểm
- Ban đầu khi mới tìm hiểu thì khó khăn trong việc hiểu và sử dụng, do code không trong suốt

Không có nhận xét nào:

Đăng nhận xét