struts2第三回:自定以拦截器

实现一个拦截器并调用。
============下面是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;
}

这样便实现了一个简单的登录验证拦截器
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值