login.jsp页面body中
<s:form action="user_login.action" method="post"> <s:textfield name="username" label="用户名"/> <s:password name="password" label="密码"/> <s:submit value="登陆"/> </s:form>
show.jsp页面body中
有权限登陆后的页面:<s:property value="username"/>---<s:property value="password"/>
只有用户名为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="true" /> <package name="user" namespace="/" extends="struts-default"> <interceptors> <interceptor name="permission" class="cn.axin.interceptor.PermissionInterceptor"/> <interceptor-stack name="permStack"> <interceptor-ref name="defaultStack"/> <interceptor-ref name="permission"/> </interceptor-stack> </interceptors> <!-- 测试:http://localhost:8080/struts2_practice03/login.jsp --> <action name="user_*" class="cn.axin.action.LoginAction" method="{1}"> <result name="login">/show.jsp</result> <result name="back_login">/login.jsp</result> <interceptor-ref name="permStack"/> </action> </package> </struts>
时间: 2024-10-07 04:51:51