Struts2自定义拦截器实例—登陆权限验证

版本:struts2.1.6

此实例实现功能:用户需要指定用户名登陆,登陆成功进入相应页面执行操作,否则返回到登陆页面进行登陆,当直接访问操作页面(登陆后才能访问的页面)时则不允许,须返回登陆页面。

代码如下:

一、页面

login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> yuewei'Login

User:
Passoword:

welcome.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> yuewei's Welcome

登录成功后显示此页面

show

show.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> yuewei's Show Show This Page 登录后执行此页面

 

二、Action

LoginFormAction

package com.ywjava.action; import com.opensymphony.xwork2.ActionSupport; public class LoginFormAction extends ActionSupport { public String exexcute() { return "success"; } }

LoginAction

package com.ywjava.action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.ywjava.utils.Constants; public class LoginAction extends ActionSupport{ private String username; private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } private boolean isInvalid(String value) { return (value == null || value.length() == 0); } public String execute(){ System.out.println(username); System.out.println(password); if (isInvalid(getUsername())) return INPUT; if (isInvalid(getPassword())) return INPUT; if(this.getUsername().equals("yuewei")&& this.getPassword().equals("yuewei")){ ActionContext.getContext().getSession().put(Constants.USER_SESSION,getUsername()); ActionContext.getContext().getSession().put(Constants.PASS,getPassword()); return "success"; } return "error"; } }

ShowAction

package com.ywjava.action; import com.opensymphony.xwork2.ActionSupport; public class ShowAction extends ActionSupport { public String execute() { return "success"; } }

三、拦截器

package com.ywjava.interceptot; import java.util.Map; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import com.ywjava.utils.Constants; public class LoginInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation invocation) throws Exception { // 取得请求相关的ActionContext实例 ActionContext ctx = invocation.getInvocationContext(); Map session = ctx.getSession(); String user = (String) session.get(Constants.USER_SESSION); // 如果没有登陆,或者登陆所有的用户名不是yuewei,都返回重新登陆 if (user != null && user.equals("yuewei")) { System.out.println("test"); return invocation.invoke(); } ctx.put("tip", "你还没有登录"); return Action.LOGIN; } }

四 struts.xml

/login.jsp /login.jsp /welcome.jsp /login.jsp /login.jsp /show.jsp

你可能感兴趣的:(SSH)