您的位置:首页 > 编程语言 > Java开发

Struts 拦截器权限控制【通过拦截器实现登录后跳转到登录前页面】

2014-01-21 13:17 851 查看
应用情形:在web项目中,经常会遇到用户未登录或SESSION失效时用户发出非法的权限操作,如新闻的评论、文件的下载等等,在此我们可以使用struts拦截器对该用户发出的请求进行拦截,拦截后判断用户是否登录或SESSION是否有效,然后进行其正常操作。具体实例如下:

新建一个拦截器类UserInterceptor ,UserInterceptor.java代码如下

[java]
view plaincopyprint?

package com.hsinghsu.test.interceptor;  
  
import com.opensymphony.xwork2.*;  
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;  
import java.util.*;  
import javax.servlet.http.HttpServletRequest;  
import org.apache.struts2.ServletActionContext;  
  
public class UserInterceptor extends AbstractInterceptor {  
  
    private static final long serialVersionUID = 4956767125951165062L;  
  
    // 拦截Action处理的拦截方法  
    public String intercept(ActionInvocation invocation) throws Exception {  
  
        // 取得请求相关的ActionContext实例  
        ActionContext ctx = invocation.getInvocationContext();  
        Map<String, Object> session = ctx.getSession();  
        // 取出名为user的Session属性  
        String user = (String) session.get("user");  
  
        // 如果已经登录,放行  
        if (user != null && user.equals("hsing")) {  
            return invocation.invoke();  
        }  
  
        // 获取HttpServletRequest对象  
        HttpServletRequest req = ServletActionContext.getRequest();  
  
        // 获取此请求的地址  
        String path = req.getRequestURI();  
        System.out.println("path:" + path);  
        // 存入session,方便调用  
        session.put("prePage", path);  
  
        // 没有登录,将服务器提示设置成一个HttpServletRequest属性  
        ctx.put("tip", "您还没有登录,请输入hsing,hsu登录系统");  
  
        // 直接返回login的逻辑视图  
        return "login";  
    }  
}  

package com.hsinghsu.test.interceptor;

import com.opensymphony.xwork2.*;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;

public class UserInterceptor extends AbstractInterceptor {

private static final long serialVersionUID = 4956767125951165062L;

// 拦截Action处理的拦截方法
public String intercept(ActionInvocation invocation) throws Exception {

// 取得请求相关的ActionContext实例
ActionContext ctx = invocation.getInvocationContext();
Map<String, Object> session = ctx.getSession();
// 取出名为user的Session属性
String user = (String) session.get("user");

// 如果已经登录,放行
if (user != null && user.equals("hsing")) {
return invocation.invoke();
}

// 获取HttpServletRequest对象
HttpServletRequest req = ServletActionContext.getRequest();

// 获取此请求的地址
String path = req.getRequestURI();
System.out.println("path:" + path);
// 存入session,方便调用
session.put("prePage", path);

// 没有登录,将服务器提示设置成一个HttpServletRequest属性
ctx.put("tip", "您还没有登录,请输入hsing,hsu登录系统");

// 直接返回login的逻辑视图
return "login";
}
}
新建登录action,LoginAction.java代码如下:

[java]
view plaincopyprint?

package com.hsinghsu.test.action;  
  
import com.opensymphony.xwork2.ActionSupport;  
import com.opensymphony.xwork2.ActionContext;  
  
import java.util.*;  
  
public class LoginAction extends ActionSupport {  
  
    private static final long serialVersionUID = 8013816027944871760L;  
    private String username;// 登录用户名  
    private String password;// 登录密码  
    private String prePage;// 登录前页面  
  
    public String execute() throws Exception {  
          
        if (null != username && null != password && username.equals("hsing") && password.equals("hsu")) {  
  
            ActionContext ctx = ActionContext.getContext();  
            Map<String, Object> session = ctx.getSession();  
              
            //保存用户信息session  
            session.put("user", getUsername());  
  
            // 获取跳转到登陆界面之前的页面地址,由拦截器提供  
            prePage = (String) session.get("prePage");  
  
            // 清除session中的数据  
            session.remove("prePage");  
  
            if (null == prePage) {  
                return "usercenter";// 不是拦截器跳转到登陆页面的,直接访问的登陆页面  
            } else {  
                return SUCCESS;// 是拦截器跳转到登陆登录前页面  
            }  
  
        } else {  
            return INPUT;  
        }  
    }  
  
    public void setUsername(String username) {  
        this.username = username;  
    }  
  
    public String getUsername() {  
        return this.username;  
    }  
  
    public void setPassword(String password) {  
        this.password = password;  
    }  
  
    public String getPassword() {  
        return this.password;  
    }  
  
    public String getPrePage() {  
        return prePage;  
    }  
  
    public void setPrePage(String prePage) {  
        this.prePage = prePage;  
    }  
}  

package com.hsinghsu.test.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext;

import java.util.*;

public class LoginAction extends ActionSupport {

private static final long serialVersionUID = 8013816027944871760L;
private String username;// 登录用户名
private String password;// 登录密码
private String prePage;// 登录前页面

public String execute() throws Exception {

if (null != username && null != password && username.equals("hsing") && password.equals("hsu")) {

ActionContext ctx = ActionContext.getContext();
Map<String, Object> session = ctx.getSession();

//保存用户信息session
session.put("user", getUsername());

// 获取跳转到登陆界面之前的页面地址,由拦截器提供
prePage = (String) session.get("prePage");

// 清除session中的数据
session.remove("prePage");

if (null == prePage) {
return "usercenter";// 不是拦截器跳转到登陆页面的,直接访问的登陆页面
} else {
return SUCCESS;// 是拦截器跳转到登陆登录前页面
}

} else {
return INPUT;
}
}

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

public String getUsername() {
return this.username;
}

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

public String getPassword() {
return this.password;
}

public String getPrePage() {
return prePage;
}

public void setPrePage(String prePage) {
this.prePage = prePage;
}
}
配置拦截器与action映射关系,struts.xml代码如下:

[html]
view plaincopyprint?

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE struts PUBLIC  
    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"  
    "http://struts.apache.org/dtds/struts-2.1.7.dtd">  
<struts>  
    <constant name="struts.custom.i18n.resources" value="globalMessages" />  
    <constant name="struts.i18n.encoding" value="UTF-8" />  
  
    <package name="hsinghsu" extends="struts-default">  
      
        <!-- 用户拦截器定义 -->  
        <interceptors>  
            <interceptor name="userInterceptor" class="com.hsinghsu.test.interceptor.UserInterceptor" />  
        </interceptors>  
  
        <!-- 定义全局result -->  
        <global-results>  
            <result name="login">/jsp/login.jsp</result>  
        </global-results>  
  
        <action name="loginPro" class="com.hsinghsu.test.action.LoginAction">  
            <result name="success" type="redirectAction">${prePage}</result>  
            <result name="input">/jsp/login.jsp</result>  
            <result name="usercenter">/jsp/userCenter.jsp</result>  
        </action>  
          
        <action name="productList">  
            <result name="success">/jsp/productList.jsp</result>  
            <interceptor-ref name="defaultStack" /> <!-- 默认拦截器 -->  
            <interceptor-ref name="userInterceptor" /> <!-- 应用自定义拦截器 -->  
        </action>  
          
    </package>  
</struts>  

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<constant name="struts.custom.i18n.resources" value="globalMessages" />
<constant name="struts.i18n.encoding" value="UTF-8" />

<package name="hsinghsu" extends="struts-default">

<!-- 用户拦截器定义 -->
<interceptors>
<interceptor name="userInterceptor" class="com.hsinghsu.test.interceptor.UserInterceptor" />
</interceptors>

<!-- 定义全局result -->
<global-results>
<result name="login">/jsp/login.jsp</result>
</global-results>

<action name="loginPro" class="com.hsinghsu.test.action.LoginAction">
<result name="success" type="redirectAction">${prePage}</result>
<result name="input">/jsp/login.jsp</result>
<result name="usercenter">/jsp/userCenter.jsp</result>
</action>

<action name="productList">
<result name="success">/jsp/productList.jsp</result>
<interceptor-ref name="defaultStack" /> <!-- 默认拦截器 -->
<interceptor-ref name="userInterceptor" /> <!-- 应用自定义拦截器 -->
</action>

</package>
</struts>
登录页面login.jsp代码如下:

[html]
view plaincopyprint?

<%@ page contentType="text/html; charset=utf-8" language="java"  
    errorPage=""%>  
<%@ taglib prefix="s" uri="/struts-tags"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<title>登录页面</title>  
</head>  
<body>  
    <h3>用户登录</h3>  
    ${tip}  
    <s:form action="loginPro">  
        <s:textfield name="username" label="用户名" />  
        <s:password name="password" label="密码" />  
        <s:submit value="登录" />  
    </s:form>  
</body>  
</html>  

<%@ page contentType="text/html; charset=utf-8" language="java"
errorPage=""%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>登录页面</title>
</head>
<body>
<h3>用户登录</h3>
${tip}
<s:form action="loginPro">
<s:textfield name="username" label="用户名" />
<s:password name="password" label="密码" />
<s:submit value="登录" />
</s:form>
</body>
</html>
产品列表页面productList.jsp代码如下:

[html]
view plaincopyprint?

<%@ page contentType="text/html; charset=utf-8" language="java"  
    errorPage=""%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<title>产品列表</title>  
</head>  
<body>  
    <h2>水果:</h2>  
    苹果<br/> 橘子<br/> 香蕉<br/>  
</body>  
</html>  

<%@ page contentType="text/html; charset=utf-8" language="java"
errorPage=""%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>产品列表</title>
</head>
<body>
<h2>水果:</h2>
苹果<br/> 橘子<br/> 香蕉<br/>
</body>
</html>
用户中心userCenter.jsp代码如下:

[html]
view plaincopyprint?

<%@ page contentType="text/html; charset=utf-8" language="java"  
    errorPage=""%>  
<%@ taglib prefix="s" uri="/struts-tags"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<title>成功页面</title>  
</head>  
<body>个人用户中心,您已经登录!  
</body>  
</html>  

<%@ page contentType="text/html; charset=utf-8" language="java"
errorPage=""%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>成功页面</title>
</head>
<body>个人用户中心,您已经登录!
</body>
</html>
验证:

情形一:若用户未登录,输入http://localhost:8686/testInterceptor/productList.action
则系统会自动跳转到login.jsp页面,进行用户登录,登录后系统会自动跳到productList.jsp前台展现页面。

情形二:若用户已登录,输入http://localhost:8686/testInterceptor/productList.action
则系统直接跳转到productList.jsp前台展现页面。

情形三:若用户未登录,输入http://localhost:8686/testInterceptor/testInterceptor/loginPro.action
则系统会自动跳转到login.jsp页面,进行用户登录,登录后系统会自动跳到userCenter.jsp前台展现页面。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐