Struts2 自定义拦截器-登录验证拦截器

需求:对登录进行验证,用户名cy 密码123456才能登录进去;

         登录进去后,将用户存在session中;

           其他链接比如要来访问(除了登录链接),首先验证是否登录,对这个进行拦截;

用户登陆是经过MyInterceptor.java的,看美女这个操作要经过LoginInterceptor.java,其中要在sesssion中取用户登陆过的用户,如果没登陆过的话或者登陆过的用户退出去了的话会跳到error.jsp页面,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;
    }
    
}

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;
    }
    
}

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;
//session中有用户,说明现在有用户登陆着,就通过验证了
        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;
        }
    }
}

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>

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>

测试:

没有登录,直接访问gril链接:

进行登录,并且登录成功:

再次访问gril链接就ok了,console:

在Action执行之前
看美女
在Action执行之后

猜你喜欢

转载自blog.csdn.net/qq_40135955/article/details/89086118