1. 程式人生 > >struts2學習(6)自定義攔截器-登錄驗證攔截器

struts2學習(6)自定義攔截器-登錄驗證攔截器

back tps class res urn fff .com space war

需求:對登錄進行驗證,用戶名cy 密碼123456才能登錄進去;

  登錄進去後,將用戶存在session中;

其他鏈接要來訪問(除了登錄鏈接),首先驗證是否登錄,對這個進行攔截;

技術分享

com.cy.model.User.java:

技術分享
package com.cy.model;

public class User {
    private String userName;
    private String password;
    
    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; } }
View Code

com.cy.action.UserAction.java:

package com.cy.action;

import java.util.Map; import com.cy.model.User; import com.cy.service.UserService; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport{ private static final long serialVersionUID = 1L; private User user;
private UserService userService = new UserService(); private String error; public String getError() { return error; } public void setError(String error) { this.error = error; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String execute() throws Exception { if(userService.login(user)){ ActionContext actionContext = ActionContext.getContext(); Map<String, Object> session = actionContext.getSession(); session.put("currentUser", user); return SUCCESS; }else{ this.error = "用戶名或密碼錯誤"; return ERROR; } } }

com.cy.action.GrilAction.java:

技術分享
package com.cy.action;

import com.opensymphony.xwork2.ActionSupport;

public class GrilAction extends ActionSupport{
    private static final long serialVersionUID = 1L;

    @Override
    public String execute() throws Exception {
        System.out.println("看美女");
        return SUCCESS;
    }
    
}
View Code

com.cy.interceptor.LoginInterceptor.java:

package com.cy.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class LoginInterceptor implements Interceptor{
    
    private static final long serialVersionUID = 1L;

    public void destroy() {
        System.out.println("LoginInterceptor銷毀");
    }
    
    public void init() {
        System.out.println("LoginInterceptor初始化");
    }
    
    public String intercept(ActionInvocation invocation) throws Exception {
        System.out.println("在Action執行之前");
        ActionContext actionContext = invocation.getInvocationContext();
        Map<String, Object> session = actionContext.getSession();
        Object currentUser = session.get("currentUser");
        String result = null;
        if(currentUser != null){
            result = invocation.invoke();
        }else{
            HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(ServletActionContext.HTTP_REQUEST);
            request.setAttribute("error", "請先登錄!");
            result = "error";
        }
            
        System.out.println("在Action執行之後");
        
        return result;                            
    }

}

com.cy.service.UserService.java:

技術分享
package com.cy.service;

import com.cy.model.User;

public class UserService {
    
    public boolean login(User user){
        if("cy".equals(user.getUserName()) && "123456".equals(user.getPassword())){
            return true;
        }else{
            return false;
        }
    }
}
View Code

struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    
    <package name="manage" namespace="/" extends="struts-default">
        <interceptors>
            <interceptor name="loginInterceptor" class="com.cy.interceptor.LoginInterceptor"></interceptor>
            
            <interceptor-stack name="myStack">
                <interceptor-ref name="loginInterceptor"></interceptor-ref>
                <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        
        <!-- package默認使用myStack 這個包下面的每個action默認使用myStack攔截器棧-->
        <default-interceptor-ref name="myStack"></default-interceptor-ref>
        
        <global-results>
            <result name="error">error.jsp</result>
        </global-results>
        
        <action name="gril" class="com.cy.action.GrilAction">
            <result name="success">success.jsp</result>
            
            <!-- 定義了默認的攔截器棧,這裏就註釋掉
                <interceptor-ref name="loginInterceptor"></interceptor-ref>
                <interceptor-ref name="defaultStack"></interceptor-ref>
             -->
        </action>
        
        <action name="user" class="com.cy.action.UserAction">
            <result name="success">success.jsp</result>
            <!-- 因為登錄的時候不需要進行登錄驗證,不需要使用loginInterceptor
                  因此這裏就寫defaultStack
                  寫了defaultStack action就不會再使用其他的攔截器了。
             -->
            <interceptor-ref name="defaultStack"></interceptor-ref>
        </action>
        
    </package>
    
</struts>

success.jsp:

技術分享
<body>
    當前用戶: ${currentUser.userName}
</body>
View Code

error.jsp:

<body>
    錯誤信息:${error} <a href="login.jsp">登錄</a>
</body>

login.jsp:

技術分享
<body>
    <form action="user" method="post">
        用戶名: <input type="text" name="user.userName"/><br>
        密碼: <input type="text" name="user.password"/><br>
        <input type="submit" value="登錄" />
    </form>
</body>
View Code

測試:

沒有登錄,直接訪問gril鏈接:

技術分享

進行登錄,並且登錄成功:

技術分享技術分享

再次訪問gril鏈接就ok了,console:

在Action執行之前
看美女
在Action執行之後

-------------

struts2學習(6)自定義攔截器-登錄驗證攔截器