实现一个拦截器并调用。
============下面是LoginIntercepter.java代码===============
============下面是LoginIntercepter.java代码===============
============login.jsp中代码=================
==================action中得代码=======================
这样便实现了一个简单的登录验证拦截器
============下面是LoginIntercepter.java代码===============
package com;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class LoginIntercepter extends AbstractInterceptor {
/**
* 常见问题:进过拦截器后,action里面取不到表单的值了。
* 是因为xml中没有引入默认的defaultStack
*
*/
public String intercept(ActionInvocation arg0) throws Exception {
System.out.println("进入拦截器:LoginIntercepter");
String requestUrl=ServletActionContext.getRequest().getRequestURI();
System.out.println("url:"+requestUrl);
Map session = arg0.getInvocationContext().getSession();
String loginId = (String) session.get("loginId");
if (!(requestUrl.contains("!doLogin")||loginId!=null)) {
//未登录,返回重新登录
return "login";
}
return arg0.invoke();
}
}
============下面是LoginIntercepter.java代码===============
<package name="abc" extends="struts-default">
<!--自己写一个拦截器demo -->
<interceptors>
<interceptor name="loginCheck" class="com.LoginIntercepter"></interceptor>
</interceptors>
<global-results>
<result name="success">/success.jsp</result>
</global-results>
<!-- 标签测试类 -->
<action name="tagTest" class="com.StrutsTagTestAction">
<result name="login">/login.jsp</result>
<interceptor-ref name="loginCheck" /><!--配置登录验证拦截器-->
<interceptor-ref name="defaultStack" /><!--如果自己加入了其他拦截器,则必须手动添加此拦截器,否则在action中会取不到表单的值-->
</action>
</package>
</struts>
============login.jsp中代码=================
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body >
<form action="tagTest!doLogin.action" method="post">
<!-- 文本框,密码框的使用 -->
userName:<input type="text" name="userName"><br/>
passWord:<input type="password" name="passWord" /><br/>
<input type="submit"e value="login">
<form>
</body>
</html>
==================action中得代码=======================
public String doLogin() {
HttpServletRequest requst=ServletActionContext.getRequest();
requst.getSession().setAttribute("loginId","abing");
String content=requst.getParameter("content");
System.out.println("userName:" + userName + "\tpassWord:" + passWord);
return SUCCESS;
}
这样便实现了一个简单的登录验证拦截器