今天没事干看了看struts2.1的拦截器部分,自己做了一个小例子,汇总一下,有需要的朋友也可以看看……
注:有关struts2.1的拦截器的概念东东我就不介绍了,自己可以去查查资料.
下面是本人写的登录实现拦截器的例子:
1. login.jsp
<s:form action="userLoginAction.action" method="post"> Username:<s:textfield name="user.username" /><br> Password:<s:password name="user.password" /><br/> <s:submit value="Submit" /> <s:reset value="Reset" /> </s:form>
2. struts.xml
<package name="User" extends="struts-default">
<!-- 设置自己创建的拦截器栈 -->
<interceptors>
<interceptor name="loginInterceptor" class="org.com.ssh.action.LoginInterceptor"></interceptor>
<interceptor-stack name="loginDefaultStack">
<interceptor-ref name="loginInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<global-results>
<result name="login" type="redirect">/login.jsp</result>
</global-results>
<action name="findUserAction" class="org.com.ssh.action.UserAction" method="FindUser">
<result>/index.jsp</result>
<!-- 此处引用拦截器 -->
<interceptor-ref name="loginDefaultStack"></interceptor-ref>
</action>
<action name="userLoginAction" class="org.com.ssh.action.UserLoginAction" method="UserLogin">
<result name="success">/loginSuc.jsp</result>
<result name="error">/login.jsp</result>
</action>
</package>
注意:配置文件里最好使用全局转发的login代码
struts2 写道
<global-results>
<result name="login" type="redirect">/login.jsp</result>
</global-results>
<result name="login" type="redirect">/login.jsp</result>
</global-results>
3. UserLoginAction.java
private User user;
@Autowired
private UserService userservice;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public UserService getUserservice() {
return userservice;
}
public void setUserservice(UserService userservice) {
this.userservice = userservice;
}
/**
* 验证登录用户是否正确
* @return tipMes
*/
public String UserLogin()
{
String tipMes = "";
//MD5对密码进行加密
MD5 m = new MD5();
user.setPassword(m.getMD5ofStr(user.getPassword()));
Boolean b = userservice.valLogin(user);
if(b == true)
{
user = userservice.FindUserPro(user);
ActionContext.getContext().getSession().put("user", user);
return SUCCESS;
}
else
{
this.addFieldError(tipMes, "您输入的Username或者Password不匹配,请重新输入!");
return ERROR;
}
}
4. LoginInterceptor.java
public class LoginInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext actionContext = invocation.getInvocationContext();
Map session = actionContext.getSession();
User user = (User)session.get("user");
if (user == null){
return Action.LOGIN;
}
else
{
return invocation.invoke();
}
}
}
5. loginSuc.jsp
<body> 登录成功! </body>
OK,简单的登录的拦截器就搞定了!