首页 > 代码库 > struts2的拦截器的简单使用

struts2的拦截器的简单使用

login.jsp页面body中

<s:form action="user_login.action" method="post">
   		<s:textfield name="username" label="用户名"/>
   		<s:password name="password" label="密码"/>
   		<s:submit value=http://www.mamicode.com/"登陆"/>>

show.jsp页面body中

有权限登陆后的页面:<s:property value=http://www.mamicode.com/"username"/>---

只有用户名为admin和密码为admin时才能登陆显示show.jsp页面,否则都返回到login.jsp页面

LoginAction类是简单处理登陆的action

public class LoginAction extends ActionSupport{
	private String username;
	private String password;
	
	public String login(){
		System.out.println(username+"---"+password);
		return "login";
	}
	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;
	}
	
}

拦截器PermissionInteceptor

public class PermissionInterceptor extends AbstractInterceptor{

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Map<String,Object> params = invocation.getInvocationContext().getParameters();
		String username = null;
		String password = null;
		for(Map.Entry<String, Object> ma : params.entrySet()){
			String key = ma.getKey();
			if(key.equals("username")){
				String[] values = (String[]) params.get(key);
				username = values[0];
			}
			if(key.equals("password")){
				String[] values = (String[]) params.get(key);
				password = values[0];
			}
		}
		if(username.equals("admin")&&password.equals("admin")){
			return invocation.invoke();
		}
		return "back_login";
	}

}

struts.xml的配置

<struts>
	<constant name="struts.devMode" value=http://www.mamicode.com/"true" />>

struts2的拦截器的简单使用