重定向到Struts 2中的拦截器中的另一个动作 [英] Redirect to another action in an interceptor in struts 2
问题描述
我目前正在学习Struts 2,目前正在构建一个简单的应用程序,将未经验证的用户重定向到登录表单.
I am currently in the process of learning Struts 2 and I am currently building a simple application where unverified users are redirected to a login form.
我有一个登录表单和操作功能,该功能可获取用户凭据,对其进行验证并将其存储在会话中,但是我现在试图在登录之前阻止访问页面,并且我试图这样做带有拦截器.
I have a login form and action functional which takes the users credentials, verifies them and stores a User object in the session however I am now trying to prevent access to pages before the login has taken place and I am trying to do this with an interceptor.
我的问题是我编写了一个拦截器,用于检查User对象是否已保存在会话中,但是如果没有保存,我想重定向到登录页面,并且在不绕过struts的情况下找不到任何方法并使用HttpServletResponse.sendRedirect方法
My problem is that I have written an interceptor that checks whether the User object has been saved in the session but if it has not I want to redirect to the login page and can't find any way of doing this without bypassing struts and using the HttpServletResponse.sendRedirect method
配置:
<package name="mypackage" extends="struts-default" namespace="/admin">
<interceptors>
<interceptor name="login" class="my.LoginInterceptor" />
</interceptors>
<default-interceptor-ref name="login"/>
<action name="login" class="my.LoginAction">
<result name="input">/admin/login.jsp</result>
<result name="success" type="redirect">/admin</result>
</action>
<action name="private" class="my.PrivateAction">
<result>/admin/private.jsp</result>
</action>
</package>
拦截器代码:
@Override
public String intercept(ActionInvocation inv) throws Exception {
Map<String, Object> session = inv.getInvocationContext().getSession();
Object user = session.get("user");
if(user == null) {
// redirect to the 'login' action here
}
else {
return inv.invoke();
}
}
推荐答案
标准方法是返回特殊的全局结果(例如" login ")并定义从该结果到您的全局映射admin/login.jsp
.因此,您只需添加以下行:
The standard way is to return a special global result (eg "login") and define a global mapping from that result to your admin/login.jsp
. So you just must add this line:
if(user == null) {
return "login";
}
在您的struts.xml
中:
<global-results>
<result name="login">/admin/login.jsp</result>
</global-results>
顺便说一句,恐怕您是用单个拦截器替换默认的Struts2拦截器堆栈,通常您想将拦截器 add 添加到堆栈中.例如:
BTW, I'm afraid that you are replacing the default Struts2 interceptor stack with your single interceptor, normally you want to add your interceptor to the stack. Eg:
<interceptors>
<interceptor name="login" class="my.LoginInterceptor" />
<interceptor-stack name="stack-with-login">
<interceptor-ref name="login"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="stack-with-login"/>
BTW2:当然,您不得将拦截器应用于登录操作.
BTW2: You must NOT apply the interceptor to your login action, of course.
这篇关于重定向到Struts 2中的拦截器中的另一个动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!