Struts2登录拦截器的简单示例

登录拦截几乎每个WEB系统都会用到.在这里记录一下自己对于Struts2登录拦截的简单实现.

逻辑也非常简单: 用户通过登录页面,进入到主页.如果不通过登录强行进入到主页,则会调转到登录页面.

1.前台的JSP页面

登录页-UserLogin.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>User Login</title>
</head>
<body>
    <form action="user.action" method="post">
        <table border="1">
            <tr>
                <td>Username:</td>
                <td><input type="text" name="user.username" style="width: 100%"/></td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type="password" name="user.password" style="width: 100%"/></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <input type="submit" value="登录"/>
                    <input type="reset" value="重置"/>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

可以看到上面这段代码中form表单将数据提交到了user.action当中


登录成功后的页面-LoginSuccess.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login Success</title>
</head>
<body>
    <span>登录成功</span><br/>
    <span>当前用户: ${currentUser.username}</span><br/>
    <span><a href="main.action">跳转</a>到主页</span>
</body>
</html>
上面是登录成功后的页面,将会显示登录的用户名以及一个跳转到main.action的链接


Main页-MainPage.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Main Page</title>
</head>
<body>
    <span>主页</span><br/>
    <span>当前用户: ${currentUser.username}</span>
</body>
</html>
同样,这个主页也会显示用户名.

错误页-ErrorPage.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Error Page</title>
</head>
<body>
    <span>${error}<a href="UserLogin.jsp">登录</a></span>
</body>
</html>
错误页将会显示从Action/Interceptor传过来的错误信息,并且给出了跳转会登录页的链接.

2.后台代码

创建JavaBean

首先要建立一个User的JavaBean.内置的属性自然是username和password.

package com.struts.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;
    }
}

创建登录Action-LoginAction

package com.struts.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.struts.model.User;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


public class LoginAction extends ActionSupport {
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Override
    public String execute() throws Exception {
        if ("admin".equals(user.getUsername()) && "admin".equals(user.getPassword())) {
            // 获取ActionContext
            ActionContext actionContext = ActionContext.getContext();
            // 获取Session
            Map<String, Object> session = actionContext.getSession();

            session.put("currentUser", this.user);
            System.out.println("登录成功");
            return SUCCESS;
        } else {
            // 通过ActionContext获取request对象
            HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
            request.setAttribute("error", "用户名密码错误,请重新");
            System.out.println("登录失败");
            return ERROR;
        }
    }
}
这里做的比较简单,只允许用户名/密码同为admin的用户登录.但其原理是通过ActionContext获取Session,并把设置了用户名/密码的User对象放入到Session当中.随后返回SUCCESS.相反,如果输入的用户名/密码不为admin,则通过ActionContext获取request对象.并把错误信息放置到request对象当中,最后返回ERROR.

创建拦截器-AuthInterceptor

package com.struts.intercept;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class AuthInterceptor extends AbstractInterceptor {
    @Override
    public String intercept(ActionInvocation actionInvocation) throws Exception {
        ActionContext actionContext = actionInvocation.getInvocationContext();
        Map<String, Object> session = actionContext.getSession();

        Object currentUser = session.get("currentUser");

        String result = null;
        if (currentUser != null) {
            result = actionInvocation.invoke();
        } else {
            HttpServletRequest request = (HttpServletRequest) actionInvocation.getInvocationContext().get(ServletActionContext.HTTP_REQUEST);
            request.setAttribute("error", "还未登录,请先");
            result = "error";
        }
        return result;
    }
}
这个拦截器很简单,首先ActionInvocation获取用户的Session.检查这个Session是否带有用户的信息(currentUser).如果currentUser不用为空,则代表当前用户已经登录过.继续执行actionInvocation.invoke(),返回SUCCESS,通过拦截器.如果currentUser为空,则代表用户并没有登录.此时通过actionInvocation获取request对象,将错误信息放置到request对象的属性当中.最后将result设置为ERROR.并返回.

主页的Action-MainAction

package com.struts.action;

import com.opensymphony.xwork2.ActionSupport;


public class MainAction extends ActionSupport {
    @Override
    public String execute() throws Exception {
        System.out.println("进入主页");
        return SUCCESS;
    }
}
在用户等会之后,登录成功也会有一个超链接,这个链接地址则是上面的MainAction.当MainAction的execute方法执行完毕之后会跳转到对应的MainPage.jsp当中.整个过程结束.

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="true"/>
    <constant name="struts.devMode" value="true"/>

    <package name="default" namespace="/" extends="struts-default">
        <interceptors>
            <interceptor name="loginInterceptor" class="com.struts.intercept.AuthInterceptor"/>
            <interceptor-stack name="AuthStack">
                <interceptor-ref name="loginInterceptor"/>
                <interceptor-ref name="defaultStack"/>
            </interceptor-stack>
        </interceptors>

        <default-interceptor-ref name="AuthStack"/>

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

        <action name="user" class="com.struts.action.LoginAction">
            <result name="success">LoginSuccess.jsp</result>
            <interceptor-ref name="defaultStack"/>
        </action>

        <action name="main" class="com.struts.action.MainAction">
            <result name="success">MainPage.jsp</result>
        </action>
    </package>
</struts>
这是登录拦截的最主要部分,它直接关系着登录拦截是否实现正确,

在package标签当中,首先创建自定义的拦截器loginInterceptor.并且要创建一个全局的拦截器栈,当做默认拦截器栈.再设置一个全局结果集,全局结果集的意思是:当用户试图绕过登录页面进入到主页时,拦截器会生效并返回ERROR.进而通过配置将浏览器页面定向到ErrorPage.jsp当中.另外一个关键点在于全局拦截器栈和局部拦截器的关系.如果定义了全局默认的拦截器栈.并且action标签当中没有定义任何拦截器,则这个action会默认使用全局拦截器栈,相反,如果在action当中定义了局部拦截器,则全局拦截器不会对这个action起效果.这对于登录拦截比较重要,假设所有action都使用全局拦截器栈,则用户将无法登录(因为拦截器会首先使用session进行判断,没有session则无法登录).



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值